Floating-Point Precision and Numeric Pitfalls in MQL4 Trading Code
Summary
This note explains common numeric errors in MQL4 Expert Advisors, focusing on how double-precision values are stored, displayed, compared, and converted to integers. It recommends printing values at higher precision to diagnose unexpected results, accounting for finite precision in arithmetic, rounding prices to the broker’s required digits, and using tolerant comparisons rather than exact equality.
Examples show small residual errors after factorial multiplication and division, integer division producing zero, and a price-point calculation truncating before rounding. The note also flags a potential issue with the MQL4 remainder function and gives a workaround. These examples illustrate programming behavior rather than trading performance. The comparison helper’s fixed decimal tolerance may not suit every instrument or scale, and the note’s remainder warning is explicitly specific to MQL4.
Key ideas
- Display doubles at higher precision when diagnosing unexpected calculations.
- Finite precision can leave small residuals even when mathematical operations should cancel exactly.
- Normalize prices to the precision required by the trading server before submitting orders.
- Use a chosen tolerance when comparing doubles, since exact equality is often unreliable.
- Integer division truncates fractional results, and integer conversions can discard small decimal contributions.
- The article reports an MQL4-specific concern with MathMod and suggests an alternate calculation.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.