My lot size function rounded down to the broker's lot step, and for a $29 risk with a 10 pip stop it gave 0.28 instead of 0.29. Here is the bug in Python, which is the same in most languages.
Code: Select all
import math
risk, stop_pips, pip_value, step = 29.0, 10, 10.0, 0.01
raw = risk / (stop_pips * pip_value) # 0.29
print(raw / step) # 28.999999999999996
print(math.floor(raw / step) * step) # 0.28
Two fixes that work. One is to add a small tolerance before flooring, with math.floor(raw / step + 1e-9) * step. The other is to use Decimal for money and sizes.
Code: Select all
from decimal import Decimal, ROUND_DOWN
lots = Decimal(str(risk)) / (Decimal(stop_pips) * Decimal(str(pip_value)))
lots = lots.quantize(Decimal("0.01"), rounding=ROUND_DOWN) # 0.29