CRingBuffer
- Kütüphaneler
- Christian Stern
- Sürüm: 1.0
- Etkinleştirmeler: 10
CRingBuffer - Numeric ring buffer with lightweight high-performance statistics engine
CRingBuffer is a powerful MQL5 library for numeric rolling-window analysis. After each insertion it immediately provides
mean, variance, standard deviation, percentiles, z-scores, min/max tracking and normalized values - all in O(1) to O(n log n).
Table of contents:
- Application area
- Two operating modes
- Basic statistics
- Welford statistics (numerically stable, recommended for large price levels)
- Percentiles
- Z-score analysis (three modes)
- Min/max tracking (O(1))
- Min-max normalization
- Placeholder logic
- Virtual index
- Extendability through inheritance (6 event hooks)
- Statistics snapshot via RBufStats (30+ metrics in one object)
- Advantages
- Example
- Statistics functions at a glance
- Updates & Support
1. Application area:
CRingBuffer is designed for MQL5 developers who need statistical rolling-window analysis in indicators, expert advisors or libraries
.
Typical use cases:
- Continuous market observation (price, spread, volume, ATR values)
- Normalization of signals to [0,1] for scoring systems
- Z-score-based outlier detection in real time or in backtests
- Percentile-based threshold determination (timeframe-robust)
- Building custom indicator calculation layers through inheritance
- Component in multi-layer class architectures
- Data collection in event-based systems with variable history length
Not suitable for:
- Real-time order book analysis with very high tick frequency (no lock-free parallel processing)
- Storage of non-numeric data
2. Two operating modes:
- Static buffer: fixed window size, oldest values are automatically
overwritten. Ideal for ATR-14, RSI-14 or any rolling windows.
- Dynamic buffer: window size can be changed at runtime. Individual values
can be removed. Capacity grows or shrinks as needed.
3. Basic statistics (all O(1) after insertion):
- Sum, sum of squares
- Arithmetic mean
- Bessel-corrected sample variance and standard deviation
4. Welford statistics (numerically stable, recommended for large price levels):
- Welford mean, Welford variance, Welford standard deviation
- Robust against cancellation effects in long series or at high price levels
(e.g. BTCUSD ~100,000 or Nasdaq index)
5. Percentiles:
- getPercentile() - single percentile with linear interpolation (Hyndman & Fan, method 7)
- getPercentiles() - multiple percentiles in a single sorted pass
- Placeholders (EMPTY_VALUE, NaN, Inf) are automatically filtered out
6. Z-score analysis (three modes):
- getLastZScore() - current z-score of the newest value
- getZScoreAt() - look-ahead-free z-score for backtesting
- getZScores() - expanding window (look-ahead-free) or rolling for all buffer values at once
7. Min/max tracking (O(1)):
- Running minimum and maximum of all valid values
- Virtual positions of min and max retrievable as indices
- Range (max - min) available at any time
- Smoothed range history for trend analysis
8. Min-max normalization:
- getNormalizedValue() - normalize any value to [0,1]
- getNormalizedValueAt() - normalize value at a virtual index
- getNormalizedValues() - export all buffer values in normalized form
- Fallback 0.5 for constant data (defined behavior, not an error)
9. Placeholder logic:
- EMPTY_VALUE, NaN and Inf are detected automatically
- They occupy a slot but are not considered in any statistic
- MQL5 indicator buffers are initially filled with EMPTY_VALUE - this
filtering prevents statistical distortion without additional code
10. Virtual index:
- Uniform addressing: index 0 = oldest, index n-1 = newest value
- Internal ring buffer mechanics are fully transparent to the caller
11. Extendability through inheritance (6 event hooks):
- OnAddValue() - after each insertion
- OnRemoveValue() - on removal or overwrite
- OnChangeValue() - after replaceValue()
- OnChangeArray() - after each structural change
- OnSetMaxTotal() - after a capacity change
- OnShrink() - after buffer reduction
- All hooks fire after the statistics have been fully updated
12. Statistics snapshot via RBufStats (30+ metrics in one object):
- Group A: Basic statistics (mean, variance, stddev, min, max, range, sum,
total_count, valid_count, last_value, previous_value, oldest_value,
min_index, max_index, avg_range, avg_diff, fill_rate)
- Group B: Welford statistics (welford_mean, welford_variance, welford_stddev)
- Group C: Percentiles (Q05, Q10, Q25, Median, Q75, Q90, Q95, IQR)
- Group D: Z-score and normalization (zscore, zscore_prev, zscore_delta,
norm_last, norm_oldest)
- Validation method Validate(), copy constructor, operator=()
13. Advantages:
- No custom ring buffer code required: replaces several hundred lines of recurring boilerplate implementation
- Numerically stable Welford method available in parallel to the sum formula
- Three z-score modes including a look-ahead-free mode for backtest-compliant signal evaluation
- Automatic placeholder filtering prevents statistical distortion caused by EMPTY_VALUE initialization of MQL5 indicator buffers
- Incremental O(1) update of all statistics after each insert - no expensive recalculation during queries
- Fully extendable through inheritance and event hooks without changing the base class
- Uniform virtual index hides the complexity of the internal ring buffer
- Complete English documentation (API reference, behavioral details, code examples, pitfalls)
14. Example:
1. Copy CRingBuffer.ex5 to the desired project directory
2. Include it in the MQL5 file:
#include "CRingBuffer_standalone.ex5"
3. Instantiate buffer:
CRingBuffer buf(20, false); // Static buffer, capacity 20 CRingBuffer dyn(20, true); // Dynamic buffer
4. Add values and retrieve statistics:
buf.addValue(close[0]); double mean = buf.getMean(); double stddev = buf.getWelfordStdDev(); double zscore = buf.getLastZScore();
No further dependencies. The library is completely self-contained.
15. Statistics functions at a glance
| Group | Methods | Benefit |
|---|---|---|
| Basic statistics | getSum(), getSumSq(), getMean(), getVariance(), getStdDev() | Provides the classic metrics for mean, dispersion and total sum of valid values. |
| Welford statistics | getWelfordMean(), getWelfordVariance(), getWelfordStdDev() | Offers numerically more stable alternatives for long series, high price levels and small value differences. |
| Min/max tracking | getMin(), getMax(), getMinIndex(), getMaxIndex(), getMinMaxRange() | Describes extreme values, their positions and the current buffer range for fast state assessments. |
| Range history | getAverageRange(), getRangeHistory() | Shows how the range evolves over time and supports volatility analysis. |
| Average change | getAverageDiff() | Measures the average absolute change between consecutive valid values and helps assess market dynamics. |
16. Updates & Support:
- Support exclusively via the internal MQL5 communication system
- Error reports and improvement suggestions are answered promptly
