//+------------------------------------------------------------------+ //| LotByRisk.mq5 | //| Copyright 2026, bandersoft | //| https://www.mql5.com/en/users/fats | //+------------------------------------------------------------------+ //| | //| Position sizing from a risk percentage - the thing the library | //| is most often wanted for. | //| | //| Run it on any chart. It places no orders. | //| | //+------------------------------------------------------------------+ #property copyright "Copyright 2026, bandersoft" #property link "https://www.mql5.com/en/users/fats" #property version "1.00" #property script_show_inputs #property description "Calculates lot size for a given risk percentage and stop distance." #include input double RiskPercent = 1.0; // Risk per trade, % of balance input double StopLossPips = 30.0; // Stop distance in pips //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- The pip rule is the forex convention. Instruments where a pip //--- means something else need telling, or every number below is //--- wrong by the same factor: //--- SetPipSize("XAUUSD", 0.1); double pip = GetPipSize(); double lots = CalcLotSizeByRisk(RiskPercent, StopLossPips); if(lots <= 0) { //--- 0 is deliberate, not a glitch: the risk budget does not //--- cover one minimum lot. Rounding up would risk more than //--- was asked for, so the library refuses instead. PrintFormat("Cannot size a trade risking %.2f%% over %.1f pips on %s.", RiskPercent, StopLossPips, _Symbol); PrintFormat("Minimum lot is %.2f, which needs a wider stop or a larger balance.", SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN)); return; } double risked = CalcValueAtRisk(lots, StopLossPips); double stopDistance = PipsToPrice(StopLossPips); double entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK); PrintFormat("%s 1 pip = %s balance %.2f %s", _Symbol, DoubleToString(pip, _Digits), AccountInfoDouble(ACCOUNT_BALANCE), AccountInfoString(ACCOUNT_CURRENCY)); PrintFormat("Risking %.2f%% over a %.1f pip stop:", RiskPercent, StopLossPips); PrintFormat(" lot size %.2f", lots); PrintFormat(" money at risk %.2f %s", risked, AccountInfoString(ACCOUNT_CURRENCY)); PrintFormat(" buy at %s", FormatPrice(entry)); PrintFormat(" stop at %s", FormatPrice(entry - stopDistance)); PrintFormat(" reward:risk 1:%.2f at a %.1f pip target", CalcRiskRewardRatio(entry, entry - stopDistance, entry + stopDistance * 2), StopLossPips * 2); } //+------------------------------------------------------------------+