Kill Switch for a Trading Bot: Build a Dead Man's Switch That Survives a Crash
An in-process kill switch dies with the process it is meant to kill, so a frequently-restarting system silently disarms its own safety. Here is why a systematic book needs a graded de-risk ladder plus an out-of-process backstop, and a dead man's switch that alarms on silence, not just on error. War-stories about a breaker that reset on every restart and a halt that never reached the node.
The most dangerous piece of safety code I ever shipped into Titan, my live multi-strategy system, passed every test I wrote for it and then quietly switched itself off at the exact moment I needed it. It was a drawdown breaker with a companion safety counter, and both lived in memory. Cross the loss limit, the breaker trips and halts the book; count too many rejected orders in a window, the counter halts too. Clean, tested, green on every path. What I had not internalised is that a breaker living inside the process it is meant to stop carries a fatal dependency: it dies whenever that process dies. And Titan restarts. A deploy, a crash, an out-of-memory kill at 3am, a routine redeploy: every one of those wiped the counter back to zero and reset the drawdown state to "all clear". The system came back up believing nothing had ever gone wrong.
My safety mechanism was disarming itself on every restart. Worse, it disarmed most reliably in precisely the conditions a safety net exists for: the more unstable the system was, the more it crashed and restarted, the more often the net vanished. That is the whole essay in one bug. A kill switch that lives inside the thing it kills is not a kill switch. It is a suggestion that holds only while the thing it guards is healthy, which is exactly the state in which you do not need it.
Why the in-process switch is the default, and why it is a trap
Every kill-switch example you will find in a public trading-bot repo is in-process. It is a flag the strategy loop checks each bar, or a try/except that flattens on error. This is the natural thing to write, because the code that knows your live drawdown, your open positions and your reject rate is the trading code, so the check that reacts to them lives right there next to the data. It is convenient, it is granular, and it is fast. It is also structurally blind to the two failure modes that matter most.
The first is the one that bit me: state that does not outlive the process. A counter in a variable, a breaker whose "tripped" flag is a boolean in memory, a high-water mark held in RAM. None of it survives a restart, so a system that restarts more often than it trades safely can never accumulate the very history the safety logic is reasoning about. The fix for that half is persistence: the halt is a file, or a row, or a KV entry that a fresh boot reads before it arms anything, and it boots halted if the file says halted. Fail-closed on restart, not fail-open.
The second is deeper, and persistence alone does not solve it: the switch only runs when the loop that hosts it runs. An in-process check is invoked from the per-bar handler. No bar, no handler, no check. If the data feed stalls, or a handler throws before it reaches the risk line, or the event loop wedges, the process is alive but the safety is dormant, and it is dormant at the worst possible time. You cannot fix a "the guard did not get a turn" bug by making the guard remember more. The guard has to run somewhere the wedge cannot reach.
The shape of the fix: a ladder, not a switch
Before the switch can live in the right place, it has to be the right shape. A single line, "if drawdown exceeds X, flatten everything", is brittle for reasons I unpack at length in the book, but the short version is that it reacts only after the loss is realised, it is all-or-nothing against a risk that is actually a continuum, and it can flap itself on and off so fast it becomes the thing that costs you money. The replacement is a graded de-risk ladder, where each rung does less damage than the one below it and fires earlier, and each lower rung exists only to catch what the rung above missed.
Figure
The graded de-risk ladder
Each rung fires deeper than the one above and does less damage. The first four live inside the trading process; the last lives outside it.
- 1
Normal
full size
- 2
Throttle
shave size, keep trading
- 3
Pre-emptive flatten
close the worst sleeves
- 4
In-process hard kill
halt all and persist the halt
- 5
Out-of-process backstop
an independent arbiter trips the same halt
A safety that shares the failure cannot be the last line. The backstop lives outside the process it guards.
The figure shows the four rungs. A throttle comes first: shave position size, keep trading, because a modest run of correlated losses does not warrant abandoning the book. If the hole keeps deepening, a pre-emptive flatten closes the most risk-heavy sleeves, bleeding off exposure well above the kill line so the blunt stop rarely has to fire at all. Only past that does the in-process hard kill halt the whole book, zero the size scale and persist the halt. And beneath all of it sits the rung nobody ships: an out-of-process backstop, an independent arbiter in its own process, tripping the same persisted halt a little deeper again. The exact trigger levels, the spacing between rungs and the hysteresis bands are deployment parameters I keep for the book, because publishing them would be publishing Titan's risk posture. The transferable part is the ordering, and the fact that the deepest rung is not code inside your trading process at all.
Read the ladder top to bottom and one property jumps out. The first three rungs share a single point of failure: they are all inside the trading process, invoked by the same loop. If that loop is the thing that broke, all three are gone together. The fourth rung is the only one that does not share the fault, and that is the entire reason it exists.
The backstop has to live outside the thing it guards
Figure
In-process kill versus out-of-process backstop
Both write to one persisted halt file that a fresh boot reads to come up halted.
In-process kill
fast, granular, fragile
The per-bar handler checks drawdown and trips the halt. Fast and precise, but it dies with the loop that calls it: a wedged event loop or a stalled feed leaves it dormant just when you need it.
Out-of-process backstop
slower, blunter, unkillable
A separate process on its own timer polls the broker's net liquidation value directly and trips the same persisted halt at a slightly deeper threshold, over a two-poll confirm. It cannot be wedged by the trading loop.
The most dangerous state is silence, so the last line of defence must live where the silence cannot reach it.
This panel is the load-bearing picture of the piece. On the left, the in-process kill: the per-bar handler checks drawdown and trips the halt. Fast, granular, and it dies with the loop that calls it. On the right, the out-of-process backstop: a separate process, on its own timer, polling account net liquidation value directly from the broker and tripping the same halt at a slightly deeper threshold, confirmed over two polls so a single bad tick cannot fire it. It is slower and blunter than the in-process check. It is also unkillable by a wedged event loop, because it is not in that loop. When the trading process is spinning happily but blind, the backstop is the only thing still watching your money.
Building the second process is the easy half. Wiring it correctly is where I got burned a second time, and the failure is instructive because everything looked right. The backstop tripped, dutifully flattened, and wrote its halt file. The node then restarted and came straight back up trading, exactly what fail-closed loading was supposed to prevent. The two halves of the system agreed perfectly on the protocol and disagreed silently on the filesystem: the backstop, running on the host, wrote the halt to the host filesystem, while the containerised risk manager read the halt from a volume mounted inside the container. The backstop was writing "STOP" somewhere the reader never looked. An out-of-process control must write its halt where the in-process reader actually reads it, same shared volume, same path, or you have two programs that agree on a handshake and never touch. The only way I trust that wiring now is to test the round-trip end to end: trip the backstop, restart the node, and assert it boots halted.
Silence is the most dangerous state
There is one failure the whole ladder above still misses, and it is the one that scares me most. Every rung, even the out-of-process backstop, is triggered by something the system observes going wrong: a drawdown crossing a line, an NLV reading past a threshold. But the state that hurt me worst was not a bad reading. It was no reading at all. The bar pipeline died once with the process still alive: the event loop spun, no exception was thrown, and simply no new bars arrived. Every drawdown control was wired to fire inside the per-bar handler, so with no bars there was no handler, and with no handler there was no check. The book sat fully exposed with every safety rung dormant and nothing in the process aware anything was wrong. The realised loss stayed bounded only because positions happened to be small that day. That is luck, not safety.
The lesson is that an error is a signal you can catch, but silence is not, and silence is more dangerous precisely because nothing raises it. So you need a control whose trigger is the absence of activity: a dead man's switch. The trading process emits a heartbeat on a fixed cadence, a timestamp written somewhere durable each cycle. A watcher, in its own process, alarms and force-restarts when that heartbeat goes stale past a tolerance. It does not wait for an error, because a wedged loop never throws one. It treats a heartbeat that has stopped as the emergency, on the principle that a process which is alive is not the same as a process which is working. Pair it with the out-of-process backstop and you have covered both shapes of failure: the backstop stops you when the numbers go bad, the dead man's switch stops you when the numbers stop coming.
The portable rule
If you take one thing from this piece, take a design constraint, not a threshold. A safety mechanism must live outside the thing it is meant to stop, and it must alarm on silence, not only on error. The two clauses fix the two failure modes directly. "Outside the thing it stops" kills the in-process trap: a switch that dies with its host, and state that resets on every restart, both fail this test, and both are the default you will write if you do not fight it. "Alarm on silence" kills the dormant-guard trap: any control that only fires on an observed bad value is blind to the most dangerous state a system can be in, which is dark and saying nothing.
Hold every safety control you own up to that constraint and score it honestly. Where does its state live, and does that state survive a restart? What loop invokes it, and what happens to the control if that loop is the thing that broke? And what fires if the control simply never runs, if the whole stack goes quiet? If the honest answer to the last question is "nothing", you do not have a kill switch. You have a switch that works right up until the moment it is the only thing standing between you and the market, and then it is gone.
The graded ladder, the exact rung spacing and hysteresis, the heartbeat cadence and staleness tolerances, the two-poll confirmation, and the round-trip halt-file test are all in the book: Building a Production Quant Trading System works through the layered safety net and the alerting that survives the thing it watches as full chapters, with the schema and the runbook. A sanitised skeleton of the out-of-process arbiter and the persisted-halt loader lives in the Apache-2.0 framework on GitHub. If these field notes are useful, the newsletter is where the next one lands.
This is an engineering essay, not investment advice, and it contains no tradable strategy. All figures and thresholds are illustrative and sanitised, and the war-stories are about bugs and losses, not profits.
Figure
The graded de-risk ladder
Each rung fires deeper than the one above and does less damage. The first four live inside the trading process; the last lives outside it.
- 1
Normal
full size
- 2
Throttle
shave size, keep trading
- 3
Pre-emptive flatten
close the worst sleeves
- 4
In-process hard kill
halt all and persist the halt
- 5
Out-of-process backstop
an independent arbiter trips the same halt
A safety that shares the failure cannot be the last line. The backstop lives outside the process it guards.
Figure
In-process kill versus out-of-process backstop
Both write to one persisted halt file that a fresh boot reads to come up halted.
In-process kill
fast, granular, fragile
The per-bar handler checks drawdown and trips the halt. Fast and precise, but it dies with the loop that calls it: a wedged event loop or a stalled feed leaves it dormant just when you need it.
Out-of-process backstop
slower, blunter, unkillable
A separate process on its own timer polls the broker's net liquidation value directly and trips the same persisted halt at a slightly deeper threshold, over a two-poll confirm. It cannot be wedged by the trading loop.
The most dangerous state is silence, so the last line of defence must live where the silence cannot reach it.
Further reading
- Fail Closed Data Validation: Why a Trading Bot Should Refuse to Boot on Bad Data
Its safety sibling: both are fail-closed disciplines, one for bad data, one for a runaway loss, and both must survive a restart.
- Suspicion Over Celebration: Inside "Building a Production Quant Trading System"
The exact ladder rungs, thresholds and the out-of-process arbiter are in the book.
Related posts
Fractional Kelly Position Sizing: Why the Kelly Criterion Is a Leverage, Not a Weight
The Kelly criterion for position sizing does not hand you a 0-to-1 portfolio weight. It hands you a leverage multiple, and for a high-Sharpe, low-vol edge that number comes out at many multiples of your equity. Read it as a weight and you starve a real edge; deploy the raw leverage and you detonate the account. Here is the war-story that taught me to run a fraction of Kelly, and the one rule I now size everything on.
Purged Cross-Validation and Train/Serve Skew: Four Gates Before an ML Model Trades
When the strategy is a machine-learning model, standard validation lies to you: overlapping labels leak across a naive k-fold split and manufacture a phantom score. Here are the four mechanism-level gates I make any live ML model clear before it touches capital, and the war-story of a model that looked excellent until I purged and embargoed the folds and watched it collapse.
Cannot Trade a US ETF in the UK: Streaming Data, PRIIPs and the Substitute Pattern
Under PRIIPs, a UK or EU retail account can stream a US-listed ETF's market data yet be forbidden from ever holding it, because the fund publishes no Key Information Document. Here is the production pattern I use when my cleanest signal lives on an instrument I am not allowed to trade: compute the signal on the data-only line, trade a UCITS substitute, and match the substitute on currency, not just correlation. The broker catalogue, not the alpha, defines your tradable universe.