MQL5 Circular Buffers for Efficient Rolling Indicator Windows
Summary
The article explains how a fixed-capacity circular buffer can replace repeated array shifting when maintaining rolling market data in MQL5. Rather than moving every stored value on each update, the buffer advances a head index and overwrites the oldest slot, making insertion and offset-based reads constant-time. It describes a templated class with count and capacity tracking, reset and export operations, and rolling mean and variance calculations. For variance, it favors a two-pass calculation to reduce catastrophic cancellation when price levels are large relative to their dispersion.
A rolling standard-deviation indicator and scripts for cross-validation and benchmarking demonstrate how the class can be used and assessed. The article contrasts the insertion cost with array shifting across several window sizes, though the supplied text does not include the actual benchmark results. The buffer has fixed capacity and is intended for numeric data; statistical queries still traverse the window, and applications that resize windows frequently or require nonnumeric behavior are poor fits.
Key ideas
- A circular buffer replaces per-update array shifts with a head-index advance and one overwrite.
- The buffer supports constant-time pushes and reads by recency offset, while rolling statistics require traversing stored values.
- Tracking the number of valid entries prevents uninitialized slots from being treated as real observations.
- A two-pass variance calculation avoids precision loss that can affect a one-pass formula on price data.
- The implementation suits fixed-capacity numeric windows, while frequent resizing and nonnumeric statistics fall outside its intended use.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.