Systematic Trading Field Guide
10.3 · From backtest to live

Position limits, kill switches, unattended failure modes

~15 min read
Mechanism

Safety limits must be enforced by machinery outside the strategy code, because the failure you have to survive is precisely the one where the strategy code is the thing that has gone mad. A layered set of hard limits — per-order, per-position, per-day — plus one tested, independent flatten-everything switch converts your worst software failure from an unbounded loss into a bounded, pre-priced one.

The idea

On 1 August 2012, Knight Capital — at the time one of the largest market makers in US equities — deployed new order-routing code to production. The deployment went wrong, and stale code that was never meant to run in production began firing orders on its own logic. Over the next 45 minutes, before anyone effectively intervened, the firm sent more than 4 million orders and traded roughly 397 million shares it did not intend to trade, losing more than $460 million — most of the firm's capital — and Knight had to be rescued by outside investors within days. The SEC's enforcement action (U.S. Securities and Exchange Commission 2013) — which fined the firm $12 million for violating the market access rule that requires broker-dealers to have pre-trade risk controls — reads like a checklist of everything this lesson is about: the risk controls that would have capped the damage existed as a regulatory concept but not as working machinery; the warning signals existed but weren't wired to anything that could act.

Sit with the shape of that disaster, because it is the shape that should organise all your safety thinking. Knight's strategy wasn't wrong. Their deployment was wrong, and once it was wrong, every downstream layer that could have contained it was either absent or too slow. The lethal failures of automated trading are almost never "the model made a bad prediction" — bad predictions are priced into the whole enterprise. They are "the system did something no sane version of the strategy would ever do, at machine speed, for longer than any human could notice and react." A 45-minute failure at machine speed is tens of thousands of decisions. Your defence cannot be attention; you don't have a risk desk, and you sleep. Your defence is architecture.

The architecture is defence in depth — concentric rings, each assuming every ring inside it has failed:

Ring 1: per-order sanity checks. Before any order leaves the process: is the size below a hard per-order maximum? Is the limit price within a collar of the last known market price (say, a few percent)? Is the order rate normal — if the engine normally sends a dozen orders a day and has just tried to send fifty in a minute, something upstream is broken, and the fiftieth order is not a trade, it's a symptom? Knight's failure mode was, at bottom, an order-rate failure that nothing was counting.

Ring 2: position and exposure limits. After every fill and every reconciliation cycle: is any single-instrument position beyond its cap? Is gross exposure beyond the account's cap? These limits are set from the sizing work of module 4 — the point here is only that they are enforced, mechanically, by code that does not import the strategy and cannot be argued with by it.

Ring 3: state-of-the-world breakers. Data staleness (the feed's last tick is older than a threshold — trading on a frozen price is trading blind); reconciliation failure (lesson 10.1's diffs breached — the engine provably disagrees with reality); daily loss beyond a bound. Any of these trips the system into a safe state.

Ring 4: the kill switch itself. One command — a script, a big red alias — that flattens every position and cancels every working order by talking directly to the broker's API, sharing nothing with the strategy stack: not its process, not its data feed, ideally not even its API session. It must work when the main system is hung, wedged, or lying. And it must be tested — a kill switch that has never been fired is a hypothesis, and the moment you need it is the worst possible moment to run the experiment for the first time.

What should a tripped breaker actually do — freeze, or flatten? The answer differs by ring, and it's worth deciding in daylight. Freeze (cancel working orders, send nothing new, hold positions) is right when the doubt is about the machinery: stale data, reconciliation breaks, order- rate anomalies. Your positions were presumably sane an hour ago; the new information is only that the machine can no longer be trusted to change them sanely. Flatten is right when the doubt is about risk: the daily loss bound, a margin call approaching, a position limit breached by a fat fill. There, holding is itself the hazard. Encode the choice per trigger, in the runbook, so that at 3 a.m. neither you nor the machine has to exercise judgement.

