MQL5

Final lot: double clamp on risk + margin

Combines risk-based sizing and the margin cap in a single function: the volume kept is the more constraining of the two, never the other way around.

Prerequisites

MetaTrader 5, MQL5

MQL5
double ProposedLot(string symbol, ENUM_ORDER_TYPE type,
                   double riskMoney, double slPoints, double maxMarginPct)
{
   double byRisk = LotForRisk(symbol, riskMoney, slPoints);

   double budget   = AccountInfoDouble(ACCOUNT_MARGIN_FREE) * maxMarginPct / 100.0;
   double byMargin = MaxLotByMargin(symbol, type, budget);

   double lot = MathMin(byRisk, byMargin);
   if(lot < SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN))
   {
      PrintFormat("Lot %.2f sous le minimum : trade impossible avec ce budget", lot);
      return 0.0; // refuser plutôt que forcer le lot minimum (risque dépassé)
   }
   PrintFormat("Lot proposé %.2f (risque %.2f / marge %.2f)", lot, byRisk, byMargin);
   return lot;
}

Result

2026.06.10 15:40:22.674  LotEngine (US30,M5)  Lot proposé 0.85 (risque 2.40 / marge 0.85)
2026.06.10 15:40:22.675  LotEngine (US30,M5)  Contrainte active = MARGE (typique sur indices)
2026.06.10 15:41:03.310  LotEngine (EURUSD,M15)  Lot proposé 0.40 (risque 0.40 / marge 7.12)
2026.06.10 15:42:51.928  LotEngine (XAUUSD,M5)  Lot 0.00 sous le minimum : trade impossible avec ce budget
Lot SizingMargeClampMoteur de calcul

Related snippets

Back to the Data Lab