Does Your Trading Bot Have an Off Switch?
Every automated trading system eventually does something its owner did not intend. A data feed glitches, a deployment goes wrong, or a rule fires in a loop. The question then is not whether the strategy is any good, but whether the system can be stopped quickly and completely.
“I’d switch the computer off” stops the program, but often leaves orders working at the broker or exchange. This article covers what a proper off switch has to do, the limits that should trigger it, and how to build one into an Expert Advisor, a TradingView-to-broker bridge and an exchange bot.
What a Kill Switch Actually Has to Do
The futures industry body FIA publishes best practices for automated trading safeguards. It defines a kill switch as a control that, when activated, “immediately disables all trading activity for a particular participant or group of participants, typically preventing the ability to enter new orders and cancelling all working orders”. It adds that a kill switch “also may allow for risk-reducing orders while preventing risk-increasing orders” (FIA, Best Practices for Automated Trading Risk Controls and System Safeguards, July 2024).
So a kill switch has two halves: stop anything new going out, and cancel what is already resting in the market. FIA also encourages firms to build their own, fine-grained enough to stop individual trading systems.
The EU and UK technical standard for algorithmic trading firms, RTS 6, says the same in legal language: a firm must be able to “cancel immediately, as an emergency measure, any or all of its unexecuted orders” (Commission Delegated Regulation (EU) 2017/589, Article 12). Most traders are not regulated firms, but it is a useful checklist.
Why Stopping the Program Is Not Enough
In MetaTrader 5, pending orders wait on the broker’s trade server and stop-loss levels are executed there too, unlike a trailing stop, which runs in the terminal (MetaTrader 5 Help, Types of Orders). So removing the EA does not remove its pending orders or protective stops. MetaQuotes’ documentation for ExpertRemove() makes another point clear: the EA “is not stopped immediately”. The call only sets a flag, so no further events are processed, OnDeinit() runs and the EA is unloaded (MQL5 Reference, ExpertRemove). Nothing in that sequence deletes orders or closes positions on its own.
The terminal’s Algo Trading button is similar. MetaTrader 5’s help says that turning it off disables automated trading for all Expert Advisors, and an EA can read that permission through TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) (MQL5 Reference, Client Terminal Properties). Nothing there cancels orders already sent. Turning it off also blocks an EA’s own clean-up, because its cancel requests are refused with “Autotrading disabled by client terminal”. A kill path has to cancel orders explicitly first, and only then stop.
The Limits That Should Trip the Switch
FIA describes a kill switch as a last resort, a final backstop behind pre-trade checks. The everyday work is done by smaller limits that reject a bad order before it leaves. FIA’s list includes:
- Maximum order size, the “fat-finger” limit, checked when an order is sent and when it is modified.
- Price tolerance, rejecting a limit order whose price is too far from a reference price such as the current market.
- Repeated automated execution limits, the number of times a strategy or identical order can be filled and re-enter the market without a person stepping in.
- Message throttles, so one system cannot flood a venue with orders and cancels.
RTS 6 Article 15 adds a rule worth copying exactly. After a set number of repeated executions, “the trading system shall be automatically disabled until re-enabled by a designated staff member” (Commission Delegated Regulation (EU) 2017/589, Article 15). FIA says the same: the strategy “should be disabled until an authorized person re-enables it”.
So a tripped limit should stay tripped, not quietly reset on the next bar or after a restart. Someone looks at what happened and switches the system back on deliberately. Which limits to use, and at what values, depends on the trader and the strategy, so they belong in configurable inputs.
Building One into an Expert Advisor
In MQL5, a simple kill path looks like this. It sets a halt flag first, so no new orders go out, saves that flag where it survives a restart, then deletes this EA’s pending orders and, if asked, closes its positions:
#include <Trade/Trade.mqh>
input long InpMagic = 12345; // this EA's magic number
CTrade trade;
bool g_halted = false;
string g_haltName;
int CountOwn(const bool positions)
{
int n = 0;
int total = positions ? PositionsTotal() : OrdersTotal();
for(int i = total - 1; i >= 0; i--)
{
ulong ticket = positions ? PositionGetTicket(i) : OrderGetTicket(i);
if(ticket == 0) continue;
long magic = positions ? PositionGetInteger(POSITION_MAGIC) : OrderGetInteger(ORDER_MAGIC);
if(magic == InpMagic) n++;
}
return n;
}
bool KillSwitch(const bool closePositions)
{
g_halted = true; // 1. block new orders
GlobalVariableSet(g_haltName, 1.0); // 2. remember it after a restart
GlobalVariablesFlush(); // and save it to disk now
for(int attempt = 0; attempt < 3; attempt++)
{
for(int i = OrdersTotal() - 1; i >= 0; i--) // 3. cancel pending orders
{
ulong ticket = OrderGetTicket(i);
if(ticket > 0 && OrderGetInteger(ORDER_MAGIC) == InpMagic)
if(!trade.OrderDelete(ticket) || trade.ResultRetcode() != TRADE_RETCODE_DONE)
PrintFormat("Delete %I64u failed: %u %s", ticket,
trade.ResultRetcode(), trade.ResultRetcodeDescription());
}
if(closePositions)
for(int i = PositionsTotal() - 1; i >= 0; i--) // 4. optionally close positions
{
ulong ticket = PositionGetTicket(i);
if(ticket > 0 && PositionGetInteger(POSITION_MAGIC) == InpMagic)
if(!trade.PositionClose(ticket) || trade.ResultRetcode() != TRADE_RETCODE_DONE)
PrintFormat("Close %I64u failed: %u %s", ticket,
trade.ResultRetcode(), trade.ResultRetcodeDescription());
}
if(CountOwn(false) == 0 && (!closePositions || CountOwn(true) == 0))
return true; // 5. verified: nothing left
Sleep(500); // let the terminal update, then retry
}
Alert("Kill switch: orders or positions still open for magic ", InpMagic, ". Check manually.");
return false;
}
int OnInit()
{
g_haltName = "Halt_" + IntegerToString(InpMagic);
g_halted = GlobalVariableCheck(g_haltName); // stays halted until a person clears it
return(INIT_SUCCEEDED);
}
Every function that sends an order checks g_halted first. OrderGetTicket() and PositionGetTicket() also select the order or position, so the property reads that follow apply to it (MQL5 Reference, OrderGetTicket). MetaQuotes notes that a successful OrderDelete() or PositionClose() call “does not always mean successful execution of the trade operation”, so the code checks that the server’s return code is TRADE_RETCODE_DONE, retries anything still open and raises an alert if something will not go away (MQL5 Reference, CTrade OrderDelete). The halt flag is a terminal global variable. The terminal saves these to disk when it shuts down, so the code calls GlobalVariablesFlush() to save the flag straight away in case the computer crashes (MQL5 Reference, GlobalVariablesFlush). MetaQuotes also says a global variable is deleted automatically four weeks after it was last accessed (MQL5 Reference, Global Variables of the Terminal), so a halt left alone longer than that would clear itself. A halt that must last should also be written to a file. Deleting the flag by hand, in the terminal’s Global Variables window, is the deliberate “re-enable” step.
Whether to close positions as well as cancel orders is the trader’s decision, not a coding one; some prefer to keep positions with their protective stops in place.
Webhook Bridges and Exchange Bots
A TradingView alert with a webhook sends an HTTP POST request to the URL you give it “as soon as the alert is triggered” (TradingView, How to configure webhook alerts). Those requests time out after 3 seconds, and webhooks need two-factor authentication. TradingView does not know whether your bridge is healthy, so alerts keep arriving. The off switch belongs in the bridge: when halted, it logs and refuses incoming alerts, and cancels working orders through the broker’s own API.
On exchanges, check exactly what “cancel all” means. Binance Spot’s DELETE /api/v3/openOrders “Cancels all active orders on a symbol”, including orders in an order list (Binance Spot API, REST API). It works one symbol at a time, so a bot-wide kill switch has to loop over every symbol it trades.
Some venues also offer cancel-on-disconnect, which FIA describes as a “best-effort attempt to cancel all resting orders” when a session’s connection drops. Bybit’s version, Disconnection Protect, cancels active orders if the client does not reconnect and resume its heartbeat within a window (10 seconds by default), but Bybit states it is “only available for Ins clients” (Bybit’s institutional clients). VIP clients cannot use it, and it is switched on through a client manager (Bybit API, Set Disconnect Cancel All). For most accounts, the bot has to provide this protection itself.
A Cautionary Example
The best-known case is Knight Capital in 2012. According to the US Securities and Exchange Commission, an incorrect code deployment triggered an old, unused function in an order router, which “rapidly sent more than 4 million orders into the market when attempting to fill just 212 customer orders” in the first 45 minutes of trading. The SEC also found inadequate controls immediately before order submission, and 97 automated emails flagging an error before the open that were not acted on (SEC press release 2013-222). Dead code, a bad deployment and ignored warnings can happen in small systems too.
Limits and Caveats
A kill switch only reaches what it can talk to. If the connection is what has failed, cancel requests may not arrive. FIA notes that when a customer loses its connection to a broker, passing cancels through to the exchange is typically unsupported, and the customer may need to contact the broker to cancel working orders manually.
legislation.gov.uk lists a revocation of the UK version of RTS 6 under the Financial Services and Markets Act 2023 that has not yet been applied to its text, and the FCA amended RTS 6 as recently as October 2025, so it still applies to UK investment firms that trade algorithmically. Most private traders are not such firms, so we use it here as a checklist, and nothing here is legal or compliance advice. Venue features such as Disconnection Protect, and who can use them, change over time. The MQL5 example is a starting point to test on a demo account, not a drop-in safety system. And none of this says whether a strategy is any good; it only makes sure the system stops when you need it to.
Conclusion
Does your trading bot have an off switch? If the answer is “I’d close the terminal”, probably not a complete one. A real kill switch blocks new orders first, cancels resting orders explicitly, stays tripped until a person resets it, and sits behind smaller limits that catch most problems first. It is a short piece of code, and far easier to add before it is needed.
Building these safeguards into Expert Advisors, webhook bridges and exchange bots is part of our Trading Automation work, with the MQL5 side covered by our MetaTrader Services and TradingView alert handling by our TradingView Services.
Drafted with AI assistance; reviewed, edited and approved by Ionut Claudiu Fratila.