Episode 42 · AI Trading · Building a Complete Trading System

A health report for a demo system: stale data isn't drift

Write thresholds first for quote age, spread, gaps, duplicates and unknown orders; block entries on operational faults and only flag drift for review.

When do you have to stop a demo system, and how is an operational fault different from drift (the data’s distribution changing)?

This post writes the thresholds down first, for quote age, spread, duplicates and orders in an unknown state, each with the action it allows. Then a script turns a snapshot of the system into a report you can send to Telegram. The easy mistake: reacting to a few losing trades. That’s far too small a sample; never let the AI change parameters, retrain or raise the lot size because of it.

Terms used below:

  • Drift: a change in the data’s distribution, or in the relation the model relies on. It needs a defined measurement.
  • Heartbeat: a regular “still alive” message from the bot. It says the process runs, nothing about the data.
  • Quote age: how long ago the last price arrived.
  • PSI (population stability index): one common drift measure. It compares how a feature’s recent values spread across bins with how a reference window spread across the same bins. Around 0 means similar; larger means more different.
  • Runbook: the written list of what to do for each alert.

Thresholds and actions, written first

Pick the metric windows and thresholds beforehand: bar gaps, quote age, spread, duplicates, orders in an unknown state, features outside the trained range. Telegram carries a heartbeat and exception reports, and never a secret. Don’t retrain or raise risk on your own because of a few losses. Every alert has its action in the runbook: wait, stop taking entries, or reconcile the demo.

The thresholds, config/health.json, committed before the system runs:

{
  "rule_version": "ema-cross-v1",
  "model_hash": "3f9a1c0e",
  "display_timezone": "UTC",
  "max_quote_age_s": 120,
  "max_spread_points": 50,
  "max_bar_gap_minutes": 30,
  "max_duplicates_today": 3,
  "max_unknown_orders": 0,
  "feature_range": {"rsi14": [0, 100], "ret5_pct": [-3.0, 3.0]},
  "min_feature_coverage": 0.95,
  "drift_feature": "ret5_pct",
  "drift_psi_flag": 0.25,
  "drift_min_window": 200,
  "min_matured_for_comparison": 30
}

The report groups its fields so data, model, execution and reporting stay apart. A field without enough data says unavailable; it never shows a zero that looks like a measurement.

Group Fields
Identity event_id, as_of_utc, display_timezone, rule_version
Data data_age_seconds, feature_coverage
Model model_hash, drift_state, baseline_comparison
Finished outcomes matured_outcomes
Demo execution pending_orders, position_reconciliation, execution_errors
Reporting notifier_status; a Telegram failure must never trigger a retry that duplicates an order

The bot is alive but the data is old

  • The heartbeat passes every minute, but the quote hasn’t changed in 10 minutes: the bot is alive and the data is stale.
  • A heartbeat never stands in for quote freshness.
  • Past the quote-age threshold you chose, block new entries and log it.
  • Report the symbol, the time of the last data and the DEMO status.
  • Resume only after the check procedure passes, with the cause written down.
Step What
1 Heartbeat
2 Quote freshness
3 Alert
4 Stop, then resume

Worked example: stop for infrastructure, or for the model?

Operational fault Drift (the distribution changed)
30 minutes of missing data A feature or the forecasts’ distribution shifted
Spread above the limit Reference window, measure and threshold set beforehand
An order whose state can’t be confirmed Goes to review as a flag
Block new signals now; don’t wait for the P/L Never retrain on your own and raise the size

The bot loses 30 minutes of data, sees a spread above its limit, or can’t confirm an order’s state. Those are operational faults, which may need new signals blocked at once under your policy, without waiting for the day’s P/L. Log freshness, latency, the duplicate count, rejects and the reconciliation state separately.

Drift in a feature or in the distribution of forecasts is a different problem. Set the reference window, the measure and the threshold beforehand. A losing week doesn’t prove drift, and drift doesn’t prove the strategy will lose. Put the flag into a review; don’t retrain automatically and raise the size to make up for it.