One more ring exists outside all of yours: the market's own. Exchanges halt trading on circuit breakers, and — the relevant lesson for your design — liquidity can evaporate faster than any halt. The Flash Crash of 6 May 2010 is the canonical study: Kirilenko, Kyle, Samadi and Tuzun (Kirilenko, Kyle, Samadi & Tuzun 2017) document how, as order flow turned one-sided, market makers withdrew and orders executed against a nearly empty book, with prints far from any sensible value, until trading paused and liquidity returned. Two design consequences. First, your emergency exits should use limit orders with generous collars, not naked market orders — in an evaporated book a market order is a donation. Second, your breakers should distinguish "my system is broken" from "the market is broken": a market-wide dislocation with your machinery healthy argues for freezing and waiting, not for flattening into the worst prints of the decade.

The maths

Deliberately little. Safety limits should be simple enough to audit at a glance, and the arithmetic is all in the calibration:

Order rate. If normal operation sends at most nn orders per hour, alarm at knkn with kk of 3–5 and hard-stop at 10n10n. The gap between alarm and stop is your investigation window.

Per-order size. Cap at the largest order the strategy could legitimately need — the full rebalance of your largest position — plus modest headroom. With target weight wmax⁡w_{\max}, NAV VV and a headroom factor h≈1.5h \approx 1.5: Qmax⁡=h wmax⁡V/PQ_{\max} = h \, w_{\max} V / P for price PP. Anything larger cannot be a sane instruction, only a bug or a fat finger.

Daily loss bound. Set it where a healthy day essentially never goes: 4–5 daily standard deviations. At σd=σ/252\sigma_d = \sigma/\sqrt{252} — for a 12% vol book, about 0.75% a day — a 4σ bound is a 3% day. A healthy strategy loses 3% in a day rarely (heavy tails granted, more often than the Gaussian 1-in-16,000 — which is exactly why this is a breaker and not a forecast); a broken one can do it in minutes. The point of setting it wide is that this breaker flattens, and false flattens are expensive.

The cost of the switch. A breaker that flattens on a false alarm costs you round-trip transaction costs plus re-entry timing luck; a breaker that fails on a true fault costs you Knight. The asymmetry is so extreme that every marginal calibration decision should lean toward tripping. You are not optimising expected P&L here; you are buying insurance against unbounded left tails with small known premiums.

Worked example

Worked example — a limits sheet for a £100k, 10-instrument futures book

The entire safety spec fits on one page, which is the point — it must be auditable in one sitting. Vol target 12%, normal operation ≈ 5 orders/day, largest target weight 20% of NAV:

RingTriggerActionEnforced byTested
1Order size beyond 1.5× largest legitimate rebalanceReject order, pageEngine gatewayMonthly, synthetic order
1Limit price beyond 3% collar of last markReject order, pageEngine gatewayMonthly
1More than 20 orders/hourReject and freeze, pageEngine gatewayMonthly
2Any position beyond 1.5× its target capFlatten excessWatchdog processQuarterly, paper
2Gross exposure beyond 2.5× NAVFreeze, pageWatchdogQuarterly
3Data staleness beyond 10 min in market hoursFreezeWatchdogMonthly (unplug feed)
3Recon diff beyond hard tolerance (10.1)Freeze, pageNightly reconWith recon drills
3Daily P&L below −3%Flatten allWatchdogQuarterly, paper
4Manual: one commandFlatten all, cancel allStandalone scriptQuarterly, one micro contract live

The watchdog is deliberately dumb — under a hundred lines, no strategy imports, its own broker session:

# watchdog.py — separate process, separate box if possible; illustrative
while True:
    pos   = broker.positions()          # reality, direct from the API
    marks = broker.marks()              # broker's prices, not your feed
    if stale(marks, limit_min=10):          freeze("stale marks")
    if gross_exposure(pos, marks) > 2.5:    freeze("gross cap")
    if day_pnl(pos, marks) < -0.03 * nav(): flatten_all("daily loss bound")
    for sym, q in pos.items():
        if abs(q) > CAP[sym] * 1.5:         flatten_excess(sym, "position cap")
    heartbeat()                         # absence alarms externally (10.1)
    sleep(30)

