Contents Lesson 12 of 19

10 min read · professional

Alert rules as data

By the end of this lesson you will have your threshold rules as a document in the store, checked against closed lists of fields and operators on the way in, a pure evaluate that uses the last value to see a crossing, tests for crossing up, crossing down and sitting exactly on the threshold, and every rule shown as a sentence.

Build Your First Tool gave your watchlist threshold rules that ran on render. This lesson makes them documents, which is what lets the next lesson move them somewhere they can actually fire.

The rule document

type Rule = {
  id: string;
  symbol: string;
  field: "close" | "change_p" | "volume";
  op: ">" | "<" | "crosses_above" | "crosses_below";
  value: number;
  enabled: boolean;
  lastFiredAt: number | null;
  lastValue: number | null;
};

Same move as filters in Build a Screener and panels in unit 1: data rather than code. One evaluator reads all of them, and adding a rule is a row rather than a deploy.

field and op are closed sets, validated on read. A rule is a thing your server evaluates and may act on, so it is privileged input and gets the allowlist treatment.

Two of those fields are the interesting ones

lastValue and lastFiredAt are what separate a rule from a comparison.

crosses_above needs lastValue. "Price is above 300" is true on every evaluation while it stays above; "price crossed above 300" is true once. The difference is having the previous observation, and without it you cannot express the thing people actually want.

lastFiredAt is what stops the flood. Next lesson's subject, and the field has to exist in the document from the start or you will be migrating under pressure.

Evaluation is a pure function

function evaluate(rule: Rule, quote: Quote): { fires: boolean; nextLastValue: number };

No I/O, no clock read, no notification. It takes a rule and an observation and returns a verdict plus the new state to store.

That signature is what makes the whole feature testable, and Backtest Strategies's craft applies directly: fixtures for crossing up, crossing down, sitting exactly on the threshold, and a missing field. The exactly-equal case is the one generated code gets wrong, because > and >= both look reasonable and only one matches what you told the user.

Say what the rule watches, in words

Render every rule back as a sentence: "Alert when AAPL.US trades above 320.00 (checked against the last price, not the session close)". Not a row of dropdowns echoing the JSON.

A person reading their own rules a month later needs to know what they asked for. If the sentence is awkward to generate, the rule model is probably wrong — that is a useful design signal and it costs one function.

Try it now

Write the evaluator and its fixtures before any UI, including the exactly-on-the-threshold case. Then ask your assistant what your rule does when the price equals the value precisely, and see whether its answer matches your test.

The prompt

Mock mode on, plan mode on, and paste:

Plan, then build. Turn the Rule in src/lib/rules.ts into this document:

type Rule = {
  id: string;
  symbol: string;
  field: "close" | "change_p" | "volume";
  op: ">" | "<" | "crosses_above" | "crosses_below";
  value: number;
  enabled: boolean;
  lastFiredAt: number | null;
  lastValue: number | null;
};

Add parseRules(raw: unknown), which drops any rule whose
field or operator is not on those lists rather than repairing it. Add a
pure evaluate(rule, quote) that returns { fires, nextLastValue }, reads
no clock and does no I/O. Write the tests first in tests/rules.test.ts
and show me them failing: crossing up, crossing down, exactly on the
threshold, and a quote without the field. Then ruleSentence(rule), which reads like "Alert when AAPL trades
above 320.00 (checked against the last price, not the session close)",
and list every rule on the dashboard with it. Keep the rules as a
"rules" document in the store (add "rules" to the keys its route
accepts), seeded from today's RULES. The home page's alerts must still
work. Mock mode, no new
request. Run npm test, typecheck, lint and check:leak; diff first.

A good answer changes the rules module and its test, adds rules to the keys the store accepts, lists the rules on the dashboard, and leaves the home page's alert line working with a small change at most. Crossing rules cannot fire yet, because nothing writes lastValue back; the next lessons do that.

Check it yourself

  1. The exactly-on-the-threshold test exists, and its name says what you decided: for >, equal does not fire.
  2. In a fresh session, ask the agent what your rule does when the price equals the value: its answer matches the test.
  3. A stored rule with the operator >= is dropped on read, not repaired into something else.
  4. Each rule listed on the dashboard reads as a sentence naming the symbol, the threshold and which price it is checked against.
  5. The home page still shows its alert line in mock mode.
Compare with ours
// src/lib/rules.ts: pure, and the equal case is a decision written down
export function evaluate(rule: Rule, quote: Quote): { fires: boolean; nextLastValue: number | null } {
  const now = quote[rule.field];
  if (typeof now !== "number") return { fires: false, nextLastValue: rule.lastValue };
  const before = rule.lastValue;
  const fires =
    rule.op === ">" ? now > rule.value :
    rule.op === "<" ? now < rule.value :
    rule.op === "crosses_above" ? before !== null && before <= rule.value && now > rule.value :
    before !== null && before >= rule.value && now < rule.value;   // crosses_below
  return { fires, nextLastValue: now };
}

Ours keeps the field name ticker from Build Your First Tool rather than renaming it symbol, so the home page needed no edit. The full state at the end of this unit is on the starter's branch ref/build-a-dashboard/u3.

Checkpoint

npm test && npm run typecheck
git status          # the files you expect, and no .env file
git add -A
git commit -m "Rules as documents: closed fields and operators, a pure evaluate, crossings tested"

Then answer this lesson's questions.