I needed this in every EA so here it is as one small include file. It calculates the position size (lot) for a trade from the risk you want to take and the stop loss distance.
You give it entry, stop loss and the risk in % (or a fixed money amount) and it gives you back the lot. It uses tick value and tick size of the symbol, so it works for gold, indices and forex the same way. The lot is always rounded DOWN to the volume step, so the real risk is never higher than what you set. If the lot would be below the minimum lot it returns 0 instead of opening a bigger trade than planned. It also checks the free margin and makes the lot smaller if the margin is not enough.

Demo script output in the Experts journal
Functions
Both lot functions have an optional last parameter maxMarginShare (default 0.8 = max 80 % of free margin for this trade).
Usage
#include <LS_RiskLot.mqh> double lot = LS_LotByRisk(_Symbol, ORDER_TYPE_BUY, entry, sl, 1.0); // 1 % of balance if(lot > 0) trade.Buy(lot, _Symbol, entry, sl, tp);
Demo script
The small script LS_RiskLot_Demo shows how to use it: drop it on a chart, set risk and stop in points and it prints the lot and the real risk in the Experts journal. It doesnt open any trade. Inputs: InpRiskPct (risk in % of balance, 0 = use money), InpRiskMoney (risk in account currency), InpStopPts (stop distance in points), InpBuy (buy or sell side).
Small accounts: with 0.01 minimum lot and a wide stop the function can return 0. Thats on purpose, better no trade than 3x the risk.
Closed Trades to CSV - one row per closing deal (partial closes, reversals)
Exports closed trades to a CSV file, one row per closing deal: partial closes, close-by and netting reversals are split, each row with the position's open time, volume-weighted open price and its share of the entry commission.
XAUUSD Hourly Volatility Clock: typical range by hour vs today
A 24-hour clock of typical H1 ranges for XAUUSD (and any other symbol) versus the range of the current hour. The profile uses closed hours only. Display only — it does not trade.
Auto Fibonacci Retracement on the Latest Swing
Detects swing highs and lows automatically and draws Fibonacci retracement levels on the latest completed swing leg. The levels move to the new leg as soon as a new swing is confirmed; the levels, their colors and the swing sensitivity are configurable.
False Breakout Envelope
False breaks at an ATR envelope, drawn as trades: price pushes through a band, closes back inside, and a box runs from the entry to the moving midline, with the stop as a thick line. Each label prints the win rate of earlier signals in the same RSI zone, and a corner card charts it for every zone.