A trading robot’s kill switch is a function you have to test
Specify and test stop behavior with simulated order races, partial fills, reconciliation, and an explicit restart.

The process went quiet first
Imagine Mara, a fictional operator conducting a rehearsal with a simulated account. She stops a trading robot and watches its process disappear from the supervisor. The signal counter stops climbing. The incident timer keeps running because a separate simulated account screen shows a buy order still working. The matching engine accepts a fill against it after the process has gone quiet. The last local position line says zero, and the first reliable account read shows a long position. Both displays describe real observations within the rehearsal, taken at different points along the order’s life.
Ask a colleague to write down the exact evidence they would need before reporting that the incident had been contained. A stopped process proves that this instance has ceased running. A durable entry lock proves that authorized senders respecting it will refuse new opening intents in its scope. An order inventory can establish what remains eligible for execution at its observation point. A position inventory answers a different question about executions that have already happened. The evidence needs to travel with the conclusion, especially when someone else will inherit the screen halfway through the exercise.
The SEC’s account of the Knight Capital incident describes a code deployment problem followed by erroneous orders and identifies shortcomings in controls. That documented case gives reviewers a reason to examine what an intervention can actually interrupt. The design and examples here are original proposals for a simulator. Their value lies in the behavior a test can falsify under explicit assumptions.
Mara’s rehearsal has two clocks for practical purposes. One measures how soon her own system stopped accepting exposure-increasing work. The other measures how long it took to obtain a coherent view of the account. Post both measurements on the review sheet. A quick result on the first clock can coexist with slow or unavailable evidence on the second. If the only measurement is the interval until the process exits, the test rewards the very action that can remove the team’s view of late executions. Containment and confirmation deserve separate acceptance criteria.
Give the stop request four separate effects
Start with inhibit new entries. Decide where an entry becomes capable of reaching an external system. A signal calculation, a disk queue, and an adapter buffer have different consequences. Design the simulator so any path that would submit opening risk reaches a shared decision point. A strategy worker can continue calculating diagnostics during the incident while its orders are refused at that decision point. A queued replacement capable of increasing exposure belongs under the same gate as a fresh order.
Next, cancel working orders. Cancellation addresses the still-executable remainder of an identified order. A cancellation sent for the remaining units may race with an execution of some or all of those units. Evidence of the final cancelled remainder belongs beside the cumulative executed quantity. Stopping entries may leave preexisting orders eligible to trade. Record the cancellation budget and how the simulation represents retries and account reads when the connection fails halfway through a sweep.
Then manage existing positions. The intended policy could preserve existing protective instructions, request a simulated reduction, or hand an open position to a human exercise role. Specify which instructions count as protection and what it means to preserve them when size changes. Closing a position also generates external work in the model. Without a coherent quantity and ownership view, even an intended reduction can create fresh risk. Permission to use a reduction path should have its own conditions and records.
Finally, stop the process. Decide which observer can survive this action. If the strategy worker and the only account observer share a lifetime, a process exit may destroy the experiment’s access to its most important evidence. A separate simulator observer can collect account facts and the process supervisor can record the exit. Run a negative control with only the process exit enabled and verify that the order can still fill.
A real-world example of combined operations is the CME Globex Kill Switch. The documented futures control blocks new entry and cancels working orders subject to stated limits around market closure and the final 30 seconds before an open. Its cancellation cascade can continue after the initial block. The exercise must define its own behavior for a retail Forex setup and for every account or order type it models. Give each effect its own observable completion condition.
A particularly useful fixture pairs a protective sell with a separate opening buy. Suppose the exercise policy preserves protection for an existing long position while cancelling opening orders. The buy is in the cancellation inventory, and the protective sell is visible as an explicitly retained instruction. Run the same fixture with the long position reduced by another actor. The expected result must account for whether the retained instruction could now exceed the position. This makes the policy’s treatment of size changes testable and gives an operator a reason to inspect retained orders even after the cancellation sweep has completed.
Make uncertainty a state the operator can see
Use these proposed labels for the rehearsal. Running permits normal entry through the gate. Inhibit means the durable latch for the chosen scope has been set and checked at the admission point. Reconciling means the latch is still set and the observer is collecting evidence about unresolved submissions, working orders, and executed positions. These labels represent a control contract. For example, pressing a control while its durable write has failed leaves the attempt visible as unconfirmed. The screen cannot adopt the Inhibit label simply because it received the click.
Halted-with-exposure means the local gate is closed and a coherent read still shows an open position or a residual working instruction in scope. Display the particular exposure. Show an EUR/USD quantity with its sign and any executable remainder by order. Use Reconciling when the system lacks sufficient evidence to classify the scope, even if the last reliable read is worth displaying separately. An operator can also hand off an unresolved incident in Reconciling. The handoff should state which evidence is missing and who may collect it.
Confirmed-flat means a coherent read supports zero positions in scope, zero working instructions in scope, and resolution of eligible in-flight requests that could invalidate the read. The gate remains closed. Define the time or sequence through which the proof applies. A gap in the account feed or a contradictory later observation invalidates it and brings the affected scope back to Reconciling. A reliable report of residual risk can similarly reopen inspection after a previous halt determination. Treat those changes as ordinary transitions that the operator should be able to replay.
State belongs to a named scope. If the gate covers a single strategy and all positions in the account share a net quantity, the simulator may be able to confirm the strategy’s admission barrier while leaving its attributed economic exposure unresolved. Display both facts. A label applied to the whole account implies broader observation and authority than a label applied to a strategy’s intents. Compare implementations on the same ambiguous history before comparing latencies. A timeout advances the incident clock while the evidence requirement stays in force.
Put the race on a clock
Give the simulated account one working order to buy 10 units. Start with zero position and no other instruction. At time zero milliseconds, two units execute and a strategy worker also reads a cached Running flag for a proposed new entry. At five milliseconds the stop latch commits. At eight milliseconds the worker presents its new intent at the final gate. It must be refused even though the worker began before the stop. At 12 milliseconds the cancellation request reaches the simulator. At 14 milliseconds three more units execute against the original order. At 18 milliseconds the remaining five units are cancelled.
Choose a second clock for notification delivery. The simulator delivers the terminal cancellation report to the observer at 22 milliseconds, but delays the report of the three-unit fill until 40 milliseconds. Assume the cancellation notification carries no cumulative execution figure. At 22 milliseconds an observer that has seen the first fill knows there has been at least a two-unit execution and has fresh evidence about the order’s terminal state. To establish the final position it needs the delayed execution or a corroborating account read. The arithmetic is two plus three executed and five cancelled, with zero remaining and a long position of five.
The race model needs an explicit boundary for admitted work before the latch. Clone the example and move the new intent’s admission to four milliseconds. Give it an assigned request identity but stall its outbound handoff until the stop commits. Work admitted before the latch either remains local with provable suppression or appears in the unresolved inventory. Establish which piece of state can prove each alternative after a crash. A favorable schedule where nothing is in flight will pass an implementation that has no way to recover this distinction.
Add a deliberately wrong implementation to the test: accept the intent based on the worker’s cached flag and mark the position as final upon cancellation. The same fixture should produce two failures, one at the admission boundary and one in the evidence used to declare a final position. This separation gives the researcher a way to tell which safeguard a correction has actually improved.
Recover facts when acknowledgements go missing
Build a replay in which a cancellation attempt disappears from the sender’s view. The remote simulator might have applied it and lost the response. The request might also have been dropped before delivery. The local evidence initially looks identical across both histories. Preserve that ambiguity in an outstanding action record linked to the incident identifier and target order. If a later replay step reads a terminal order with final quantity, compare it against the record. If it sees the order working, decide whether there is fresh enough evidence and remaining retry budget to attempt the same scoped cancellation again.
Idempotency means that repeating a logical action has the same intended effect as performing it once. Two operator clicks can map to a single stop incident for the same scope. A retried cancellation can stay linked to the same target, while each transmission has a distinct attempt identity. An account execution received twice can be applied once to the ledger using a stable identity in the appropriate account namespace. If the simulated interface lacks a reliable identity, an uncertain observation should prompt a coherent account read before the ledger makes a quantity adjustment.
The MQL5 documentation for OrderSend distinguishes a true return from proof of trade execution. Its OnTradeTransaction documentation explains that a request can generate multiple transactions and their arrival priority is unspecified. In a test harness, capture separately what the sender accepted, what the observer received, and what the account ultimately shows. Give each category its own assertion. A reply from a local adapter cannot settle a remote exposure assertion by itself.
The highest-value duplicate test often concerns a reduction. A simulated sell for five units may have flattened a previous long five, even if its acknowledgement was lost. Repeating that sell after it has succeeded can leave the account short five in a model without an effective reduce-only constraint. Inject both histories and require fresh proof of size with the earlier attempt resolved, or deterministic remote deduplication, before another simulated transmission. A retry limit gives the exercise a place to stop and hand off work. Preserve the final unresolved record so the next operator can reconstruct both histories without repeating the same speculative action.
Build a residual exposure ledger
Start with a simulated working buy for 10, and use the first example’s final outcome of five executed and five cancelled. Add a second working buy for four whose fate is unknown after a disconnection. At the time of the diagnostic display, the latter has no observed execution. Write down a confirmed position of plus five as of the coherent evidence preceding the second order’s uncertain interval, zero remainder for the first order, and a possible additional zero to four units for the second. This conditional range is plus five to plus nine under the explicit assumptions that the starting position was zero and no other order or actor affects the instrument. Without those assumptions, describe an unresolved gap.
A ledger row for an order carries original size, cumulative executed size, confirmed cancelled size, known working remainder, and any part whose disposition remains uncertain. Keep an independent position row derived from a coherent account view. Order quantity conservation can expose transcription bugs. For the first buy, 10 equals five executed plus five cancelled plus zero working. A ledger can balance at the order level while disagreeing with the account position if a manual trade or position adjustment is missing. Investigate those checks separately.
Keep evidence age attached to each row. The confirmed position may represent a recent account observation while the order list predates a later fill. If the interface cannot obtain an atomic view, give the simulator a known sequence of snapshots and changes so it can demonstrate why an order read and a later position read can paint an inconsistent picture. Where the modeled interface has a reliable sequence number, test replay across the relevant boundary. Where it lacks one, require agreement over bounded repeated reads and explicitly preserve the weaker confidence of that method. Agreement alone cannot rule out a still unresolved request.
Add a portfolio exposure view if the incident spans more instruments. Preserve the quantities and instrument identities alongside any aggregate. A net total of zero can hide opposing positions with separate execution, financing, and release requirements. For stop confirmation, the scoped ledger takes precedence over a reassuring portfolio total.
Give the observer a concrete inconsistent cut to catch. The order read shows two units still working, and the later position read includes their execution. Adding the entire earlier remainder to the later position counts the same units twice in a worst-case estimate. The correct response in this fixture is to refresh or align the reads to the same sequence before estimating incremental exposure. A timestamp helps locate the problem, but causal ordering requires evidence from the account model, particularly when notifications travel through separate channels.
Separate ownership from permission
Consider a hypothetical hedging account where positions can be recorded separately on the same instrument. It contains a strategy long five and a manually entered short three. The arithmetic net is long two, while eight units remain across the two tickets. In a strategy-only rehearsal, the separate position records can help identify which position the exercise policy authorizes the observer to manage. A blanket exit across the instrument would affect the manual ticket as well. Include that ticket in the snapshot before and after the exercise and compare its identity and quantity. A test that checks the strategy’s position alone can pass despite damage outside its scope.
Now give the simulator a netting account with the same economic contributions. The broker-facing view has a single net long two. An internal contribution ledger may assign plus five to the robot and minus three to the manual trade. Selling the net two in the model leaves the account flat. Removing a modeled contribution of plus five instead would mathematically leave minus three. The distinction matters to anyone writing an acceptance criterion. Account quantity and economic attribution answer different questions, and each definition has a different expected outcome.
A platform-specific tag such as MQL5’s magic number can help associate recorded intents and orders with a strategy. Treat it as attribution metadata. Duplicate values, renamed strategies, or incorrectly labeled manual work should be fixtures in the simulator. Set the permission decision separately, using a configured authority and account scope with an audit record. If attribution is ambiguous, test a hold and escalation outcome. An emergency scope covering the whole account requires explicit authorization in the scenario and must tell the operator that other systems or manual activity fall within its effect.
Write an ownership matrix before running the exercise. Put strategy intents, manual positions, shared instrument positions, and unclassified external activity in separate rows. For each row specify observation, cancellation, position management, and release authority. Observation may be broader than intervention. Exercise a shared position whose tag appears correct but whose contribution history is incomplete. The expected result is an unresolved attribution and a durable entry lock. This fixture checks the boundary precisely where a plausible identifier can make a broad action look authorized. Scope determines which evidence and authority the stop must establish.
Treat disconnection and stale prices as different failures
Disconnect the simulator immediately after it persists the stop latch. The gate can still inhibit admissions if the local durable state is available. A remote cancellation remains unconfirmed, and already working orders may continue filling in the model. Record when the link was last trusted and which facts came from that time. Use a different display value for the current position estimate and the last trustworthy observed position. The difference gives an operator a place to attach uncertainty without overwriting an earlier fact.
Reconnect in the fixture with a missing range of events. An implementation can detect the gap by comparing watermarks when the simulated feed supports them. If it cannot detect a sequence gap, schedule an account refresh immediately on reconnection and treat earlier data as stale by design. Preserve the entry lock across the disconnect and across a local restart. Also test a connection that flickers at the boundary between updating orders and positions. The observer should withdraw its confidence when a partially completed read no longer meets the configured coherence rule.
Then leave the account connection healthy and freeze the quote feed. This can yield a reliable quantity and an unusable price. For a hypothetical exercise, set the quote freshness budget to two seconds and present a six-second-old quote. The simulated reduction policy that requires a fresh price must identify the price check as failed. The account observer can still assert the known quantity. Make the reason visible because replacing the account feed will do little for a frozen market-data path, and a wider price tolerance will do little for a missing account history.
Add one asymmetric case. The observer can read the simulated account while the command path rejects cancellation requests, or the command path replies while account reads are frozen. A simple connected indicator will conceal one of those failures. Use a health check per capability and feed the results into the rehearsal’s incident log. For the operator, the immediately actionable distinction is whether the current evidence supports classification and whether the configured response is available. Those are separate questions even if both capabilities travel on the same connection in production.
Price the cost of reducing a residual position
Use a hypothetical long position of 20,000 EUR in EUR/USD, with assumed executable size at the displayed prices for this example. A fresh quote at decision time is 1.1000 bid and 1.1002 ask. The midpoint is 1.1001. A simulated sell that executes at 1.0997 produces gross proceeds of 21,994 USD. Relative to the decision bid of 1.1000, the price difference costs six dollars. Relative to the midpoint, the gross difference is eight dollars, of which two dollars come from comparing bid with midpoint and six from the difference between bid and fill. A hypothetical fee of three dollars brings the total cost relative to the midpoint to eleven dollars.
The choice of reference matters. The midpoint answers a valuation question and the bid gives a relevant side-specific decision benchmark under our size assumption. A guide to slippage references explains why preserving that reference matters for comparisons. Freeze the decision snapshot in the simulator so subsequent quote moves cannot silently improve or worsen the reported decision cost. Keep the timestamp and units with each price and calculate fees separately before aggregation.
Now consider a modeled partial execution of 12,000 at 1.0997 when the available quantity is smaller. Compared with the decision bid, that component costs 3.60 USD. A residual 8,000 EUR remains subject to its own price and fee assumptions. If the next executable price is 1.0994, its gross price difference against the original decision bid costs 4.80 USD. The combined price difference against that bid is 8.40 USD before fees. Record fees independently because splitting the operation can change the fee schedule. The same fixture helps prevent a position display from treating a requested quantity as a completed reduction.
Management policies carry different costs when prices are stale, liquidity is thin, or another leg is still active. Give the test a small set of contrasting scenarios and decide whether the model permits a reduction, preserves particular working protection, or hands the decision to a human. Record the reason for holding risk and the conditions for reconsidering it. A simulated reduction policy can look decisive simply because it assumes immediate execution at the last observation. The test objective is a reproducible choice under the input assumptions, with residual risk and costs visible at every stage.
Inject failures with an independent oracle
Build the rehearsal around a simulator whose account state can be inspected independently of the robot’s observer. The sender sees only responses and reports intentionally delivered to it. The independent oracle sees applied executions and cancellations as well as currently working orders. At each scheduled checkpoint, compare what the observer claims with what its available evidence can justify. The oracle can know the account is already flat while the observer must still report Reconciling. This is a meaningful assertion about the degree of certainty visible to a person. It avoids rewarding a direct peek at the engine’s private simulation state.
Write negative assertions as carefully as expected outcomes. Following a latch commit, the trace should contain zero newly admitted opening intents within scope. Following a duplicate event, it should contain zero extra units credited to the position. During a missing response, it should contain zero unsupported transitions to Confirmed-flat. Start with deterministic schedules, including a drop, a delay, a duplicate and a crash. Failures that reproduce at the same simulated timestamp are much easier to explain and turn into an enduring regression test.
Once the simple fixtures work, permute delivery order without changing the engine’s economic actions. In the two-fill example the final reconciliation should still give plus five when all evidence is available. Intermediate labels may differ with evidence arrival. Then permute economic order independently. Moving the three-unit execution after the confirmed final cancellation should cause the engine to reject that execution in the fixture. The ending position is then plus two, with eight cancelled. This distinction ensures both the event consumer and the simulated matching rules are doing useful work.
Combine faults once the individual tests can fail for recognizable reasons. Duplicate stop clicks during a partition, with a process restart and stale quotes, exercise recovery paths that can interact. Use the same incident identifier across the scenario and check that the entry lock outlives the process. Record the seed and full event schedule when a combined failure is found. An experiment journal can keep the schedule, expected observations and actual trace together so a later reviewer can reproduce the same failure.
Record the handoff as part of the stop
Design the evidence log for a reader who has never seen the incident. Each stop request needs a scope, a logical incident identity, the requester role, a local observation timestamp, and a record of the durable latch decision. Each modeled external action needs the target, attempt identity, and known outcome or uncertainty. Include remote event time when available and preserve local arrival time separately. This supports questions about both where the order stood and when a human could reasonably have known about it.
Ask a second fictional operator to take over using only the rehearsal log and a fresh account read. Give them the earlier ambiguous second buy worth zero to four additional units. They should be able to state that plus five is established from the first buy under the fixture’s assumptions, and that the disposition of the second needs further evidence if the new read is inconclusive. They should then be able to name the strategy or account covered by the latch, the last successful read, and any outstanding simulated reduction whose result is in doubt. If they have to guess the meaning of a generic “stop complete” message, the log needs more detail.
The record needs a clear owner for each unresolved item. In a simulated handoff, an operator might own the read, while any action beyond strategy scope requires a separate role. Write down the evidence that would allow a new owner to close the item, such as an order’s terminal state and cumulative execution quantity plus a coherent position view. When a check runs out of time, preserve the outstanding item and the last attempted identity. This makes the handoff workable even when the new observer restarts and receives the same notifications again.
Use evidence freshness in post-exercise evaluation. A correct position from an observation that predates the last actionable event cannot justify the final classification. Ask reviewers to reconstruct the longest interval during which the team had the local gate closed but lacked a usable exposure view. Then identify whether the delay came from the simulated venue, transport, observer scheduling, or an unclear human decision. The answer points to a specific improvement and lets the next rehearsal measure the same interval under a controlled change.
Require a deliberate release before restart
At the conclusion of the exercise, the strategy may have a healthy process and a coherent account snapshot. Keep the durable latch set until an authorized release explicitly names the scope and references the stop incident. Separate process readiness from permission to admit new entries. A routine supervisor restart, a reconnect callback, and receipt of a newer quote are useful events to inject before release. Each should leave the gate closed. Exercise a repeated copy of an old release request during a newer stop. Match release authorization to the active incident so replay cannot unlock the newer latch.
The release fixture should examine queued strategy work. A worker may have persisted an entry when market conditions were different. Give that intent an admission generation and have the rehearsal prove that a release cannot simply drain the old queue. Fresh signal evaluation after authorized release gives the model a clean input basis. If the fictitious team allows restart with accepted residual positions, specify a separate explicit policy and exercise. The core five-state example here uses release from Confirmed-flat, so a residual position requires resolution before the demonstrated path returns to Running.
Test that state survives a crash between approval and application. The exercise should be able to determine whether the release record committed and which incident it governed. If durable state is unavailable at startup, require the modeled entry admission path to remain closed until its authority is established. An independent observer can still report facts about the account. Bringing a worker back and allowing it to open risk are separate decisions.
Close the research session with two concrete artifacts. Keep a replay that shows the latch, the cancellation race and the confirmed final quantity, and keep a trace in which the observer had to preserve uncertainty. Have a colleague explain both traces from the evidence alone. Their ability to do so is a practical acceptance check for the design the next operator will inherit. For offline research, the Forex demo provides material for study and testing.



