Discussing the article: "Implementing a Circular Buffer Class in MQL5: Fixed-Memory Rolling Windows for Real-Time Indicator Calculations"

 

Check out the new article: Implementing a Circular Buffer Class in MQL5: Fixed-Memory Rolling Windows for Real-Time Indicator Calculations.

A templated CCircularBuffer class for MQL5 replaces the O(n) ArrayCopy array-shift pattern with O(1) insertion using a fixed-capacity ring buffer. The implementation is shown end to end and integrated into a rolling standard deviation indicator. Benchmarks across multiple window sizes compare both approaches and quantify the impact on real-time indicator calculations.

Every indicator that maintains a historical window of price data faces the same mechanical problem on each new bar: the oldest value must be discarded and the newest value must take its place. The conventional MQL5 solution is to shift the internal array one position using ArrayCopy(), then write the new value into index zero.

This pattern appears throughout published indicator code:

double g_window[];

void PushValue(double value, int period)
  {
   ArrayCopy(g_window, g_window, 1, 0, period - 1);
   g_window[0] = value;
  }

The call moves period - 1 double-precision values from their current positions to the next positions in memory. Even though source and destination overlap within the same array, every element is touched. The computational complexity is O(n) where n is the window size — the number of memory write operations grows linearly with the period.

At a 200-period window this amounts to 199 double writes per bar, roughly 1,592 bytes moved on every call. On a modern processor with warm caches this is fast enough to be invisible. The problem is not the constant factor — it is the slope. At 500 periods the work doubles. At 1,000 periods it quadruples. An indicator running on a 5,000-period lookback window must perform nearly 40,000 bytes of memory movement per bar before any actual computation begins.


Author: Ushana Kevin Iorkumbul