The script, src/health.py. Every operational check adds a block reason; drift only adds a review flag; the heartbeat is reported but never gates anything:

# src/health.py: turn a snapshot of the demo system into a health report with thresholds written beforehand.
# Operational failures block new entries at once; drift only raises a flag for review. Reads files only.
#   .venv\Scripts\python src\health.py config\health.json data\snapshot.json
import json, math, sys
from datetime import datetime, timezone

UNAVAILABLE = "unavailable"


def ts(s):
    return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)


def psi(reference, recent, bins=10):
    """Population stability index of `recent` against `reference`, with bins cut at the reference's deciles."""
    ref = sorted(reference)
    edges = [ref[int(len(ref) * i / bins)] for i in range(1, bins)]
    def shares(xs):
        counts = [0] * bins
        for x in xs:
            counts[sum(x > e for e in edges)] += 1
        return [max(c / len(xs), 1e-4) for c in counts]
    a, b = shares(reference), shares(recent)
    return sum((q - p) * math.log(q / p) for p, q in zip(a, b))


def report(cfg, snap):
    now = ts(snap["as_of_utc"])
    blocks, flags = [], []
    age = (now - ts(snap["last_quote_utc"])).total_seconds()
    if age > cfg["max_quote_age_s"]:
        blocks.append(f"quote {age:.0f} s old > {cfg['max_quote_age_s']} s")
    if snap["spread_points"] > cfg["max_spread_points"]:
        blocks.append(f"spread {snap['spread_points']} > {cfg['max_spread_points']} points")
    if snap["largest_bar_gap_minutes"] > cfg["max_bar_gap_minutes"]:
        blocks.append(f"bar gap {snap['largest_bar_gap_minutes']} min > {cfg['max_bar_gap_minutes']} min")
    if snap["duplicates_today"] > cfg["max_duplicates_today"]:
        blocks.append(f"{snap['duplicates_today']} duplicate events today")
    unknown = [o for o in snap["orders"] if o["state"] == "unknown"]
    if len(unknown) > cfg["max_unknown_orders"]:
        blocks.append(f"{len(unknown)} order(s) in unknown state")
    if snap["running_model_hash"] != cfg["model_hash"]:
        blocks.append(f"model {snap['running_model_hash']} is not the approved {cfg['model_hash']}")
    if not snap["positions_match_terminal"]:
        blocks.append("positions don't match the terminal")

    feats = snap["recent_features"]
    inside = [all(lo <= f[k] <= hi for k, (lo, hi) in cfg["feature_range"].items()) for f in feats]
    coverage = sum(inside) / len(inside) if inside else 0.0
    if coverage < cfg["min_feature_coverage"]:
        blocks.append(f"only {coverage:.0%} of recent bars have features inside the trained range")

    key, ref = cfg["drift_feature"], snap["reference_feature_values"]
    recent = [f[key] for f in feats]
    if len(recent) < cfg["drift_min_window"]:
        drift = UNAVAILABLE
    else:
        value = psi(ref, recent)
        drift = f"PSI {value:.2f}" + (" FLAG: review" if value > cfg["drift_psi_flag"] else " ok")
        if value > cfg["drift_psi_flag"]:
            flags.append(f"drift on {key}: PSI {value:.2f} > {cfg['drift_psi_flag']} (review, no automatic action)")

    m = snap["matured"]
    comparison = (UNAVAILABLE if m["n"] < cfg["min_matured_for_comparison"]
                  else f"model {m['model_mean_r']:+.2f}R vs baseline {m['baseline_mean_r']:+.2f}R on {m['n']}")
    return {
        "event_id": f"health-{now:%Y%m%dT%H%MZ}",
        "as_of_utc": snap["as_of_utc"],
        "display_timezone": cfg["display_timezone"],
        "rule_version": cfg["rule_version"],
        "model_hash": snap["running_model_hash"],
        "data_age_seconds": round(age),
        "heartbeat_age_seconds": round((now - ts(snap["heartbeat_utc"])).total_seconds()),   # reported, never a gate
        "feature_coverage": round(coverage, 3),
        "matured_outcomes": m["n"],
        "baseline_comparison": comparison,
        "drift_state": drift,
        "pending_orders": len(snap["orders"]),
        "position_reconciliation": "match" if snap["positions_match_terminal"] else "MISMATCH",
        "execution_errors": snap["execution_errors_today"],
        "notifier_status": snap["notifier_last_ok"],
        "entries": "BLOCKED" if blocks else "allowed",
        "block_reasons": blocks,
        "review_flags": flags,
    }


