Blog / Code & convert EAs · Prop firms · MQL5 · Risk management

Coding a Daily Loss Limit into Your EA

Learn how to implement a daily loss limit in MQL5 to prevent an Expert Advisor from opening new trades after a defined loss threshold.

· 6 min read

A daily loss limit is one of the most important risk controls for an Expert Advisor operating on a prop firm account.

It prevents a trading strategy from continuing to open new positions after the account reaches a predefined loss threshold.

Without this protection, an EA can continue trading through a losing sequence and potentially breach the firm's daily drawdown rules.

In this guide, we'll build a basic daily loss protection mechanism in MQL5, explain how it works, and highlight the details you need to consider before using it on a prop firm account.

1. Understand how a daily loss limit works

A daily loss limit defines the maximum amount an account is allowed to lose within a particular trading day.

For example, suppose a prop firm provides a $100,000 account with a 5% daily loss limit.

The permitted daily loss is:

100,000 × 0.05 = $5,000

If the firm's calculation uses a $100,000 starting-of-day equity reference, the breach threshold is $95,000.

When the account reaches that threshold, the EA should stop opening new trades.

However, daily loss rules are not identical across prop firms. Some calculate losses from starting balance, others use starting equity or the higher of the two, and some include floating losses, commissions, swaps, or other adjustments. The day can also reset at different times: some firms use midnight broker-server time, others midnight in a fixed time zone such as Central European Time.

Before implementing the control, establish exactly how the firm calculates its limit and when its trading day resets. The Most Important Prop Firm Rules goes through the usual variations.

2. Choose the correct account value to monitor

MQL5 provides account information functions that allow an EA to monitor the trading account.

Two particularly useful properties are:

  • ACCOUNT_BALANCE: The account balance after completed transactions.
  • ACCOUNT_EQUITY: The account's current equity, including floating profit and loss.

For a daily loss guard that needs to account for open positions, equity is useful because it reflects both realised and unrealised account performance.

Consider this example:

Account metric Value
Starting equity $100,000
Current balance $99,000
Floating loss -$2,000
Current equity $97,000

The account has lost $3,000 relative to its starting equity, even though the balance has only decreased by $1,000.

Monitoring balance alone would not capture the full current loss.

Important: Use the account value specified by the prop firm's actual drawdown formula. Equity-based monitoring is not automatically the correct implementation for every firm.

3. Define the daily loss limit

Start by creating an input variable that allows the user to configure the permitted daily loss percentage.

MQL5
input double DailyLossLimitPct = 5.0;

Next, calculate the maximum permitted loss using the starting-of-day reference value.

MQL5
double CalculateDailyLossLimit(double startEquity)
{
   return startEquity * DailyLossLimitPct / 100.0;
}

For example, if the starting equity is $100,000 and the configured limit is 5%, the function returns $5,000.

The corresponding equity threshold is:

MQL5
double breachLevel = startEquity - CalculateDailyLossLimit(startEquity);

The EA can then compare current equity against this threshold.

However, there is an important detail: the starting equity must remain consistent throughout the trading day. It should not be recalculated every time the EA receives a tick or restarts.

4. Store the starting equity and identify the trading day

An EA needs to remember the starting equity reference so that restarting MetaTrader does not accidentally reset its daily loss calculation.

MQL5 terminal global variables provide a simple way to persist this information between EA restarts.

The following example creates a unique key for each trading account and broker-server calendar date.

MQL5
string GetDailyEquityKey()
{
   datetime serverTime = TimeTradeServer();

   if(serverTime == 0)
      serverTime = TimeCurrent();

   MqlDateTime date;
   TimeToStruct(serverTime, date);

   return StringFormat(
      "PA_DSL_%I64d_%04d%02d%02d",
      AccountInfoInteger(ACCOUNT_LOGIN),
      date.year,
      date.mon,
      date.day
   );
}

The key changes when the broker-server date changes.

Next, retrieve the stored starting equity or initialise it if no value exists.

MQL5
double GetDailyStartEquity()
{
   string key = GetDailyEquityKey();
   double startEquity = 0.0;

   if(!GlobalVariableCheck(key))
   {
      startEquity = AccountInfoDouble(ACCOUNT_EQUITY);

      GlobalVariableSet(key, startEquity);
   }
   else
   {
      if(!GlobalVariableGet(key, startEquity))
         return 0.0;
   }

   return startEquity;
}

This prevents an ordinary EA restart from replacing the original daily reference with the account's newer equity.

There is one limitation: if the EA first starts after the firm's daily reset, it records equity at that first execution rather than reconstructing the exact reset-time value. For production use, synchronise the reference with the firm's actual reset time and calculation method.

