EA Risk Management for MT5: Position Sizing, SL/TP, Trailing Stops

Size every trade from its stop: the lot formula from tick value and tick size, volume-step rounding, stop and freeze levels, trailing stops and a daily-loss guard.

📖 13 min read

📝 2,522 words

🏷️ MQL5 and Expert Advisors

Share this article:

EA Risk Management in MetaTrader 5: Size Every Trade From Its Stop

Short answer: decide the most you accept to lose on one trade, as a % of the account; place the stop where the strategy needs it; then compute the lot from the stop distance with the broker's tick value and tick size:

Lot = (balance × risk % ÷ 100) ÷ (stop distance ÷ tick size × tick value)

Round the lot down to the volume step, skip the trade if it is below the minimum volume, keep the stop outside the broker's stop level, and add a daily-loss guard that stops new trades for the rest of the day. Read every number from your broker in code with SymbolInfoDouble [1]; none of them should be typed in, because they differ between brokers, symbols and account currencies.

This guide shows the formula, worked shapes for EURUSD, gold, an index and a JPY pair, volume-step rounding, stop and freeze levels, stops and trailing, a daily-loss guard, and the same rules set without code.

Part of the MQL5 and Expert Advisors academy.


The Lot Size Formula: Tick Value and Tick Size

Three numbers turn "I risk 1 %" into a lot size. All three come from the broker, per symbol:

PropertyWhat it isRead it with
SYMBOL_TRADE_TICK_SIZEThe smallest price change of the symbolSymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE)
SYMBOL_TRADE_TICK_VALUEWhat one tick is worth for one lot, in your account currencySymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE)
SYMBOL_VOLUME_STEP, _MIN, _MAXThe lot grid and its limitsSymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP)

The steps:

  1. Risk money = balance (or equity) × risk % ÷ 100. Balance comes from AccountInfoDouble [2].
  2. Ticks in the stop = stop distance in price ÷ tick size. Work in price, not in "pips": a pip means different things on different symbols.
  3. Loss per lot = ticks in the stop × tick value.
  4. Raw lot = risk money ÷ loss per lot. Then round it (next sections).
mql5
// Raw lot for a risk in % of the balance and a stop distance in price.
// Every symbol value comes from the broker; nothing is typed in.
double RawLotForRisk(double riskPercent, double stopDistance)
{
   double balance   = AccountInfoDouble(ACCOUNT_BALANCE);
   double riskMoney = balance * riskPercent / 100.0;
   double tickSize  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   if(tickSize <= 0.0 || tickValue <= 0.0 || stopDistance <= 0.0)
      return 0.0;                                    // no data: do not trade
   double lossPerLot = stopDistance / tickSize * tickValue;
   return riskMoney / lossPerLot;
}

When the account currency is not the symbol's quote currency, the tick value moves with the exchange rate, so read it at the moment you size the trade. MQL5 also has SYMBOL_TRADE_TICK_VALUE_LOSS for losing positions. To check the result, OrderCalcProfit (opens in a new tab) [3] returns the money one lot would make or lose between the entry and the stop price; it should match your loss per lot.


Worked Shapes: EURUSD, XAUUSD, an Index and a JPY Pair

The formula is the same everywhere; what changes is how you write the stop and where the tick value comes from. The numbers to put in are your broker's values, read in code; this table shows the shape, not anyone's contract.

SymbolWrite the stop asTicks in the stopWhere the tick value comes fromWatch out for
EURUSDA price distance: 20 pips = 0.00200.0020 ÷ tick sizeThe quote currency is USD: fixed per lot in a USD account, it moves with EURUSD in a EUR accountOn a 5-digit quote, 1 pip = 10 points; code that mixes the two sizes trades 10 times too big or small
XAUUSD (gold)A price distance in USD: a $5.00 move = 5.005.00 ÷ tick sizeThe contract size per lot (SYMBOL_TRADE_CONTRACT_SIZE) times the tick size, in USD, converted to your account currencyContract size, digits and volume step differ between brokers; "pips" on gold mean different things, so stay in price
An index CFDIndex points: 40 points = 40.040.0 ÷ tick sizeThe broker's value per point per lot, often in the index's own currency (EUR for a German index)The tick size is often not the point, and the volume step may be 0.1 or 1 lot
A JPY pair (USDJPY)A price distance: 30 pips = 0.300.30 ÷ tick sizeThe quote currency is JPY, converted to your account currency at the current rate, so it changes every dayOn a 3-digit quote, 1 pip = 0.01 = 10 points

A quick sanity check for any symbol: open one minimum lot on a demo account, move the stop by a known price distance, and compare the change in the shown loss with your loss per lot × the lot. If they differ, your code reads the wrong property or mixes points and pips. More on gold's specifics: Gold EA (XAUUSD).


