Adding a daily loss limit to an MQ5 expert advisor

How to Add a Daily Loss Limit to Any MQ5 Expert Advisor (MQL5 Code Example)

One of the biggest advantages of owning an EA's MQ5 source code is that you can add the protections it is missing. The most valuable one, especially for prop firm traders, is a daily loss limit: a rule that stops trading and closes positions once the account loses a set percentage in a day. This guide gives you a clean, reusable MQL5 module and shows you how to plug it into almost any Expert Advisor.

What the Daily Loss Limit Does

  • Records the account balance at the start of each trading day.
  • Compares it with current equity on every tick, so floating losses are counted.
  • When the loss reaches your limit, closes the EA's open positions and blocks new trades until the next day.

Step 1: Add the Inputs and Global Variables

Open your EA in MetaEditor (see our MetaEditor guide) and add this near the top of the file, below any existing #include lines:

#include <Trade/Trade.mqh>

input double InpDailyLossPct = 4.0;   // Max daily loss (% of start-of-day balance)
input long   InpMagic        = 123456; // Magic number of this EA's trades

CTrade   g_trade;
double   g_dayStartBalance = 0.0;
datetime g_currentDay      = 0;
bool     g_tradingHalted   = false;

If your EA already declares a CTrade object or a magic number input, reuse those instead of adding duplicates.

Step 2: Add the Helper Functions

// Reset the reference balance when a new D1 bar starts (broker server time)
void UpdateTradingDay()
{
   datetime today = iTime(_Symbol, PERIOD_D1, 0);
   if(today == 0)
      return;                                  // D1 history not ready yet

   if(today != g_currentDay)
   {
      g_currentDay      = today;
      g_dayStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
      g_tradingHalted   = false;
      PrintFormat("New trading day. Reference balance: %.2f", g_dayStartBalance);
   }
}

// True when equity has dropped by InpDailyLossPct or more
bool IsDailyLossHit()
{
   if(g_dayStartBalance <= 0.0 || InpDailyLossPct <= 0.0)
      return false;

   double equity  = AccountInfoDouble(ACCOUNT_EQUITY);
   double lossPct = (g_dayStartBalance - equity) / g_dayStartBalance * 100.0;
   return (lossPct >= InpDailyLossPct);
}

// Close only this EA's positions (matching magic number)
void CloseOwnPositions()
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0)
         continue;
      if(PositionGetInteger(POSITION_MAGIC) != InpMagic)
         continue;

      if(!g_trade.PositionClose(ticket))
         PrintFormat("Failed to close #%I64u: %u %s", ticket,
                     g_trade.ResultRetcode(), g_trade.ResultRetcodeDescription());
   }
}

Step 3: Call It at the Top of OnTick()

Place this block at the very beginning of the EA's existing OnTick() function, before any entry logic:

void OnTick()
{
   UpdateTradingDay();

   if(g_tradingHalted)
      return;                                  // blocked until the next day

   if(IsDailyLossHit())
   {
      g_tradingHalted = true;
      CloseOwnPositions();
      Print("Daily loss limit reached. Trading halted until next day.");
      return;
   }

   // ... the EA's original trading logic continues here ...
}

Also set the magic number on your trade object in OnInit() with g_trade.SetExpertMagicNumber(InpMagic); so new orders carry it.

Step 4: Compile and Test

  1. Press F7 in MetaEditor and fix any errors in the Toolbox tab.
  2. Run the EA in the Strategy Tester with a deliberately low limit (for example 0.5%) to confirm it halts and closes positions as expected.
  3. Check the Journal for the "Daily loss limit reached" message.
  4. Restore your real limit and forward test on demo. Our backtesting guide covers the settings.

Important Limitations to Know

  • Day boundary: this module uses the broker's D1 bar. Prop firms may reset at a different hour, so set your limit with a safety margin.
  • Restarts: the reference balance lives in memory. If the terminal restarts mid-day, it is recalculated from the current balance. For full persistence, store it with GlobalVariableSet() and read it back in OnInit().
  • Slippage: closing happens at market, so the final loss can slightly exceed the limit during fast moves. Keep a buffer below your firm's real limit.
  • Other EAs: the module only closes positions with its own magic number. If several EAs run on one account, give each its own limit or build an account-level guard.

FAQ

Can I add this to an EX5 file ?

No. Compiled .ex5 files cannot be edited. You need the .mq5 source code.

Should the limit use balance or equity ?

Equity. Most prop firms count floating losses, and an equity check protects you before trades are closed.

Will this slow down my EA ?

No. The checks are a few simple calculations per tick and have no noticeable impact on performance.

Conclusion

A daily loss limit is a small piece of code with a big impact: it turns any EA into a far safer system for funded accounts. Read our prop firm drawdown rules guide, then browse our MQ5 gold EA source codes and MQ5 forex EAs and tools to apply it.

Always test code changes on a demo account before live trading. Trading involves significant risk of loss.

Back to blog