strategy.risk in MQL5: drawdown and daily loss guards
Short answer
MetaTrader 5 has nothing comparable for an EA, so the strategy.risk.* rules become guard functions that run on every tick before any order. They read the account and the deal history, close positions and refuse new entries when a limit is hit.
The strategy.risk.* functions are rules the TradingView emulator enforces on top of your script: stop trading after a drawdown, after a daily loss, above a position size, or in a forbidden direction. MetaTrader 5 has nothing comparable for an EA; brokers may stop out an account, but that is a margin rule, not a strategy rule. The MQL5 equivalent is a set of guard functions that run on every tick before any order, read the account and the deal history, close positions and refuse new entries when a limit is hit.
What strategy.risk computes
Each call is evaluated once and holds for the whole run:
max_drawdown(value, type): when the drawdown from the equity peak reachesvalue(percent of equity or cash), all open trades are closed, all pending orders cancelled, and the strategy places no orders for the rest of the run.max_intraday_loss(value, type): when the day's loss, closed plus open, reachesvalue, positions are closed and trading stops until the next trading session.max_position_size(contracts): an entry that would take the absolute position above the limit is reduced or not placed.allow_entry_in(direction): entries in the other direction are not opened; an oppositestrategy.entryonly closes the current position.
Pine also has max_cons_loss_days and max_intraday_filled_orders, which follow the same pattern: a counter, a limit, and a halt.
The MQL5 equivalent
//@version=6
strategy("Risk rules demo", overlay = true, initial_capital = 10000,
default_qty_type = strategy.fixed, default_qty_value = 1, pyramiding = 3)
// emulator-enforced risk rules
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.risk.max_position_size(2)
strategy.risk.max_drawdown(20, strategy.percent_of_equity)
strategy.risk.max_intraday_loss(300, strategy.cash)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
if ta.crossover(fast, slow)
strategy.entry("L", strategy.long)
if ta.crossunder(fast, slow)
strategy.entry("S", strategy.short) // becomes an exit: shorts are not allowedThe EA keeps each rule as an input and puts all checks in RiskAllowsTrading, called at the top of OnTick on every tick, so a limit is caught inside the bar the way the emulator catches it. The daily loss sums today's closing deals of this EA (profit, swap, commission) plus floating profit; the drawdown latch stays set until the EA is restarted.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input bool InpLongOnly = true; // allow_entry_in(strategy.direction.long)
input double InpMaxPosLots = 0.20; // max_position_size, in lots
input double InpMaxDrawdownPct = 20.0; // max_drawdown(20, percent_of_equity)
input double InpMaxDayLoss = 300.0; // max_intraday_loss(300, cash)
input long InpMagic = 60021;
CTrade trade;
int hFast = INVALID_HANDLE, hSlow = INVALID_HANDLE;
double peakEquity = 0.0;
bool stopForever = false; // max_drawdown: trading stops for good
int lossDay = -1; // max_intraday_loss: day that is locked
int OnInit()
{
hFast = iMA(_Symbol, _Period, 9, 0, MODE_EMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE)
return INIT_FAILED;
trade.SetExpertMagicNumber(InpMagic);
trade.SetTypeFillingBySymbol(_Symbol);
peakEquity = AccountInfoDouble(ACCOUNT_EQUITY);
return INIT_SUCCEEDED;
}
bool IsNewBar()
{
static datetime last = 0;
const datetime t = iTime(_Symbol, _Period, 0);
if(t == last)
return false;
last = t;
return true;
}
// signed net lots of this EA on this symbol
double NetLots()
{
double net = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(PositionGetTicket(i) == 0 || PositionGetString(POSITION_SYMBOL) != _Symbol
|| PositionGetInteger(POSITION_MAGIC) != InpMagic)
continue;
const double v = PositionGetDouble(POSITION_VOLUME);
net += PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? v : -v;
}
return net;
}
void CloseAll()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
const ulong ticket = PositionGetTicket(i);
if(ticket != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic)
trade.PositionClose(ticket);
}
}
// today's closed P&L of this EA plus its floating P&L, account currency
double TodayPnL()
{
MqlDateTime d;
TimeToStruct(TimeCurrent(), d);
d.hour = 0; d.min = 0; d.sec = 0;
double pnl = 0.0;
if(HistorySelect(StructToTime(d), TimeCurrent()))
for(int i = 0; i < HistoryDealsTotal(); i++)
{
const ulong t = HistoryDealGetTicket(i);
if(t != 0 && HistoryDealGetInteger(t, DEAL_MAGIC) == InpMagic
&& HistoryDealGetString(t, DEAL_SYMBOL) == _Symbol)
pnl += HistoryDealGetDouble(t, DEAL_PROFIT) + HistoryDealGetDouble(t, DEAL_SWAP)
+ HistoryDealGetDouble(t, DEAL_COMMISSION);
}
for(int i = PositionsTotal() - 1; i >= 0; i--)
if(PositionGetTicket(i) != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic)
pnl += PositionGetDouble(POSITION_PROFIT);
return pnl;
}
// all guards; returns true when new entries are allowed
bool RiskAllowsTrading()
{
const double eq = AccountInfoDouble(ACCOUNT_EQUITY);
peakEquity = MathMax(peakEquity, eq);
if(!stopForever && (peakEquity - eq) / peakEquity * 100.0 >= InpMaxDrawdownPct)
stopForever = true;
MqlDateTime d;
TimeToStruct(TimeCurrent(), d);
if(lossDay != d.day_of_year && TodayPnL() <= -InpMaxDayLoss)
lossDay = d.day_of_year;
if(stopForever || lossDay == d.day_of_year)
{
CloseAll();
return false;
}
return true;
}
void OnTick()
{
const bool allowed = RiskAllowsTrading(); // checked on every tick
if(!IsNewBar() || !allowed)
return;
double f[2], s[2];
if(CopyBuffer(hFast, 0, 1, 2, f) != 2 || CopyBuffer(hSlow, 0, 1, 2, s) != 2)
return;
const double net = NetLots();
if(f[1] > s[1] && f[0] <= s[0] && net + InpLots <= InpMaxPosLots + 1e-9)
trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L");
if(f[1] < s[1] && f[0] >= s[0])
{
if(InpLongOnly)
CloseAll(); // the short entry only closes the long
else
trade.Sell(InpLots, _Symbol, 0.0, 0.0, 0.0, "S");
}
}"Today" here is the trade server's day, from TimeCurrent(). TradingView uses the exchange session of the symbol; for forex the two can be several hours apart. If the halt must survive a terminal restart, store stopForever and peakEquity with GlobalVariableSet.
Where the two differ
| Rule | Pine | MQL5 |
|---|---|---|
| Enforcement | by the emulator, cannot be bypassed | by your code; a bug or a restart can bypass it |
| Drawdown basis | strategy equity from initial_capital | ACCOUNT_EQUITY, which includes anything else on the account |
| Day boundary | exchange session | server time unless you convert |
| Position size unit | contracts | lots |
| Evaluation | on fills and bar updates | every tick, if you put the check before the new-bar gate |
| Pending orders on halt | cancelled | delete them yourself with OrderDelete if the EA uses any |
What the Stratlate converter emits
None of the strategy.risk.* functions are converted. Each call is reported as unsupported (PM900, "no MQL mapping"), the conversion is marked PARTIAL, and the call is left in place as a PINE_NA /* UNCONVERTED: strategy.risk.max_drawdown */; statement that compiles with an "expression has no effect" warning and does nothing. The rest of the strategy is converted normally, so the EA trades without its risk limits until you add guards like the ones above; with allow_entry_in(strategy.direction.long) dropped, the converted EA in this example also opens the short trades Pine would have refused. Add the guards, then compile and backtest.
Pitfalls
- Checking the guards only on a new bar. Symptom: a fast move inside one bar takes the account well past the drawdown limit before the EA reacts.
- Measuring drawdown from
ACCOUNT_BALANCE. Symptom: open losses are ignored and the guard fires only after the damage is realised. - Resetting the peak or the halt flag in
OnInit. Symptom: changing the chart timeframe re-arms a strategy that should have stopped for good. - Forgetting to filter deals by magic number. Symptom: another EA's loss on the same account triggers this EA's daily limit.
- Assuming the converted EA keeps the rules. Symptom: the MT5 backtest shows deeper drawdowns and more trades than the TradingView report.
FAQ
Does the Stratlate converter support strategy.risk.max_drawdown?
No. It and the other strategy.risk.* rules are reported as unsupported and left as inert placeholders; the report lists each one so you can add the guard by hand.
Can MetaTrader 5 enforce a maximum drawdown by itself?
Not per EA. The broker's stop-out level closes positions when margin runs out, which is an account-wide margin rule. A strategy-level drawdown limit has to be coded in the EA.
How do I implement allow_entry_in in an EA?
Keep an input for the allowed direction and, when a signal points the other way, close the current position instead of opening a new one, as the InpLongOnly branch above does.
Convert the whole script
Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.
Open the converter