Round the Lot to the Volume Step

A broker accepts only lots on its grid: a whole number of SYMBOL_VOLUME_STEP (opens in a new tab), between SYMBOL_VOLUME_MIN and SYMBOL_VOLUME_MAX. Any other volume is refused (retcode 10014, invalid volume). Three rules:

  • Round down, never to the nearest: rounding up would risk more than you chose.
  • If the rounded lot is below the minimum, skip the trade. Raising it to the minimum quietly breaks your risk limit; it is a sign the stop is too wide for the account.
  • Cap at the maximum, and check the margin before you send.
mql5
// Round a raw lot down to the broker's volume step; 0 means "skip this trade".
double NormalizeLot(double rawLot)
{
   double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double vmin = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double vmax = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   if(step <= 0.0)
      return 0.0;
   double lot = MathFloor(rawLot / step + 1e-9) * step;   // down, never up
   if(lot < vmin)
      return 0.0;                                         // too small for the risk: skip
   lot = MathMin(lot, vmax);
   int decimals = (int)MathMax(0.0, MathCeil(-MathLog10(step)));
   return NormalizeDouble(lot, decimals);
}

The small 1e-9 keeps a lot that is exactly on the grid (0.3 / 0.01 is 29.999… in floating point) from dropping one step. Before OrderSend, OrderCalcMargin [4] gives the margin the lot needs; compare it with ACCOUNT_MARGIN_FREE.


Stop Level and Freeze Level

Two broker limits, both in points, both symbol properties [5] read with SymbolInfoInteger (opens in a new tab) [6]:

PropertyWhat it limitsIf you ignore it
SYMBOL_TRADE_STOPS_LEVELThe minimum distance between the current price and a new stop loss, take profit or pending orderThe order is refused: retcode 10016, invalid stops
SYMBOL_TRADE_FREEZE_LEVELThe distance inside which a pending order or a position's stops cannot be changed or deletedThe change is refused: retcode 10029, frozen

A buy position closes at Bid, so its stops are checked against Bid; a sell position closes at Ask, so against Ask. A level of 0 does not always mean "no limit": some brokers apply a floating level, so keep a small buffer and log the return code of every refused request.