def telegram_text(r):
    lines = [f"DEMO | health {r['as_of_utc']} UTC | {r['rule_version']} | model {r['model_hash']}",
             f"new entries: {r['entries']}"]
    lines += [f"  block: {b}" for b in r["block_reasons"]]
    lines += [f"  review: {f}" for f in r["review_flags"]]
    lines.append(f"heartbeat {r['heartbeat_age_seconds']} s ago | data age {r['data_age_seconds']} s | coverage {r['feature_coverage']:.0%} | drift {r['drift_state']}")
    lines.append(f"matured {r['matured_outcomes']} | vs baseline: {r['baseline_comparison']}")
    lines.append(f"orders {r['pending_orders']} | positions {r['position_reconciliation']} | errors {r['execution_errors']}")
    return "\n".join(lines)


def can_resume(checks):
    """After a stop: every box ticked, or stay stopped. 'Bot online' is not one of the boxes."""
    needed = ["new_requests_blocked", "pending_and_positions_recorded", "data_reconciled", "account_reconciled",
              "cause_written_down"]
    missing = [k for k in needed if not checks.get(k)]
    return (not missing), missing


if __name__ == "__main__":
    cfg = json.load(open(sys.argv[1]))
    r = report(cfg, json.load(open(sys.argv[2])))
    print(telegram_text(r))

A snapshot is whatever your collector writes: times, spread, gaps, orders, the model hash and recent feature values. Shortened (the real lists hold 240 recent bars and 1,000 reference values):

{
 "as_of_utc": "2026-12-02T10:00:00Z",
 "heartbeat_utc": "2026-12-02T09:59:40Z",
 "last_quote_utc": "2026-12-02T09:59:58Z",
 "spread_points": 28,
 "largest_bar_gap_minutes": 0,
 "duplicates_today": 0,
 "orders": [],
 "running_model_hash": "3f9a1c0e",
 "positions_match_terminal": true,
 "execution_errors_today": 0,
 "notifier_last_ok": "2026-12-02T09:00:03Z",
 "recent_features": [
  {
   "rsi14": 52.7,
   "ret5_pct": -0.077
  },
  {
   "rsi14": 47.4,
   "ret5_pct": 0.051
  }
 ],
 "reference_feature_values": [
  0.149,
  1.013,
  0.438
 ],
 "matured": {
  "n": 18,
  "model_mean_r": 0.12,
  "baseline_mean_r": 0.05
 }
}

The full report for that snapshot, every schema field included:

{
 "event_id": "health-20261202T1000Z",
 "as_of_utc": "2026-12-02T10:00:00Z",
 "display_timezone": "UTC",
 "rule_version": "ema-cross-v1",
 "model_hash": "3f9a1c0e",
 "data_age_seconds": 2,
 "heartbeat_age_seconds": 20,
 "feature_coverage": 1.0,
 "matured_outcomes": 18,
 "baseline_comparison": "unavailable",
 "drift_state": "PSI 0.07 ok",
 "pending_orders": 0,
 "position_reconciliation": "match",
 "execution_errors": 0,
 "notifier_status": "2026-12-02T09:00:03Z",
 "entries": "allowed",
 "block_reasons": [],
 "review_flags": []
}

Five made-up situations, as their Telegram text:

== 1 normal
DEMO | health 2026-12-02T10:00:00Z UTC | ema-cross-v1 | model 3f9a1c0e
new entries: allowed
heartbeat 20 s ago | data age 2 s | coverage 100% | drift PSI 0.07 ok
matured 18 | vs baseline: unavailable
orders 0 | positions match | errors 0

== 2 heartbeat fine, quote 10 minutes old
DEMO | health 2026-12-02T10:00:00Z UTC | ema-cross-v1 | model 3f9a1c0e
new entries: BLOCKED
  block: quote 600 s old > 120 s
heartbeat 20 s ago | data age 600 s | coverage 100% | drift PSI 0.07 ok
matured 18 | vs baseline: unavailable
orders 0 | positions match | errors 0

== 3 data gap of 35 minutes
DEMO | health 2026-12-02T10:00:00Z UTC | ema-cross-v1 | model 3f9a1c0e
new entries: BLOCKED
  block: bar gap 35 min > 30 min
heartbeat 20 s ago | data age 1 s | coverage 100% | drift PSI 0.07 ok
matured 18 | vs baseline: unavailable
orders 0 | positions match | errors 0

== 4 drift, nothing broken
DEMO | health 2026-12-02T10:00:00Z UTC | ema-cross-v1 | model 3f9a1c0e
new entries: allowed
  review: drift on ret5_pct: PSI 0.54 > 0.25 (review, no automatic action)
heartbeat 20 s ago | data age 2 s | coverage 100% | drift PSI 0.54 FLAG: review
matured 41 | vs baseline: model -0.08R vs baseline +0.02R on 41
orders 0 | positions match | errors 0

== 5 unknown order and a different model
DEMO | health 2026-12-02T10:00:00Z UTC | ema-cross-v1 | model 77b20d41
new entries: BLOCKED
  block: 1 order(s) in unknown state
  block: model 77b20d41 is not the approved 3f9a1c0e
heartbeat 20 s ago | data age 2 s | coverage 100% | drift PSI 0.07 ok
matured 18 | vs baseline: unavailable
orders 1 | positions match | errors 0

What each one shows:

  1. Normal: entries allowed. Only 18 finished outcomes, so the comparison with the baseline says unavailable rather than showing a number from too few trades.
  2. Stale quote: the heartbeat is 20 s old, so the bot looks fine, but the last price is 10 minutes old. Entries blocked.
  3. Data gap: 35 minutes of missing bars. Blocked, although the current quote is fresh.
  4. Drift: PSI 0.54 on the 5-bar return, and the model trails the baseline on 41 outcomes. Entries are still allowed; the flag goes to a review. Nothing retrains and nothing changes size.
  5. Unknown order and a different model: two block reasons at once. The running model isn’t the approved hash, and one order needs reconciling before anything new is sent.

Send the text with send() from src/notifier.py in the Telegram post. A failed send is logged; resending a report never touches an order.

Test the stop button on demo: block new requests, record the pending orders and open positions, and follow the written procedure. Turning it back on requires the data and the account to be reconciled. A “bot online” message doesn’t prove the system resynchronised after a reconnect. can_resume turns that into a checklist:

can resume: False | missing: ['account_reconciled']
Gate Question If not
Input The stop was pressed on demo
1 New requests blocked? Block new requests first
2 Pending orders and open positions recorded? Record them as the procedure says
3 Data reconciled? Don’t turn it back on
4 Account state reconciled? Don’t turn it back on
Passed Resume, with the cause written down

The tests, tests/test_health.py:

# tests/test_health.py: what blocks entries, what only raises a flag, and what stays unavailable.
import json, random
from pathlib import Path

from src.health import can_resume, psi, report, telegram_text

CFG = json.load(open(Path(__file__).resolve().parent.parent / "config" / "health.json"))
rnd = random.Random(1)
REF = [rnd.gauss(0, 0.4) for _ in range(1000)]