Walk through why each design choice is what it is. The watchdog reads positions and prices from the broker, not from your engine — if the engine's world-model is the thing that's broken, a watchdog fed by the engine is broken with it. It runs as a separate process so a hung engine can't hang it. flatten_all is the same standalone script as the manual kill switch — one code path for the most important action, exercised by both the machine and you. And the quarterly live test with a single micro contract is non-negotiable: it proves the API credentials, permissions, contract mappings and order types all still work — the four things that silently rot while a script sits untested — at a cost of a few pounds of spread. Knight's 45 minutes are what the untested version of this paragraph costs at institutional scale (U.S. Securities and Exchange Commission 2013).

How you'd use it

  1. Write the limits sheet before the first live order, as part of the deployment doc (lesson 1.10's pre-registration discipline applied to ops). Every limit has a number, an action, an owner process, and a test cadence. Going live without it is going live with your account as the limit.
  2. Fire-drill on a calendar. Monthly for the cheap drills (synthetic bad orders, unplugged feed), quarterly for the full kill-switch test with one micro contract. Put the drills in the same calendar as your attribution ritual (10.2); systems maintained by mood decay by mood. Carver (Carver 2015) is good on this temperament: the reliability of a solo systematic operation is mostly the reliability of its habits.
  3. Change limits like you change strategy code — deliberately, in writing, in calm weather, never mid-incident. The post-incident review may conclude a limit was too tight; loosen it the following week, with the reasoning logged. A limit loosened during the incident it interrupted has stopped being a limit.
  4. After any trip, reconcile before resuming. The breaker fired because something was untrustworthy; run the full 10.1 reconciliation, find the cause, and only then re-arm. Resuming on "it looks fine now" converts your circuit breaker into a snooze button.

What goes wrong

The switch shares the failure. The commonest fatal design: kill logic living inside the strategy process, reading the strategy's data feed, using the strategy's API session. The engine hangs — and takes its own executioner down with it. Independence is the entire value: separate process, direct broker data, own credentials, ideally a second machine or a phone app as the path of last resort. Audit this by asking, for each failure you can imagine: what still works?

Untested rot. API versions change, credentials expire, permissions get narrowed, a contract code rolls. Every one of these will happily wait to reveal itself until the night you need the script. The quarterly micro-lot drill exists because "the kill switch is tested" and "the kill switch ran in March" must be the same sentence.

Breaker interactions. Your vol-targeting (lesson 4.1) deleverages into rising vol; your drawdown breaker (here and lesson 10.4) also deleverages; stacked naively they can double-cut and turn a bad week into a flat book at the exact bottom. Decide the precedence explicitly — usually: safety breakers override sizing rules, but sizing rules should already have made the safety trip unlikely. Simulate the stack once (a stress replay of 2020 March through your rules) so the interaction is a design, not a surprise.

Whipsaw resentment. The daily-loss breaker fires, flattens, and the market bounces; the strategy "would have" recovered and the breaker "cost" you 2%. This will happen, repeatedly, and each time it will argue for widening the limit. Do the accounting honestly: the breaker's premium is these small whipsaw losses; its payout is the Knight scenario. Insurance that never pays a premium isn't insurance. Price the whipsaws into your expected returns and stop renegotiating after each one.

The 3 a.m. override. The page arrives, you're groggy, the system wants to flatten, and you — certain it's a false alarm — override. Sometimes you're right, which is the trap: each successful override lowers the bar for the next, until the night you override the true positive. The pre-commitment that works: the machine's action stands; your override happens the next day, in daylight, after reconciliation, as a re-entry decision rather than a cancellation. You can always get back in tomorrow. Knight never got their $460 million back (U.S. Securities and Exchange Commission 2013).

Further reading