mql5
// True when a new buy or sell may carry these stops (0 = no stop).
bool StopsAllowed(bool isBuy, double sl, double tp)
{
   double point   = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   double minDist = (double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * point;
   double bid     = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double ask     = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   if(isBuy)
      return (sl == 0.0 || bid - sl >= minDist) && (tp == 0.0 || tp - bid >= minDist);
   return (sl == 0.0 || sl - ask >= minDist) && (tp == 0.0 || ask - tp >= minDist);
}

Before you move a stop (trailing, breakeven), check the freeze level the same way: if the current stop is within SYMBOL_TRADE_FREEZE_LEVEL points of the price, leave it. Put every price on the tick grid too: round it to a whole number of SYMBOL_TRADE_TICK_SIZE, then NormalizeDouble to the symbol's digits. Full fix guide: MT5 error 10016 (invalid stops).


Stop Loss, Take Profit and Trailing Stop

Stop loss below and take profit above an entry, with a trailing stop stepping up behind it.take profitentrystop losstrailing stop follows
Where the risk levels sit around an entry. Positions only — the drawing says nothing about what happens.

Orders go out through OrderSend, one of the MQL5 trade functions [7]. In MqlTradeRequest (opens in a new tab) [8], sl and tp are prices, not distances. A buy has its stop below the entry and its target above; a sell the other way round. The stop distance you size the lot from is the one you send.

mql5
double ask  = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double tick = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
int digits  = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double stopDistance = 0.0020;                        // your rule, as a price distance
double lot = NormalizeLot(RawLotForRisk(1.0, stopDistance));
double sl  = NormalizeDouble(MathRound((ask - stopDistance) / tick) * tick, digits);
double tp  = NormalizeDouble(MathRound((ask + 2.0 * stopDistance) / tick) * tick, digits);
if(lot > 0.0 && StopsAllowed(true, sl, tp))
{
   MqlTradeRequest req = {};
   MqlTradeResult  res = {};
   req.action    = TRADE_ACTION_DEAL;
   req.symbol    = _Symbol;
   req.volume    = lot;
   req.type      = ORDER_TYPE_BUY;
   req.price     = ask;
   req.sl        = sl;
   req.tp        = tp;
   req.deviation = 10;
   req.magic     = InpMagic;
   if(!OrderSend(req, res))
      Print("OrderSend failed, retcode ", res.retcode);
}

ATR stops. A stop at a multiple of ATR (iATR [9] and CopyBuffer) follows volatility: wider when the market moves more. With % risk, a wider stop simply gives a smaller lot for the same money at risk.

Trailing stop. On each tick, for each of the EA's positions, move the stop toward the price when the price has moved far enough, and never back. For a buy, the new stop is Bid minus the trail distance; send it with TRADE_ACTION_SLTP only if it is above the current stop and outside the stop and freeze levels. A trailing stop changes where a trade exits, not how much it risked at entry.

For trades you open by hand, not the EA: Manage trades you open yourself in MT5.


A Daily-Loss Guard

A daily-loss guard stops the EA from adding losses on a bad day. It needs three decisions: when a trading day starts (the broker's midnight or your own hour), what it measures (equity, so open trades count), and what happens when the limit is reached (close this EA's trades, delete its pending orders, open nothing until the next day).

mql5
input double InpDailyLossPct = 3.0;   // your limit, % of the equity at the day's start

// Equity at the start of today's trading day, kept across restarts in a terminal global variable.
double DayStartEquity()
{
   MqlDateTime t;
   TimeToStruct(TimeCurrent(), t);
   string key = StringFormat("dayStart_%I64d_%04d%02d%02d", (long)InpMagic, t.year, t.mon, t.day);
   if(!GlobalVariableCheck(key))
      GlobalVariableSet(key, AccountInfoDouble(ACCOUNT_EQUITY));
   return GlobalVariableGet(key);
}

bool DailyLossReached()
{
   double start = DayStartEquity();
   double lost  = start - AccountInfoDouble(ACCOUNT_EQUITY);
   return lost >= start * InpDailyLossPct / 100.0;
}

// In OnTick(): if(DailyLossReached()) { close this EA's positions, delete its orders, return; }

This sketch uses the broker's server day (TimeCurrent) and the whole account's equity. If several EAs share the account, decide whether the limit is per EA or per account. Prop-firm accounts define the day's start and the measure in their own rules, and they apply them to the whole account: see Prop firm EA rules for MT5. Test the guard in the Strategy Tester on a stretch with a bad day in it: Backtest in the Strategy Tester.


More Account Safeguards

SafeguardWhat it stopsHow
Open positionsA bug that opens trade after tradeCount positions with your magic number before each entry
Margin check"Not enough money" refusals and margin callsOrderCalcMargin against ACCOUNT_MARGIN_FREE
Entries per dayOver-trading in noisy marketsCount today's entries; stop at your limit
Losing streakTrading on while the market does not suit the rulesCount consecutive losses; pause until the next day or a restart
Maximum drawdownA slow slide past what you acceptCompare equity with its peak; stop the EA when the fall reaches your limit
Largest positionOne oversized trade from a wide-stop formula errorCap the lot; skip the trade if the cap is below the minimum

Never "fix" a losing run by adding to it. Grid and martingale schemes raise the size after losses, so their worst day is far worse than any single trade's stop suggests.


Set These Risk Rules Without Code

The rules above are fields in the AlfaTactix Strategy Builder, which writes them into a readable MQL5 Expert Advisor:

  • Step 5, Exits: stop loss, take profit, trailing stop and breakeven, per side.
  • Step 6, Risk and money management: position size as risk per trade (% of the account), cash risk or fixed lots; open positions; when a trading day starts; entries per day; daily loss limit; maximum drawdown; losing streak; largest position.

For the daily loss limit, the form states what happens when it is reached: the robot closes all trades of the strategy, cancels its pending orders and opens no new trade until the next trading day. Some of these fields are in the paid plans; Pricing lists which.

Tactix Studio, the AI assistant on the paid plans, fills the same form from a description. Tactix Studio never writes risk above 10 % of the account per trade (the schema maximum); above 2 % it writes the value with a warning, above 5 % only after you confirm. It never invents risk numbers: they come from you or from the published defaults, marked "Assumed". The AI never builds grid or martingale strategies. See Tactix Studio.

In the AlfaTactix backtest, every stop loss, take profit, trailing stop and breakeven level is put on the symbol's tick grid, rounded away from the entry; position size and 1R use the raw distance. How the engine works and its limits: Backtest engine.

A backtest is not a forecast; past results do not predict future results.


Troubleshooting

SymptomCauseFix
Retcode 10016, invalid stopsStop or target inside the stop level, or on the wrong sideCheck against Bid (buy) or Ask (sell) with SYMBOL_TRADE_STOPS_LEVEL; put prices on the tick grid
Retcode 10014, invalid volumeLot off the volume step or outside min/maxRound down to SYMBOL_VOLUME_STEP with NormalizeLot
Retcode 10019, not enough moneyLot too large for the free marginSize from risk; check OrderCalcMargin before sending
Retcode 10029, frozenStop changed inside the freeze levelSkip the change while the price is within SYMBOL_TRADE_FREEZE_LEVEL
Lot is 0, no tradesStop too wide for the risk, so the lot is below the minimumExpected: the rule protects the account. Narrow the stop or accept the skip
Lot 10 times too big or smallPoints and pips mixed, or a forex tick value assumedWork in price; read tick size and tick value from the broker

All return codes: MQL5 trade return codes [10].


Next Steps

Test the sizing and the daily-loss guard in the MT5 Strategy Tester, then on demo: Deploy and maintain an EA. For funded accounts: Prop firm EA rules. To set the same rules in a form: Build an EA without coding.

Frequently Asked Questions

Risk money = balance × risk % ÷ 100. Loss per lot at the stop = stop distance ÷ SYMBOL_TRADE_TICK_SIZE × SYMBOL_TRADE_TICK_VALUE. Lot = risk money ÷ loss per lot. Then round the lot down to SYMBOL_VOLUME_STEP and skip the trade if it falls below SYMBOL_VOLUME_MIN. Read every value from your broker with SymbolInfoDouble; never type them in.

Tick size is the smallest price change of the symbol. Tick value is what that change is worth for one lot, in your account currency. Together they turn a stop distance in price into money per lot. MQL5 also has SYMBOL_TRADE_TICK_VALUE_LOSS and _PROFIT, which can differ slightly when the account currency is not the quote currency.

Usually because the code works in pips or points and assumes forex values. On gold and index CFDs the tick size is often not the point, and the contract size and its currency differ by broker. Work with the stop as a price distance, divide by the tick size and multiply by the tick value your broker reports.

Round down to a whole number of SYMBOL_VOLUME_STEP, so the risk never goes above your limit, then cap it at SYMBOL_VOLUME_MAX. If the result is below SYMBOL_VOLUME_MIN, skip the trade: rounding up to the minimum would risk more than you chose.

SYMBOL_TRADE_STOPS_LEVEL is the minimum distance, in points, between the current price and a new stop loss, take profit or pending order; closer ones are refused (retcode 10016). SYMBOL_TRADE_FREEZE_LEVEL is the distance inside which an order or a position's stops cannot be changed. Buy stops are checked against Bid, sell stops against Ask.

Store the equity at the start of each trading day. On every tick, compare it with the current equity; when the loss reaches your limit, close the EA's positions, delete its pending orders and open nothing until the next day. Keep the day's start value in a global variable of the terminal so a restart does not reset it.

A fixed lot is simple but ignores the stop distance and the account size: the same 0.1 lot risks very different amounts with a 10-pip and a 100-pip stop. A % risk sizes each trade from its own stop, so every trade risks the same share of the account.

Yes. In the AlfaTactix Strategy Builder, Step 5 sets the stop, the target, the trailing stop and breakeven, and Step 6 the position size (risk per trade as a % of the account, cash risk or fixed lots), open positions and the daily loss limit. Tactix Studio never writes risk above 10 % of the account per trade, and the AI never builds grid or martingale strategies.

References

  1. MetaQuotes, MQL5 Reference. SymbolInfoDouble. https://www.mql5.com/en/docs/marketinformation/symbolinfodouble
  2. MetaQuotes, MQL5 Reference. AccountInfoDouble. https://www.mql5.com/en/docs/account/accountinfodouble
  3. MetaQuotes, MQL5 Reference. OrderCalcProfit. https://www.mql5.com/en/docs/trading/ordercalcprofit
  4. MetaQuotes, MQL5 Reference. OrderCalcMargin. https://www.mql5.com/en/docs/trading/ordercalcmargin
  5. MetaQuotes, MQL5 Reference. Symbol Properties. https://www.mql5.com/en/docs/constants/environment_state/marketinfoconstants
  6. MetaQuotes, MQL5 Reference. SymbolInfoInteger. https://www.mql5.com/en/docs/marketinformation/symbolinfointeger
  7. MetaQuotes, MQL5 Reference. Trade Functions. https://www.mql5.com/en/docs/trading
  8. MetaQuotes, MQL5 Reference. The Trade Request Structure (MqlTradeRequest). https://www.mql5.com/en/docs/constants/structures/mqltraderequest
  9. MetaQuotes, MQL5 Reference. iATR. https://www.mql5.com/en/docs/indicators/iatr
  10. MetaQuotes, MQL5 Reference. Return Codes of the Trade Server. https://www.mql5.com/en/docs/constants/errorswarnings/enum_trade_return_codes