def snap(**change):
    s = dict(as_of_utc="2026-12-02T10:00:00Z", heartbeat_utc="2026-12-02T09:59:50Z",
             last_quote_utc="2026-12-02T09:59:58Z", spread_points=20, largest_bar_gap_minutes=0, duplicates_today=0,
             orders=[], running_model_hash=CFG["model_hash"], positions_match_terminal=True, execution_errors_today=0,
             notifier_last_ok="2026-12-02T09:00:00Z",
             recent_features=[{"rsi14": 50, "ret5_pct": rnd.gauss(0, 0.4)} for _ in range(240)],
             reference_feature_values=REF, matured=dict(n=10, model_mean_r=0.1, baseline_mean_r=0.0))
    s.update(change)
    return s


def test_fresh_heartbeat_does_not_save_a_stale_quote():
    r = report(CFG, snap(last_quote_utc="2026-12-02T09:50:00Z"))
    assert r["entries"] == "BLOCKED" and r["heartbeat_age_seconds"] == 10


def test_unknown_order_and_model_mismatch_block():
    r = report(CFG, snap(orders=[{"state": "unknown"}], running_model_hash="other"))
    assert r["entries"] == "BLOCKED" and len(r["block_reasons"]) == 2


def test_drift_flags_but_does_not_block():
    wide = [{"rsi14": 50, "ret5_pct": rnd.gauss(0, 0.9)} for _ in range(240)]
    for f in wide:
        f["ret5_pct"] = max(-3.0, min(3.0, f["ret5_pct"]))     # keep inside the trained range
    r = report(CFG, snap(recent_features=wide))
    assert r["entries"] == "allowed" and r["review_flags"] and "FLAG" in r["drift_state"]


def test_too_few_samples_are_unavailable_not_zero():
    r = report(CFG, snap(recent_features=[{"rsi14": 50, "ret5_pct": 0.1}] * 50))
    assert r["drift_state"] == "unavailable" and r["baseline_comparison"] == "unavailable"


def test_psi_is_small_for_the_same_distribution():
    assert psi(REF, [rnd.gauss(0, 0.4) for _ in range(1000)]) < 0.05


def test_resume_needs_every_box():
    ok, missing = can_resume(dict(new_requests_blocked=True, pending_and_positions_recorded=True,
                                  data_reconciled=True, account_reconciled=True, cause_written_down=False))
    assert not ok and missing == ["cause_written_down"]


def test_report_text_has_no_secret_fields():
    text = telegram_text(report(CFG, snap()))
    assert text.startswith("DEMO") and "token" not in text.lower() and "password" not in text.lower()

Run .venv\Scripts\python -m pytest -q tests; you should see 7 passed.

Try it: a read-only health report design

Design a read-only demo report for Telegram; don't create a token or send real messages yet. JSON schema: event_id, as_of_utc, display_timezone, rule_version, model_hash, data_age_seconds, feature_coverage, matured_outcomes, baseline_comparison, drift_state, pending_orders, position_reconciliation, execution_errors, notifier_status. Don't use confidence as an entry signal. Explain how each field is computed and which must return unavailable when there isn't enough data. On missing data or a model mismatch, lock new entries but keep managing positions under the rulebook; a Telegram failure must be logged and must not trigger a retry that duplicates orders. Write one normal report, one with missing data, and a test table for restart, timeout and duplicate. Don't read keys, don't call the real Telegram, and don't connect a live account.

Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.

The order to work in:

  1. Separate data drift, model error, execution error and reporting failure; each gets its own threshold and reason.
  2. Make a Telegram template with no secrets: UTC and the time zone, the version, data freshness, finished samples, alerts and the demo state.
  3. Test missing bars or volume, a label not yet finished, a model version change and a Telegram failure; never retrain on live data and switch orders back on by yourself.

Key takeaways

  • The heartbeat still passes when quotes haven’t updated for 10 minutes; a stale price blocks new orders, and you only switch back on after reconciling.
  • 30 minutes of missing data is an operational fault, not drift: block new signals at once, without waiting for the day’s P/L.
  • Drift needs a reference window, a measure and a threshold chosen beforehand; a drift flag goes to a review, never to reversing or piling into trades.

Comments