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:
| Property | What it is | Read it with |
|---|---|---|
SYMBOL_TRADE_TICK_SIZE | The smallest price change of the symbol | SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE) |
SYMBOL_TRADE_TICK_VALUE | What one tick is worth for one lot, in your account currency | SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE) |
SYMBOL_VOLUME_STEP, _MIN, _MAX | The lot grid and its limits | SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP) |
The steps:
- Risk money = balance (or equity) × risk % ÷ 100. Balance comes from
AccountInfoDouble[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.
- Loss per lot = ticks in the stop × tick value.
- Raw lot = risk money ÷ loss per lot. Then round it (next sections).
// 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.
| Symbol | Write the stop as | Ticks in the stop | Where the tick value comes from | Watch out for |
|---|---|---|---|---|
| EURUSD | A price distance: 20 pips = 0.0020 | 0.0020 ÷ tick size | The quote currency is USD: fixed per lot in a USD account, it moves with EURUSD in a EUR account | On 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.00 | 5.00 ÷ tick size | The contract size per lot (SYMBOL_TRADE_CONTRACT_SIZE) times the tick size, in USD, converted to your account currency | Contract size, digits and volume step differ between brokers; "pips" on gold mean different things, so stay in price |
| An index CFD | Index points: 40 points = 40.0 | 40.0 ÷ tick size | The 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.30 | 0.30 ÷ tick size | The quote currency is JPY, converted to your account currency at the current rate, so it changes every day | On 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.
// 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]:
| Property | What it limits | If you ignore it |
|---|---|---|
SYMBOL_TRADE_STOPS_LEVEL | The minimum distance between the current price and a new stop loss, take profit or pending order | The order is refused: retcode 10016, invalid stops |
SYMBOL_TRADE_FREEZE_LEVEL | The distance inside which a pending order or a position's stops cannot be changed or deleted | The 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.
// 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
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.
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).
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
| Safeguard | What it stops | How |
|---|---|---|
| Open positions | A bug that opens trade after trade | Count positions with your magic number before each entry |
| Margin check | "Not enough money" refusals and margin calls | OrderCalcMargin against ACCOUNT_MARGIN_FREE |
| Entries per day | Over-trading in noisy markets | Count today's entries; stop at your limit |
| Losing streak | Trading on while the market does not suit the rules | Count consecutive losses; pause until the next day or a restart |
| Maximum drawdown | A slow slide past what you accept | Compare equity with its peak; stop the EA when the fall reaches your limit |
| Largest position | One oversized trade from a wide-stop formula error | Cap 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
| Symptom | Cause | Fix |
|---|---|---|
| Retcode 10016, invalid stops | Stop or target inside the stop level, or on the wrong side | Check against Bid (buy) or Ask (sell) with SYMBOL_TRADE_STOPS_LEVEL; put prices on the tick grid |
| Retcode 10014, invalid volume | Lot off the volume step or outside min/max | Round down to SYMBOL_VOLUME_STEP with NormalizeLot |
| Retcode 10019, not enough money | Lot too large for the free margin | Size from risk; check OrderCalcMargin before sending |
| Retcode 10029, frozen | Stop changed inside the freeze level | Skip the change while the price is within SYMBOL_TRADE_FREEZE_LEVEL |
| Lot is 0, no trades | Stop too wide for the risk, so the lot is below the minimum | Expected: the rule protects the account. Narrow the stop or accept the skip |
| Lot 10 times too big or small | Points and pips mixed, or a forex tick value assumed | Work 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.

