Stable Accumulators
A naive running total (sum += value, repeated for hours or days) loses low-order bits every time a small value is added to a large running sum - each addition's rounding error is simply thrown away, and thousands of tiny errors compound into a visibly wrong total. This is not a theoretical concern: an EA accumulating tick-by-tick P/L, spread or slippage over a multi-day run on a naive double accumulator measurably drifts from the true total, and the drift is silent - no error, no warning, just a wrong number that still looks plausible. Kahan summation carries a running compensation term that recovers almost all of the rounding error a plain addition would lose, at the cost of three extra floating-point operations per value added - a decades-old, textbook fix that most hand-rolled MQL4 running totals never bother with. This header applies the same compensated-accumulation idea to a running mean and variance too (via Welford's online algorithm, with the variance term's own accumulation independently Kahan-compensated), so a long- running statistics tracker does not just get an accurate sum but an accurate mean and standard deviation as well. Notes and limitations - Kahan summation greatly reduces rounding error but does not eliminate it entirely - it is not exact arbitrary-precision arithmetic, just a far tighter bound on the accumulated error than a naive running sum. - KahanVarianceSample and KahanVariancePopulation both return 0.0 on too few observations (fewer than two, and zero respectively) rather than a division-by-zero result or an error - check KahanCount() first if the caller needs to distinguish "no data yet" from "genuinely zero spread". - The struct carries no locking or thread-safety concept, which is not meaningful in MQL4's single-threaded execution model, but a shared KahanAccumulator must still not be updated by two different code paths in the same tick without the caller coordinating that itself.
Script · MT4 · v1.0 · Free
About Stable Accumulators
Stable Accumulators is a script for MetaTrader 4. It has 1 setting, such as Sample count. MQL source code included.
Files in the download: StableAccumulators.mqh, StableAccumulators.txt, StableAccumulatorsDemo.mq4.
Settings
| Setting | Default | What it does |
|---|---|---|
| Sample count | 1000000 | how many 0.1 values to accumulate |
How to install
- Download the ZIP from your PolyMaria library and unzip it.
- In MetaTrader 4 open File → Open Data Folder, then go to MQL4 → Scripts.
- Copy the .mq4 file(s) there. Put any .mqh files in MQL4 → Include.
- Open the .mq4 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
- Drag the script onto a chart to run it once.
Tags: MT4 Script · MQL4 Source Code