INSTITUTIONAL QUANTITATIVE ENGINEERING

Statistical Arbitrage in MQL5: Implementing Rolling OLS Cointegration & Mean-Reversion Half-Life

Retail trading robots fail at pairs trading because they rely on Pearson correlation—a non-stationary metric prone to spurious regression. This guide provides the complete mathematical derivation and zero-allocation MQL5 C++ implementation of Engle-Granger cointegration, rolling ordinary least squares ($\beta$), and Ornstein-Uhlenbeck half-life estimation.

Quantitative Trading Group  |  August 25, 2026  |  MetaTrader 5 (MQL5)  |  16 min read

Real-Time Live Statistical Arbitrage Analyzer

Zero-login, live quantitative cointegration engine querying European Central Bank (ECB) real-time feeds.

Live ECB Data Connected
45 bars
Rolling OLS Beta ($\beta$)
--
Optimal Hedge Ratio
Normalized Z-Score
--
Std Deviations ($\sigma$)
Reversion Half-Life ($\tau$)
--
Ornstein-Uhlenbeck
Cointegration Status
--
Stationarity Filter
Quant Strategy Verdict: Calculating Live Real-Time Series...

1. The Correlation vs. Cointegration Trap (Granger-Newbold Fallacy)

The most common catastrophic failure in algorithmic pairs trading is confusing Pearson correlation ($r$) with cointegration. Pearson correlation measures instantaneous co-movement between two series:

$$r = \frac{\sum_{i=1}^N (X_i - \bar{X})(Y_i - \bar{Y})}{\sqrt{\sum_{i=1}^N (X_i - \bar{X})^2 \sum_{i=1}^N (Y_i - \bar{Y})^2}}$$

Financial asset prices are non-stationary, integrated of order one: $X_t, Y_t \sim I(1)$. Regressing two non-stationary series yields statistically significant correlation ($r > 0.85$) and high $t$-statistics purely due to shared macro drift (Granger & Newbold, 1974). If you trade pairs based on high correlation, when the macro drift separates, the spread diverges infinitely, blowing up the account.

Institutional Rule:

Two series $Y_t$ and $X_t$ are cointegrated if and only if there exists a unique linear combination (the hedge ratio $\beta$) such that the residual spread $\epsilon_t$ is stationary $I(0)$:

$$\epsilon_t = Y_t - (\alpha + \beta X_t) \sim I(0)$$

2. Rolling Ordinary Least Squares (OLS) Closed-Form Beta

Fixed hedge ratios ($\beta = 1.0$) fail in foreign exchange and commodities because relative instrument volatilities and cross-currency purchasing power shift over time. We implement rolling closed-form OLS over a rolling window $N$:

$$\beta = \frac{N \sum_{i=1}^N (X_i Y_i) - \left(\sum_{i=1}^N X_i\right)\left(\sum_{i=1}^N Y_i\right)}{N \sum_{i=1}^N X_i^2 - \left(\sum_{i=1}^N X_i\right)^2}, \quad \alpha = \bar{Y} - \beta \bar{X}$$

Once the dynamic hedge ratio $\beta$ is computed, the synthetic spread $S_t$ is established. Sizing is scaled so that for every $1.0$ lot of Leg A traded, exactly $\beta \cdot (\text{TickValue}_A / \text{TickValue}_B)$ lots of Leg B are simultaneously hedged to create a dollar-neutral portfolio.

3. Ornstein-Uhlenbeck (OU) Mean-Reversion Half-Life Estimation

A cointegrated spread follows a continuous-time Ornstein-Uhlenbeck stochastic differential equation:

$$d S_t = \theta (\mu - S_t) \, dt + \sigma \, dW_t$$

Where:

  • $\theta > 0$ represents the rate of mean reversion (speed at which spread snaps back).
  • $\mu$ is the long-term equilibrium mean of the synthetic spread.
  • $\sigma$ is the instantaneous diffusion volatility of the spread residuals.
  • $W_t$ is standard Brownian motion.

Discretizing via an $\text{AR}(1)$ delta regression ($\Delta S_t = a + b S_{t-1} + u_t$) gives the direct discrete mapping:

$$\Delta S_t = a + b S_{t-1} + u_t \implies \theta = -\frac{\ln(1 + b)}{\Delta t}, \quad \tau_{1/2} = \frac{\ln(2)}{\theta}$$

