Position Sizing for an EA Under a Daily Loss Limit: Lot Size, Open Risk and a Daily Guard

A daily loss limit turns position sizing from a preference into a hard constraint. Under a prop-firm account's rules, a single bad day can end the account, however well the EA performs across a month. That makes three questions matter more than usual: how the EA converts a risk budget into a lot size, how much risk is open at once, and what stops the EA from opening a trade the day can no longer absorb.

This guide covers each one, with MQL5 code you can adapt. Testing an EA's history against the rules is covered separately in how to test an EA against prop-firm drawdown rules. This article is about the controls inside the EA itself.

One point up front: these controls apply to prop-firm accounts, where the loss rules are fixed in advance. A personal account has different constraints. Good sizing logic reduces the chance of breaching a rule through avoidable errors. It can't prevent losses, gaps or slippage, and this is educational material, not a personal sizing recommendation.

Why daily limits change the sizing problem

Most sizing advice is framed around long-run growth and overall drawdown. A daily loss limit adds a short horizon with no recovery period. Three things follow:

  • The worst day matters more than the average day. Several stops in one session, or one gap through a stop, decide whether the rule holds.
  • Open risk matters, not just per-trade risk. Two positions that each risk a sensible amount can together exceed what the day allows, especially if they are correlated.
  • The EA needs to know where the day stands. It can't rely on you watching the screen.

Step 1: Turn a risk budget into a lot size

Risk per trade is usually set as a percentage of the account, applied to the distance between entry and stop. The EA then has to turn that money amount into a lot size the broker will accept.

For one lot, the loss if the stop is hit is roughly the stop distance in price, divided by the symbol's tick size, multiplied by the value of one tick for one lot. Divide the money at risk by that figure to get the lot size, then round down to the broker's volume step.

// Returns a lot size whose stop-out loss is at or below riskMoney.
// Returns 0 if even the minimum lot would risk too much.
double LotsForRisk(const string sym, const double riskMoney, const double stopDistance)
{
   double tickSize  = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE);
   double tickValue = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE_LOSS);
   double step      = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
   double minLot    = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
   double maxLot    = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
   if(tickSize <= 0 || tickValue <= 0 || step <= 0 || stopDistance <= 0)
      return 0.0;                                   // missing data: don't trade

   double lossPerLot = stopDistance / tickSize * tickValue;
   double lots = MathFloor(riskMoney / lossPerLot / step) * step;
   if(lots < minLot)
      return 0.0;                                   // too small to size safely: skip
   return MathMin(lots, maxLot);
}

Points that matter in practice:

  • Round down, never up. Rounding to the nearest step can push risk above the budget.
  • Skip the trade if the minimum lot is too big. Many EAs quietly bump the size up to the minimum lot, which can multiply the intended risk on small accounts or wide stops.
  • Use the loss-side tick value. Tick value can differ for profit and loss when the account currency differs from the quote currency. Where precision matters, MQL5's OrderCalcProfit gives the money result of a hypothetical move directly.
  • Include costs. Spread and commission add to the loss if the stop is hit. Either subtract expected costs from the risk budget or add them to the stop distance.
  • Check symbol specifications on the actual account. Tick values, contract sizes and volume steps differ between brokers and account types. AI-written EAs in particular often hard-code them; see how to validate an AI-generated EA.

Step 2: Budget open risk, not just per-trade risk

Per-trade risk caps one position. The daily rule caps the account. The link between them is open risk: the total loss if every open position hit its stop now.

To calculate it, loop through open positions, and for each one take the distance from the current price to the stop, converted to money for that position's volume. Add any pending orders that could fill today. Then:

  • Block new trades if any position has no stop. Its open risk is undefined, so the budget can't be checked.
  • Treat correlated positions as one. Positions on closely related instruments, or several entries in the same direction on one symbol, tend to lose together. Count them against a shared cap.
  • Remember open risk can rise. Adding to a position, or moving a stop further away, increases it. A trailing stop that has locked in profit reduces it.

Step 3: Add a daily guard to the EA

The daily guard answers one question before every entry: does the day have room for this trade, if everything open and this new position all hit their stops, with a buffer for slippage?

input double DailyLimitMoney = 0.0;   // set from your account's written rule
input double SafetyBuffer    = 0.0;   // extra room for slippage and gaps
input int    ResetHourServer = 0;     // daily reset hour, in server time

double   g_dayReference = 0.0;
datetime g_dayStart     = 0;

void UpdateDayReference()
{
   datetime now = TimeTradeServer();
   MqlDateTime t;
   TimeToStruct(now - ResetHourServer * 3600, t);
   t.hour = 0; t.min = 0; t.sec = 0;
   datetime today = StructToTime(t);
   if(today != g_dayStart)
   {
      g_dayStart     = today;
      g_dayReference = AccountInfoDouble(ACCOUNT_EQUITY); // or balance: match your rule
   }
}

bool DayHasRoom(const double newTradeRisk, const double openRisk)
{
   UpdateDayReference();
   double usedToday = g_dayReference - AccountInfoDouble(ACCOUNT_EQUITY);
   double room      = DailyLimitMoney - usedToday - SafetyBuffer;
   return (openRisk + newTradeRisk) <= room;
}

