Position size sounds like a big topic, but the core is one division. Here it is for gold (XAUUSD), with the two traps that break naive versions.

The formula

lots = money at risk / (stop distance in dollars x contract size) 

On most brokers one lot of XAUUSD is 100 ounces. Some brokers and cent accounts differ, so treat the contract size as an input, not a constant.

The code

function goldLots({ balance, riskPercent, stopDistance, contractSize = 100, step = 0.01 }) { if (!(balance > 0 && riskPercent > 0 && stopDistance > 0 && contractSize > 0)) return null; const money = (balance * riskPercent) / 100; const raw = money / (stopDistance * contractSize); const steps = Math.floor(raw / step + 1e-9); return Number((steps * step).toFixed(2)); } 

Trap 1: rounding up

Use Math.floor, not Math.round. Rounding up means risking more than the user asked for. The tiny 1e-9 stops floating point noise from dropping a whole step.

Trap 2: hiding "too small"

Sometimes the honest answer is zero. If the stop is wide and the account is small, even the minimum lot risks too much. Return 0 and say so in the interface. Do not quietly bump it to 0.01.

Check it

Balance Risk Stop Result
$1,000 1% $5 0.02
$500 1% $5 0.01
$1,000 1% $10 0.01
$1,000 1% $12 0

The function ignores spread, commission and slippage, so a real loss can be larger.

If you want to try the numbers without code, there is a free XAUUSD lot size calculator on TickMeridian, a project I work on.

Education only, not financial advice.