Loading…

Reservoir Sampler

A long-running EA that wants to sample its own tick stream for diagnostics - spread distribution, slippage, latency, anything worth spot-checking - faces an awkward choice. Store every value and memory grows without bound for as long as the EA runs. Keep only the first N values and the "sample" is really just whatever happened to trade when the EA started, which is not a sample of the stream at all. Algorithm R (Vitter, 1985) solves this with fixed memory and no bias. The first 'capacity' values fill the reservoir outright. Every value after that replaces a uniformly random existing slot with probability capacity/itemsSeenSoFar - the specific probability that keeps every item the stream has produced, no matter how early or late it arrived, equally likely to be the one still sitting in the reservoir when the run ends. RS_RandomIndex is the one place accuracy actually depends on: MathRand() only returns a value in 0..32767 on both platforms, which would silently bias the replacement decision the moment a stream produces more than 32767 items - precisely the regime reservoir sampling exists for. This library combines two MathRand() calls into a wider random index so the sample stays unbiased for streams well beyond that range. Notes and limitations - The sample size is min(capacity, itemsSeen) - a stream shorter than capacity returns every item seen so far, not a reservoir padded with zeros or anything else. - This is unweighted, uniform sampling: every item ever offered has equal probability of ending up in the final reservoir. A weighted variant (favouring, say, more recent or more extreme readings) is a different algorithm and is not what this header implements. - MathRand() has a period and resolution suited to diagnostics and lightweight sampling work, not cryptographic or research-grade randomness, on either platform. - The reservoir only ever holds the values themselves, not their original position in the stream. Pair each RS_Add call with your own timestamp or index array alongside it if that association needs to survive.

Script · MT4 · v1.0 · Free

About Reservoir Sampler

Reservoir Sampler is a script for MetaTrader 4. It has 2 settings, such as Capacity and Stream size. MQL source code included.

Files in the download: ReservoirSampler.mqh, ReservoirSampler.txt, ReservoirSamplerDemo.mq4.

Settings

SettingDefaultWhat it does
Capacity20Reservoir size (fixed memory budget)
Stream size5000Number of values to stream through it

How to install

  1. Download the ZIP from your PolyMaria library and unzip it.
  2. In MetaTrader 4 open File → Open Data Folder, then go to MQL4 → Scripts.
  3. Copy the .mq4 file(s) there. Put any .mqh files in MQL4 → Include.
  4. Open the .mq4 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
  5. Drag the script onto a chart to run it once.

Download the PDF guide

Tags: Arbitrage · MT4 Script · MQL4 Source Code

MQL4 & MQL5 scripts · PolyMaria