DEV Community

Omais Ali
Omais Ali

Posted on

Position sizing from a risk percent in MQL5, done properly

A common request on EA projects is "risk 1 percent per trade". The math looks simple, but most implementations I review get at least one of these wrong: tick value, lot step, minimum volume, or margin. Here is a version that handles all four.

The idea

You know three things before the trade: account equity, the risk percent, and the stop distance in price. The lot size is the money you are willing to lose divided by the money one lot loses over that stop distance.

The code

double LotsForRisk(string sym, double riskPct, double stopDistance)
{
   if(stopDistance <= 0.0) return 0.0;

   double equity    = AccountInfoDouble(ACCOUNT_EQUITY);
   double riskMoney = equity / (100.0 / riskPct);

   double tickValue = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE_LOSS);
   double tickSize  = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE);
   if(tickValue <= 0.0 || tickSize <= 0.0) return 0.0;

   double lossPerLot = stopDistance / (tickSize / tickValue);
   double lots       = riskMoney / lossPerLot;

   double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
   double vmin = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
   double vmax = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);

   lots -= MathMod(lots, step);            // round down, never up
   if(lots < vmin) return 0.0;             // too small: skip, do not inflate
   if(lots > vmax) lots = vmax;
   return NormalizeDouble(lots, 2);
}
Enter fullscreen mode Exit fullscreen mode

Why each line matters

  1. SYMBOL_TRADE_TICK_VALUE_LOSS rather than plain TICK_VALUE. On cross pairs the loss side value can differ slightly from the profit side because of conversion rates.
  2. Rounding down to the volume step. Rounding to nearest can push you over your risk limit.
  3. Returning zero below the minimum volume. Bumping a 0.004 lot calculation up to 0.01 means you are suddenly risking 2.5 times what you planned. Skipping the trade is the honest answer.
  4. Checking margin afterwards. Call OrderCalcMargin with the result and compare it to free margin before sending, especially on high leverage symbols like gold and indices.

Test it before you trust it

Print the inputs and the result for a few symbols on your broker: a major pair, a cross pair, gold and an index. If the money at risk printed for each one is not close to your target percent, something in the symbol specification is not what you expected, and it is much better to learn that in the log than in the account history.

Top comments (0)