How to add a kill switch to a trading agent with real money
How to add a kill switch to a trading agent with real money. Covers triggers, flattening sequences, testing, and why it is a required safety layer before going live.
- 01A kill switch is an emergency override that cancels orders, flattens positions, and revokes an agent's access in a single action.
- 02It is the final layer of defense above budget caps, position limits, and scoped keys, not a replacement for them.
- 03You should define the trigger, flattening sequence, and recovery path before authorizing live trading, not during an incident.
- 04Test the switch in paper trading first, then validate latency with a live micro-test using minimal capital.
- 05Trading can lose money, including everything, and a kill switch does not guarantee a profitable exit; it only stops the agent from trading further.
A kill switch for an AI trading agent is an emergency control that immediately cancels open orders, flattens existing positions, and revokes the agent's access to your funds. It exists so that you can stop all trading activity instantly when something goes wrong, without relying on the agent to cooperate or to recognize its own malfunction. When real money is at stake, this is not an optional convenience. It is a structural requirement for any non-custodial deployment that handles capital outside of a sandbox.
What does a kill switch actually do?
A kill switch is a single action that triggers a predefined emergency sequence. The sequence typically has three stages. First, it cancels any open orders that have not yet filled, preventing new unintended entries. Second, it submits orders to close any open positions, turning exposure back into cash or stablecoins as quickly as the underlying venue allows. Third, it revokes the scoped API key or credential that the agent uses to trade, so the agent cannot place new orders even if its logic continues running. The goal is not to optimize the exit price. The goal is to remove the agent's ability to trade as fast as possible, because a malfunctioning agent can lose money rapidly, including everything.
The kill switch does not reverse losses that have already occurred. It does not guarantee that flattening orders will fill at the price you expect, especially in thin markets or during volatile periods. It also does not shut down the agent's compute environment. The agent process may keep running, but it loses the authority to move your money. This distinction matters because some developers mistakenly think a kill switch is a form of insurance. It is not. It is a brake, not a seatbelt.
Some systems separate the flatten step from the revocation step. In those designs, you might flatten first and revoke second, or you might revoke first to block new orders while you flatten manually. The difference matters for latency and for markets with low liquidity. If you revoke before flattening, the agent cannot make things worse, but you may need another mechanism to close positions. If you flatten first, the agent might place new orders during the flattening process unless the system has a temporary pause state. The best configuration depends on the market type and the agent's typical position size. For options or prediction markets with wider spreads, a poorly timed flatten can cost more than the original risk. You should decide the sequence before you go live, not during an incident.
How is a kill switch different from a stop loss or exit plan?
An exit plan is a trading strategy. It defines how the agent should close a position under normal or adverse conditions, often with rules about take-profit levels, trailing stops, or time limits. A stop loss is an order type that closes a position when the price reaches a certain level. Both of these are part of the agent's trading logic, and both can fail if the agent itself is malfunctioning, if the market gaps, or if the API connection breaks. A kill switch is not part of the trading logic. It is an override that sits outside the agent, controlled by you or by a separate monitoring process.
Think of the exit plan as the agent's internal navigation system. It works when the agent is healthy. The kill switch is the ejection seat. It works when the agent is not healthy, when you no longer trust the navigation, or when external conditions change so rapidly that you want to stop everything immediately. You can read more about building exit plans in How to build your first automated exit plan and take-profit strategy. You should have both. One does not replace the other.
There is also a difference in scope. A stop loss applies to one position. An exit plan might apply to one strategy or one market. A kill switch applies to the entire agent, across all markets and all positions, in a single action. If your agent trades stocks and perpetual futures simultaneously, the kill switch closes both. This global scope is what makes it an emergency tool rather than a tactical one.
Where does the kill switch sit in the safety stack?
Safety for an agent handling real money works in layers. The outer layer is the wallet architecture itself. Because Felix is non-custodial by construction, the agent trades from a wallet you control, and withdrawal addresses are owner-approved only. The agent can spend within limits but can never withdraw funds to itself. The next layer consists of scoped API keys and budget caps. These limit which markets the agent can access and how much capital it can deploy. Inside that layer are position limits and drawdown controls, which restrict how large any single position can become and how much the portfolio can lose in a given period.
The kill switch sits at the top of this stack as a circuit breaker. It overrides all other permissions. When activated, it does not negotiate with the agent. It does not check whether the current trade looks profitable. It simply executes the emergency sequence. This is why How to trade every market through one API with hard limits the agent cannot cross is relevant background. Hard limits try to prevent problems from occurring. The kill switch assumes a problem has already occurred and acts to contain it.
You should configure the kill switch only after you have set the underlying layers. A kill switch without budget caps or position limits is like a fire extinguisher in a building with no fire doors. It helps, but the fire should not be allowed to spread that far in the first place. The kill switch is the last line of defense, not the first. If you find yourself pulling it frequently, the issue is probably in your position sizing, your strategy logic, or your market data pipeline, not in the absence of more aggressive switches.
How do you configure a kill switch before going live?
Configuring a kill switch means defining the trigger, the sequence, and the recovery path. The trigger is the condition that causes the switch to fire. Triggers fall into two categories: manual and automated. A manual trigger is a button you press when you observe something wrong. An automated trigger fires when a monitoring system detects a condition you predefined, such as a drawdown exceeding your limit, a position size breaching a hard cap, or a number of failed orders in a short window. Automated triggers are useful because you might not be watching the agent when it malfunctions.
The sequence is what happens after the trigger. You must decide whether to cancel, flatten, and revoke in parallel or in a specific order. You must also decide what order type to use for flattening. Market orders typically execute faster but may slip in low liquidity. Limit orders may not fill at all. For a kill switch, most operators prefer immediate execution over price optimization, because the goal is to stop exposure. The recovery path is how you restore access after the switch fires. This should require explicit reauthorization, not just a quick toggle, because you need time to diagnose what went wrong. Some operators require a cooldown period of several hours before a new key can be generated.
Before you authorize live trading, test the entire sequence in paper trading. Paper trading lets you see how fast the flattening executes and whether the revocation actually blocks new orders. Many developers assume their kill switch works because they wrote the code, but latency and venue behavior can differ between simulated and live environments. Review Common mistakes developers make with paper trading for AI agents to avoid false confidence. You should also document the exact steps you would take after the switch fires, including who is responsible for reviewing logs and how you will communicate with any relevant counterparties.
What happens when you pull the kill switch?
When the kill switch activates, the system sends commands to every venue where the agent has open activity. Open orders are cancelled first. Then flattening orders are submitted for each open position. If the agent holds stocks, perps, options, or prediction market shares, each venue receives the appropriate close order normalized into plain US dollar sizing. The system does not wait for the agent to confirm. It acts directly through the API infrastructure.
Once the flattening orders are submitted, the scoped key is revoked. This means the agent cannot place new orders, query balances, or read market data through the trading connection. The agent may still be running in its own environment, but it has no path to your capital. Because the model is non-custodial, the agent cannot move funds to another wallet or withdraw them. Only owner-approved addresses can receive withdrawals. You can read more about this custody model in How an AI agent executes orders while you keep full custody.
After the switch fires, you receive a notification with a summary of what was closed and what the final state of the portfolio looks like. You should then review logs to determine whether the switch fired because of a bug, a market event, or a breach of your safety parameters. Do not reauthorize the agent immediately. Fix the root cause first, then generate a new scoped key with the same or revised limits. If the switch fired because of an automated trigger that was too sensitive, adjust the threshold rather than disabling the trigger entirely.
How do you test a kill switch without losing money?
Testing a kill switch in a live environment is risky by definition, because the test involves real positions and real market impact. The safer approach is to test in paper trading first, then perform a live test with a very small position and a manual trigger. In paper trading, you can simulate the full sequence: open a position, activate the kill switch, and verify that the system cancels, flattens, and revokes as expected. Pay attention to timing. If the flattening step takes too long in simulation, it will likely take longer in live markets.
For a live test, allocate the minimum possible position size, ideally in a liquid market where slippage is low. Trigger the switch manually and observe the latency between each stage. Check that the key revocation happens promptly and that the agent cannot place a new order afterward. Some developers also test partial sequences, such as a revoke-only test that blocks new orders but does not flatten, to practice stopping entries while holding existing positions. This is useful if you want to pause the agent without closing a hedge or a long-term position.
Keep a log of every test, including timestamps and any anomalies. If the flattening orders fail because of a venue-side issue, you need to know that before you rely on the switch in a crisis. The exact request schema is in the docs; the shape looks like this:
{
"action": "trigger_kill_switch",
"scope": "agent_id",
"mode": "flatten_and_revoke",
"key": "YOUR_KEY"
}This is illustrative. The actual fields and endpoints may differ, so consult the documentation before writing any automation. Remember that paper trading cannot perfectly replicate live execution, especially for options or prediction markets where liquidity profiles differ. Use paper tests to validate logic, and use live micro-tests to validate latency and venue behavior.
Why every live agent needs a kill switch from day one
Some developers delay adding a kill switch because they plan to trade small sizes initially or because they trust their agent's logic. This is a mistake. The first live trade is the moment when unknowns become real. A bug that was harmless in paper trading can become expensive with real money, especially in leveraged products like perpetual futures or options. The kill switch does not need to be complex, but it must exist before the first order fills.
You should also treat the kill switch as a living component. Review it when you change the agent's strategy, when you add a new market type, or when you increase the trading budget. A switch that was appropriate for a five hundred dollar test may not be appropriate for a fifty thousand dollar allocation. Update the trigger thresholds, the flattening logic, and the key scopes accordingly. If you run multiple agents, each agent should have its own kill switch as well as a global one that can halt all activity across the portfolio.
Trading can lose money, including everything. No safety system eliminates that risk. The kill switch does not guarantee a profitable exit. It guarantees that you can stop the agent from trading further. That alone makes it essential.
Frequently asked questions
No. A kill switch stops future trading and flattens open positions, but it cannot reverse losses that have already occurred. It is a brake, not a refund mechanism. The price you receive when flattening depends on current market conditions.
You should configure both. A manual switch gives you control when you observe something wrong. An automated switch protects you when you are not watching. Relying on only one leaves a gap in your coverage.
Yes, if configured globally. The switch can cancel orders and submit flattening commands across stocks, crypto, perps, options, and prediction markets in a single action. You can also scope it to a single agent or market if your architecture requires that.
You can test the logic in paper trading, but you should also run a live test with the smallest possible position size. Paper trading validates sequence logic, while a live micro-test validates latency and venue behavior. Neither guarantees identical results, but together they reduce uncertainty.
A manual revocation only blocks new orders. A kill switch is a predefined sequence that usually includes cancelling open orders, flattening positions, and then revoking access. The sequence ensures you do not leave orphaned positions or unfilled orders after you pull the switch.
It depends on the number of venues, the latency of each venue, and the sequence you chose. Cancellation and flattening happen at network speed, but market orders still require matching. The revocation itself is typically near instant. You should test your specific setup to measure the real delay.
Give your agent a key.
One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.
Most automated trading is done by bots, but agents that connect through MCP are something else entirely. This article explains the architectural and operational differences in plain language.
Connect an AI agent to five market types through a single API. Hard limits on capital, position size, and loss are enforced in the wallet layer, so the agent cannot override them even if its instructions drift.