The Half-Life ($\tau_{1/2}$) represents the exact expected time required for a spread divergence to decay by 50%. In institutional execution, if $\tau_{1/2} > \frac{N}{2}$ or $b \ge 0$, the series is diagnosed as non-stationary, and all entry signals are strictly gated.

4. Production-Ready Zero-Allocation MQL5 Class

High-frequency tick evaluation demands that no heap allocations occur in the OnTick() critical path. The following production-ready MQL5 class encapsulates pre-allocated ring buffers, analytical OLS calculation, and Ornstein-Uhlenbeck half-life validation:

QuantStatArbEngine.mqh

5. Market Microstructure: Spread Drag & Execution Slippage

Statistical arbitrage strategies live or die on execution efficiency. Because each trade involves two concurrent legs (opening Leg A and Leg B simultaneously), you pay double the bid-ask friction.

Microstructure Friction Mathematical Penalty Institutional Mitigation in MQL5
Dual Bid-Ask Spread Drag $Cost = \text{Spread}_A + (\beta \cdot \text{Spread}_B)$ Gate entries unless $Z \cdot \sigma_{\text{spread}} \ge 3.5 \times \text{DualSpreadCost}$.
Leg Execution Asymmetry Slippage on unhedged leg risk during delay Execute less liquid leg first via IOC (Immediate-Or-Cancel) order; hedge liquid leg on fill confirmation.
Financing & Swap Drift Daily overnight interest asymmetry Incorporate net swap differential into residual drift term $\mu$.

Frequently Asked Questions (Quant Engineering)

Why does correlation fail for algorithmic pairs trading?

Correlation measures instantaneous linear co-movement between two price levels but ignores whether their price divergence will ever snap back. Non-stationary time series (random walks) can maintain high correlation for months while drifting permanently apart (Granger-Newbold spurious correlation). Cointegration specifically tests whether a linear combination of the two series is mean-reverting and stationary.

How do you handle non-integer lot sizing with dynamic beta in MQL5?

Broker lot step constraints require rounding Leg B volume (Beta * Leg A Volume) to the nearest SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP). The fractional residual is tracked in an internal accumulator and adjusted on subsequent rebalancing bars to prevent portfolio delta drift.

How is the half-life used to set dynamic stop-loss levels?

If a cointegrated spread fails to converge within 2.5 times its estimated Half-Life (Time > 2.5 * tau), the structural economic relationship between the assets has broken down. The position is exited immediately regardless of Z-score to prevent holding through structural regime shifts.

Can this quantitative architecture be used on crypto and futures?

Yes. The statistical engine is asset-agnostic and applies directly to Cross-Exchange Crypto Cash-and-Carry Arbitrage, Perpetual vs Spot Funding Arbitrage, and Calendar Commodity Spreads (e.g., Gold vs Silver or Crude Oil crack spreads).

How does AlgoSpecial engineer custom statistical arbitrage systems?

AlgoSpecial builds fully bespoke, multi-threaded C++ and MQL5 institutional trading systems featuring automated parameter calibration, real-time matrix cointegration filters, and low-latency order execution engines with verified source code.

Explore Complete Institutional Quant Suite

Deep-dive into our production-grade mathematical models, zero-allocation MQL5 classes, and live interactive computation engines:

Pillar 1 • Stat Arb
Cointegration & Half-Life
Pillar 2 • Microstructure
L2 Order Book Imbalance & DOM
Pillar 3 • Signal Processing
Adaptive Kalman State Estimation
Pillar 4 • Volatility Model
GARCH(1,1) Volatility Forecasting
Pillar 5 • Portfolio Survival
Multi-Asset Kelly & Monte Carlo
Master Directory
All 30+ Free Trading Tools →

Need Custom Quantitative Trading Systems Engineered?

From statistical arbitrage and multi-asset cointegration matrixes to HFT order-flow execution and institutional risk parity engines. We deliver production-grade MQL5 and C++ algorithms with verified mathematical models and 100% complete source code ownership.

Request Quantitative Project Quote View Development Benchmarks
🚀 Invite friends — Earn $5 You both get $5 credit on Go Ad · opencode.ai AI-Powered Coding Agent — Try Free Build apps, fix bugs & ship faster with opencode. Get $5 free credit when you join. × Ad · quo.com QuoPhone — $20 Visa Gift Card Free Sign up to Quo, subscribe 3 months, get a $20 Visa gift card. Atif's referral gift for you. ×