This is a starting point. Before relying on it:

  • Match the reference to the rule. Some rules measure the day from balance at the reset, some from equity, some from the higher of the two. Change the reference line to match yours.
  • Survive restarts. If the terminal restarts mid-day, the code above sets a new reference from current equity, which is wrong. Store the day's reference in a terminal global variable or a file, and reload it on start.
  • Know the reset time precisely. The reset is usually in the broker's server time, not your local time. Confirm both.
  • Decide what happens near the limit. Blocking new trades is the minimum. Some traders also close open positions when the day's loss reaches a level short of the limit, accepting a smaller loss to avoid the larger one. That trade-off belongs in the strategy design, and should be tested, not added afterwards.

Step 4: Size the buffer for gaps and slippage

Stops are not guaranteed fills. A stop can fill beyond its level on a gap at the open, around news, or in thin markets. The safety buffer in the guard exists for this.

  • Estimate slippage from evidence. Compare stop fills on demo or live with the stop levels. How to measure the gap between testing and live execution is covered in why an EA trades worse live than in its backtest.
  • Be most conservative around known gaps. Positions held over the weekend or through scheduled news can lose more than their stop distance.
  • Use the tail, not the average. The buffer exists for the bad fills, so size it from the worst observed slippage rather than the typical one.

Step 5: Check the sizing against the whole distribution

A daily guard stops the EA breaking the daily rule through its own entries. It doesn't decide whether the chosen risk per trade is sensible overall. For that, test the sizing against the strategy's drawdown distribution:

  • Replay the rules with the guard's logic included, over every possible start date.
  • Run Monte Carlo on whole trading days to see how often the guard would block trades and how often the maximum loss rule would still be reached. See Monte Carlo testing a trading strategy.
  • Read the tail correctly. If the 95th-percentile simulated drawdown is close to the maximum loss limit, about one simulated path in twenty reached that level or worse.

If the risk per trade that keeps the tail inside the rules is too small for the strategy to do anything useful within the evaluation period, the strategy and the account structure may be a poor match. That's worth knowing before you start.

Common sizing mistakes in EAs

  1. Rounding lot sizes up to the nearest step or the minimum lot.
  2. Hard-coding tick value or contract size instead of reading them from the symbol.
  3. Ignoring costs in the risk calculation.
  4. Checking each trade but not open risk.
  5. Treating correlated positions as independent.
  6. Resetting the daily reference on terminal restart.
  7. Using local time for the daily reset.
  8. Assuming stops always fill at the stop price.

Position sizing checklist for daily-limit accounts

  • Lot size calculated from the stop distance and read-from-symbol tick values
  • Lots rounded down; trades skipped if the minimum lot exceeds the budget
  • Costs included in the risk per trade
  • Open risk calculated across all positions and pending orders
  • New trades blocked when any position has no stop
  • Correlated positions capped together
  • Daily guard reference matched to the written rule and reset time
  • Daily reference stored so it survives restarts
  • Slippage buffer sized from the worst observed fills
  • Sizing tested with rule replay and day-level Monte Carlo

Frequently asked questions

How do I calculate lot size from risk percentage in MQL5?

Convert the risk percentage to money, work out the loss per lot from the stop distance, the tick size and the loss-side tick value, divide one by the other, and round down to the volume step. Skip the trade if the result is below the minimum lot.

What is open risk?

The total loss if every open position, and any pending order that could fill, hit its stop at once. It's the figure to compare with the room left under a daily loss limit.

Should my EA close positions when it gets near the daily limit?

It's a design choice with trade-offs. Blocking new trades is the minimum. Closing positions early can avoid a breach but also cuts trades that might have recovered. Whatever you choose, include it in your testing.

Does a daily guard guarantee I won't breach the rule?

No. Gaps and slippage can move equity past a stop, and rule definitions vary. A guard reduces the risk of avoidable breaches; it doesn't remove the risk of loss.

Do these controls apply to a personal account?

Not in this form. They are designed around prop-firm daily loss rules. A personal account has its own constraints, such as your risk tolerance and your broker's margin requirements.

Want a second pair of eyes?

Start with our free Sample Stress-Test Report. It walks one anonymized, illustrative strategy through a full stress test, start to finish, so you can see what rigorous validation looks like before you test your own.

Read the Sample Stress-Test Report

Want your own backtest checked? The Strategy Audit + 60-minute call is a paid service at a launch price of £100, credited in full against our build and portfolio offers. You send an MT4/MT5 Strategy Tester report or trade-list CSV; what we can check depends on the files you supply, and walk-forward and parameter sweeps are not included because they need the strategy itself. It is analysis of strategy testing, not investment advice, and does not promise any trading or evaluation outcome. See the Strategy Audit

Disclaimers

CollosoTrading provides educational content and analytical services for retail and professional algorithmic traders. We do not provide regulated investment advice, financial advice, or personal recommendations. Trading derivatives, leveraged products, and CFDs carries a high level of risk and may result in losses exceeding deposits. Past performance, including any verified or unverified historical results referenced on this site, is not indicative of future results. Consult an independent regulated financial adviser before making investment decisions.

All figures are backtests or simulations unless marked LIVE. Hypothetical or backtested performance results have inherent limitations and may not reflect actual trading. No representation is made that any account will or is likely to achieve profits or losses similar to those shown. Individual results vary. This article uses no strategy results; any figures you calculate from your own reports are historical simulations. We do not guarantee the outcome of any prop firm challenge.