MT5 EA for Prop Firms: Enforce Daily Loss and Drawdown Rules in MQL5
Most failed prop firm challenges are lost to a rule breach, not to the strategy: one bad day crosses the daily loss limit and the account is closed. An MT5 Expert Advisor can enforce those limits for you, automatically and without hesitation. This guide shows the rules that matter and the MQL5 code to enforce them, whether your entries are manual or automated.
The rules prop firms usually enforce
Every firm writes its own rulebook, so read yours carefully. These are the limits that appear most often:
- Daily loss limit. A maximum loss per day, often measured from the balance or equity at the start of the day.
- Maximum drawdown. A floor the account equity must never fall below. It can be static, fixed from the starting balance, or trailing, moving up as the account makes new highs.
- Lot or exposure limits. A cap on position size or on the number of open trades.
- News and weekend rules. Some firms restrict trading around major news releases or holding positions over the weekend.
- Rules about automation. Some firms restrict certain EA styles, copy trading between accounts, or high-frequency strategies.
The two details that catch people out are when the firm's day resets, and whether floating losses on open trades count. For most firms they do, which means you have to watch equity, not balance.
How a guard EA works
The idea is simple. On every tick the EA compares current equity with the limits. If a limit is about to be reached, it closes all positions and blocks new trades until the next day, or permanently for a drawdown breach.
Set the EA's limits tighter than the firm's. If the firm allows a 5% daily loss, stop at 4%. Slippage and gaps mean a close order does not fill exactly where you asked.
Step 1: Inputs and state
#include <Trade\Trade.mqh>
input double MaxDailyLossPercent = 4.0; // stop for the day at this loss
input double MaxTotalLossPercent = 8.0; // stop completely at this loss
input double StartingBalance = 100000;
input int DayResetHour = 0; // server hour when the firm's day resets
input double MaxLotsPerTrade = 5.0;
CTrade trade;
double dayStartEquity = 0;
int currentDay = -1;
bool blockedToday = false;
bool blockedForever = false;
Step 2: Track the start of each day
void UpdateDay()
{
MqlDateTime now;
TimeToStruct(TimeCurrent() - DayResetHour * 3600, now);
if(now.day_of_year != currentDay)
{
currentDay = now.day_of_year;
dayStartEquity = MathMax(AccountInfoDouble(ACCOUNT_EQUITY),
AccountInfoDouble(ACCOUNT_BALANCE));
blockedToday = false;
}
}
Some firms measure the daily loss from the higher of balance and equity at the reset, others from balance only. Adjust that line to match your firm's definition. The example keeps the day's starting equity in memory, so also save it with GlobalVariableSet and read it back in OnInit(). Otherwise restarting MT5 in the middle of a day resets the calculation.
Step 3: Close everything when a limit is hit
void CloseAll()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket > 0)
trade.PositionClose(ticket);
}
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong ticket = OrderGetTicket(i);
if(ticket > 0)
trade.OrderDelete(ticket);
}
}
void CheckLimits()
{
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double dailyLoss = dayStartEquity - equity;
double totalLoss = StartingBalance - equity;
if(totalLoss >= StartingBalance * MaxTotalLossPercent / 100.0)
{
blockedForever = true;
CloseAll();
Alert("Max drawdown guard triggered. Trading stopped.");
}
else if(dailyLoss >= dayStartEquity * MaxDailyLossPercent / 100.0)
{
blockedToday = true;
CloseAll();
Alert("Daily loss guard triggered. Trading stopped until the next day.");
}
}
Step 4: Put it in OnTick
void OnTick()
{
UpdateDay();
if(!blockedForever && !blockedToday)
CheckLimits();
if(blockedForever || blockedToday)
{
if(PositionsTotal() > 0 || OrdersTotal() > 0)
CloseAll(); // also closes trades opened manually after the block
return;
}
// your strategy's entry logic goes here
}
Because the guard runs before the entry logic, a blocked day stays blocked. The second CloseAll() also shuts any trade you open by hand after the limit, which protects you from revenge trading.
For a trailing drawdown
If your firm's maximum drawdown trails the account's highest point, track the peak and measure from there:
double peakEquity = 0;
bool TrailingDrawdownHit(double maxPercent)
{
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
if(equity > peakEquity) peakEquity = equity;
return(peakEquity - equity >= peakEquity * maxPercent / 100.0);
}
Store the peak in a global variable of the terminal with GlobalVariableSet so it survives a restart of MT5. Firms differ on whether the trail follows balance or equity and whether it stops trailing at the starting balance, so match the calculation to the rulebook.
Other protections worth adding
- Lot cap. Check the calculated lot against
MaxLotsPerTradebefore every order. - Maximum trades per day. Count entries and stop after a set number.
- News filter. Block entries for a window around high-impact releases. MT5 has a built-in economic calendar you can query from MQL5.
- Friday close. Close positions before the market closes if your firm does not allow weekend holding.
- Profit target stop. Stop trading once the challenge target is reached, so a later loss does not undo a passed phase.
Test the guard before you rely on it
- Run the EA in the Strategy Tester over a losing period and confirm trading stops at your limit.
- On a demo account, set the daily limit very low, open a manual trade, and watch the guard close it.
- Restart MT5 in the middle of a day and check that the day's starting equity and the block are still correct.
What an EA cannot protect you from
- Gaps and slippage. If price jumps past your limit, the close fills at the next available price.
- A terminal that is switched off. The guard only works while MT5 is running, so use a VPS.
- Rules it does not know about. Consistency rules and restrictions on trading styles need to be read and followed by you.
Frequently asked questions
Are EAs allowed on prop firm accounts?
Many firms allow them, some with restrictions. Check your firm's rules before using any EA on a funded or challenge account.
Can the guard work with manual trading?
Yes. Leave the entry section empty and attach the EA to one chart. It will monitor the whole account.
Will this make me pass the challenge?
No. It stops you from failing through a rule breach. Reaching the profit target still depends on the strategy.
Should the limit use balance or equity?
Equity for the live check, because open losses count at most firms. Use your firm's definition for the starting reference.
Want it built for your firm's rules?
We build Expert Advisors with daily loss, drawdown and trade limits matched to the rulebook you trade under. See MT5 Expert Advisor (EA) development, or start with how to build your first MT5 EA.
This article is for education. It is not financial advice.