MQL5 Kill Switch: Code Daily Loss & DD Guard

Build an MQL5 kill switch EA to guard daily loss, max drawdown, and equity curve deterioration. Full code, inputs, and prop firm settings.

mql5-kill-switch-code-daily-loss-dd-guard

You've seen it happen. A trend-following EA that printed money for three months gives it all back in one wild Tuesday session. The equity curve looks like a ski slope, and you're staring at a margin call because your "robust" strategy didn't account for a news spike that blew through every stop.

Most traders blame the strategy. I blame the missing kill switch.

I've been writing MQL5 Expert Advisors for over a decade, and the single biggest difference between accounts that survive and accounts that blow up isn't the entry logic — it's the risk governor sitting on top of it. A kill switch is that governor. It's a standalone EA or a block of code inside your main EA that monitors daily loss, equity drawdown, and equity curve behavior, then halts trading the moment things go sideways.

This article walks you through building a proper MQL5 kill switch EA from scratch. You'll get working code, input parameters you can tune, and the honest trade-offs of each approach. Whether you're running a martingale recovery system or a conservative grid, this is the layer that keeps you in the game.

What a Kill Switch Actually Does

A kill switch isn't a stop loss. A stop loss protects an individual position. A kill switch protects the entire account from a series of losing positions, a runaway algorithm, or a market regime shift that your strategy wasn't designed for.

Think of it as circuit breaker for your trading. When triggered, it does three things in order:

  1. Closes all open positions — immediately, regardless of profit or loss.
  2. Deletes all pending orders — so nothing new gets filled while you're locked out.
  3. Blocks new trades — either for the rest of the day, a set number of hours, or until you manually reset it.

The key insight most traders miss: a kill switch should be separate from your strategy logic. If it lives inside your main EA, a bug in your entry code can take down the protection too. I prefer a standalone utility EA that runs on the same chart, or better yet, a global EA attached to a single chart that monitors the entire account across all symbols.

There's another reason for separation: testing. If your kill switch is buried inside a 2,000-line EA, you can't easily backtest it in isolation. You end up guessing whether the protection actually works. A standalone utility EA you can attach to a demo account, torture-test with a deliberately reckless strategy, and verify the trigger logic before you trust it with real money.

Why Prop Firm Traders Need This Most

If you're trading a prop firm challenge — FTMO, MyForexFunds, Funding Pips, whatever — you already know the rules. Daily loss limits around 5%, max drawdown around 10%. Blow through either and your account is gone. No second chances.

The problem? Your EA doesn't know about prop firm rules. It just trades its strategy. A kill switch bridges that gap. You set the daily loss limit to 4% instead of 5%, giving yourself a buffer before the firm's hard limit kicks in. When your EA hits 4%, the kill switch halts trading. You keep the account, you keep the profit, and you live to trade tomorrow.

One thing I see constantly in prop firm communities: traders who set their kill switch to exactly the firm's limit. That's a mistake. You need a buffer because of spread widening and slippage. If your firm's daily loss limit is 5%, and your kill switch triggers at 5%, a sudden spread spike on GBPUSD during London open can push you to 5.3% before your close order even fills. Set your internal limit at 3.5% to 4% and you've got room to breathe.

Core Components of an MQL5 Kill Switch

Before we write code, let's break down what the EA needs to track. There are three primary triggers, and you'll want to configure each independently:

1. Daily Loss Limit

This is the most common trigger. It calculates the account's starting equity at midnight (or your broker's server time), then compares current equity against it. If the drop exceeds your configured percentage, the kill switch fires.

One subtlety: what counts as "daily"? Most prop firms use their server time, not your local time. MQL5's TimeCurrent() returns broker server time, which is exactly what you need. I'll show you how to detect a new day and reset the baseline.

Another subtlety: equity vs balance. If you have open positions, your balance doesn't move but your equity does. A daily loss limit must use equity, not balance. Floating losses count. If you wait for balance to drop, you've already been margin-called. The code below uses AccountInfoDouble(ACCOUNT_EQUITY) throughout.

2. Maximum Drawdown

This is a rolling measure of peak equity. The EA tracks the highest equity value since it started (or since the last reset), then compares current equity to that peak. If the drawdown from peak exceeds your threshold, trading halts.

This is trickier than daily loss because it's cumulative. A 10% max drawdown limit means once you peak at $10,000, you can't let equity fall below $9,000 — even if that happens over three weeks, not three hours.

You also need to decide: does the peak reset when the kill switch resets? I'd argue no. A max drawdown is a lifetime measure (or at least a "since EA start" measure). If you reset the peak every day, you're just measuring daily loss again. The whole point of a drawdown trigger is catching multi-day slides. In my implementation, the peak persists until you manually reset it or restart the EA.

3. Equity Curve Deterioration

This is the advanced trigger most traders skip. Instead of a fixed percentage, it looks at the shape of your equity curve. For example: "If equity makes a new 10-day low, halt trading." Or: "If the equity curve drops below its 20-period moving average, halt."

This catches slow bleed-outs that never hit your daily loss or max drawdown limits but still destroy your account over time. A strategy that loses 1% every day for two weeks never triggers a 5% daily limit, but it's clearly broken. The equity curve trigger catches that.

Implementation-wise, I store daily equity samples in an array. Each new day, I push the current equity onto the array and drop the oldest sample. Then I check if the current equity is the minimum of the last N samples. If it is, we're at a new low — and that's your signal to stop.

You can tune this to be more or less sensitive. A 10-bar window halts after 10 losing days. A 30-bar window allows more noise but catches deeper structural breaks. I prefer 20 as a balance. It's also worth noting that this trigger works best on daily closes, not intraday ticks. If you check it on every tick, a single volatile hour can make equity dip below a 20-day low intraday, even if the daily trend is fine. I check it once per day, right after the daily reset.

Building the Kill Switch in MQL5

Let's get into the code. I'll build this as a standalone EA you can attach to any chart. It monitors the entire account, not just the chart's symbol.

Before we start, a quick note on MQL5 vs MQL4. MQL5 is event-driven, uses OnTick() instead of start(), and has a different position model (positions vs orders). The code below is MQL5. If you're still on MQL4, you'll need to adapt the position-closing logic — but the concepts translate directly.

Input Parameters

ParameterTypeDefaultDescription
EnableDailyLossLimitbooltrueEnable the daily loss limit trigger.
DailyLossPercentdouble4.0Max daily loss as % of day-start equity (e.g., 4.0 = 4%).
EnableMaxDrawdownbooltrueEnable the max drawdown trigger.
MaxDrawdownPercentdouble8.0Max drawdown from peak equity as %.
EnableEquityCurveGuardbooltrueEnable equity curve deterioration trigger.
EquityCurveBarsint20Number of daily equity samples for curve guard.
HaltHoursint24Hours to halt trading after trigger. 0 = until manual reset.
CloseAllOnTriggerbooltrueClose all positions immediately when a trigger fires.
ResetDailyAtServerTimebooltrueReset the daily baseline at broker server midnight.

The Core Logic

Here's the full EA. I've stripped out the fluff and kept it focused. You can compile this directly in MetaEditor and attach it to any chart.

//+------------------------------------------------------------------+
//|                                               KillSwitchGuard.mq5 |
//|                                      Account-level kill switch   |
//+------------------------------------------------------------------+
#property strict
#property version   "1.00"

input bool   EnableDailyLossLimit   = true

Want to build your own version?

Recreate similar entry logic, risk rules, and filters in TradingBotMaker—no MQL coding. Start free.

Community

Clap for the article and open comments only when you want to read them.

0 claps0 comments

Related articles