5. Build the daily loss protection function

Now combine the starting equity, configured loss percentage, and current account equity.

The following implementation also stores a daily lock so that once the threshold is reached, the EA cannot resume opening trades merely because equity later recovers.

MQL5
bool DailyLossLimitReached()
{
   string baseKey = GetDailyEquityKey();
   string lockKey = baseKey + "_LOCK";

   // Keep the lock active for the remainder of the day.
   if(GlobalVariableCheck(lockKey))
      return true;

   if(DailyLossLimitPct <= 0.0)
      return true;

   double startEquity = GetDailyStartEquity();

   // Fail safely if the reference cannot be retrieved.
   if(startEquity <= 0.0)
      return true;

   double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);

   double allowedLoss =
      startEquity * DailyLossLimitPct / 100.0;

   double breachLevel = startEquity - allowedLoss;

   if(currentEquity <= breachLevel)
   {
      GlobalVariableSet(lockKey, 1.0);

      Print("Daily loss limit reached. New entries disabled.");

      return true;
   }

   return false;
}

Once the function detects a breach, it creates a lock for that account and trading day.

The lock remains active even if the EA is restarted or the account's equity subsequently recovers.

The example uses terminal global variables, which persist locally on the terminal. If you run the EA on multiple terminals or VPS instances, you need an additional shared risk-control mechanism to coordinate them.

One more consideration: the function compares equity with the firm's actual limit. In practice, you may want the EA to stop earlier, at a line set some distance inside the firm's limit, so that slippage or a fast move on the way out doesn't take the account past it.

6. Integrate the protection into your EA

Defining the function is only part of the implementation. You must also call it at the correct point in the EA's execution flow.

For example:

MQL5
void OnTick()
{
   // Continue managing existing positions.
   ManageOpenPositions();

   // Prevent new entries after the daily limit is reached.
   if(DailyLossLimitReached())
      return;

   // Run the strategy's entry logic.
   CheckForNewEntries();
}

The order matters.

Position management runs before the daily loss check, allowing the EA to continue managing existing positions even after new entries have been disabled.

This distinction is important. Simply returning at the beginning of OnTick() could prevent the EA from managing open trades, including stop-loss adjustments and other protective actions.

Also, this example only blocks new entries generated by the EA. It does not automatically close existing positions or prevent manual trades and other EAs from increasing account risk.

If the prop firm's rules require positions to be closed immediately at a particular threshold, that behaviour must be implemented separately and tested carefully.

7. Test the daily loss limit before deployment

Never assume that a daily loss protection function works correctly just because the code compiles.

Test different account conditions in the Strategy Tester and, where necessary, on a demo account.

A useful test checklist includes:

  • Confirm that the starting equity is recorded correctly.
  • Verify that the daily loss threshold is calculated correctly.
  • Check that floating losses are included when required.
  • Confirm that no new trades open after the threshold is reached.
  • Restart the EA and verify that the daily reference remains unchanged.
  • Confirm that the daily lock remains active after an equity recovery.
  • Verify that the lock resets on the next trading day.
  • Test the EA around the broker's daily reset time.
  • Check that existing positions continue to receive protective management.

Also test what happens when the terminal is disconnected, restarted, or running on another VPS.

Remember that a local EA control cannot guarantee that an account will never breach a prop firm's limit. Price gaps, slippage, commissions, swaps, other trading activity, and platform interruptions can all affect the actual account equity.

Conclusion

A daily loss limit helps prevent an Expert Advisor from continuing to open trades after an account reaches its predefined loss threshold.

In MQL5, you can build this protection using AccountInfoDouble(), terminal global variables, and a function that checks current equity against a stored daily reference.

The most important part is ensuring that the calculation matches the prop firm's actual rules. Pay particular attention to its reference value, reset time, treatment of floating losses, and breach conditions. If the account also has an overall limit, check whether it is static or trailing.

A well-designed EA should protect the account while continuing to manage existing positions safely. For the other rules to check before a challenge, read Can You Use an EA on a Prop Firm Challenge?

If you'd rather not write this yourself, PositionAlpha's Prop Firm Shield adds your challenge's daily and overall limits to an MT5 EA as prewritten code. It uses your firm's reset time and reference value, and closes everything and stops at a line you set below the firm's limit. Compile the result in MetaEditor and test it on a demo account before you rely on it; it can't prevent a loss.

Build a bot from your idea

Describe your trading idea and the AI writes MT4 or MT5 code for you to review and test, with a plain-English explanation and setup steps. Your first bot is free.

More from the blog