refactor: Standard & MTF

This commit is contained in:
Toh4iem9
2026-06-17 22:38:47 +02:00
parent 867117a6d0
commit 052b19ddc8
@@ -1,10 +1,17 @@
# Pairs Trading Cointegration Pro Suite (Oscillator & Bands)
# Pairs Trading Cointegration Pro Suite (Standard & MTF)
## 1. Summary
The **Pairs Trading Cointegration Pro Suite** is an institutional-grade, high-performance separate window statistical arbitrage trading suite comprising two advanced indicators: `PairsTrading_Pro` (Z-Score separate window oscillator) and `PairsTrading_Bands_Pro` (Main-chart overlay bands). Based on Modern Portfolio Theory and econometric cointegration, the suite decomposes the pricing relationship of two correlated assets into a stationary, volatility-normalized spread.
The **Pairs Trading Cointegration Pro Suite** is an institutional-grade, high-performance statistical arbitrage trading suite comprising four advanced indicators:
While traditional retail pairs trading methods rely on simple price correlation (which is highly unstable and prone to structural drift), the `PairsTrading_Pro` suite utilizes a dynamic rolling **Ordinary Least Squares (OLS) mathematical engine**. It dynamically calculates the rolling Hedge Ratio ($\beta$) and Intercept ($\alpha$) between any two assets to extract the true stationary spread.
* `PairsTrading_Pro` (Z-Score separate window oscillator)
* `PairsTrading_Bands_Pro` (Main-chart overlay bands)
* `PairsTrading_MTF_Pro` (Multi-Timeframe separate window oscillator)
* `PairsTrading_Bands_MTF_Pro` (Multi-Timeframe main-chart overlay bands)
Based on Modern Portfolio Theory and econometric cointegration, the suite decomposes the pricing relationship of two correlated assets into a stationary, volatility-normalized spread.
While traditional retail pairs trading methods rely on simple price correlation (which is highly unstable and prone to structural drift), this suite utilizes a dynamic rolling **Ordinary Least Squares (OLS) mathematical engine**. It dynamically calculates the rolling Hedge Ratio ($\beta$) and Intercept ($\alpha$) between any two assets to extract the true stationary spread.
Featuring **VWAP-style Anchored Resets** (Session, Weekly, Monthly, and Custom Session), the indicators can completely isolate intraday/intraweek price relationships from overnight gaps and illiquidity, delivering a highly visual and robust quantitative scanner system.
@@ -16,7 +23,7 @@ The statistical calculations operate on synchronized close prices for Asset $A$
### A. Rolling Ordinary Least Squares (OLS)
The calculator computes the rolling mean of Asset $A$ ($\bar{A}$) and Benchmark $B$ ($\bar{B}$). It then solves the OLS regression of $A$ on $B$ to find the dynamic Hedge Ratio ($\beta$) and Intercept ($\alpha$):
The calculator computes the rolling mean of Asset $A$ ($\bar{A}$) and Benchmark $B$ ($\bar{B}$). It solves the OLS regression of $A$ on $B$ to find the dynamic Hedge Ratio ($\beta$) and Intercept ($\alpha$):
$$\beta_i = \frac{\text{Covariance}(A, B)}{\text{Variance}(B)}$$
@@ -32,19 +39,17 @@ The sample standard deviation ($\sigma_{\text{spread}}$) of the spread over the
$$\sigma_{\text{spread}} = \sqrt{\frac{1}{N-1} \sum_{k=0}^{N-1} (\text{Spread}_{i-k})^2}$$
### C. Separate Window Z-Score (PairsTrading_Pro)
### C. Volatility-Normalized Z-Score (PairsTrading_Pro)
The final Z-Score is calculated, representing how many standard deviations the current spread has drifted away from its statistical equilibrium of $0.0$:
$$Z_i = \frac{P_{A,i} - \beta_i P_{B,i} - \alpha_i}{\sigma_{\text{spread}}}$$
* **$Z \ge 2.0$ (OrangeRed Histogram):** Spread is extremely overvalued (Short A, Long B).
* **$Z \le -2.0$ (DeepSkyBlue Histogram):** Spread is extremely undervalued (Long A, Short B).
* **$Z \in [-1.5, 1.5]$ (Gray Histogram):** Symmetrical neutral noise zone.
---
### D. Main Chart Cointegration Bands (PairsTrading_Bands_Pro)
## 3. Cointegration Bands (Main Chart Projection)
By rearranging the spread equation back to the price space of Asset $A$, we project the dynamic statistical boundaries directly onto the main price chart:
By rearranging the spread equation back to the price space of Asset $A$, the suite projects the dynamic statistical boundaries directly onto the main price chart:
$$\text{Center Line (Equilibrium / } Z=0.0\text{):} \quad \hat{P}_{A,i} = \beta_i P_{B,i} + \alpha_i$$
@@ -58,29 +63,26 @@ $$\text{Inner Lower Band (Warning / } Z=-M_{\text{inner}}\text{):} \quad \text{B
---
## 3. MQL5 UI & Architecture
## 4. The Pure vs. Hybrid MTF Dilemma
* **Decoupled Math Engine (`PairsTrading_Calculator.mqh`):**
All covariance, variance, rolling OLS, and Z-Score computations are encapsulated inside the highly optimized `CPairsTradingCalculator` include class. It exposes public getter methods (`GetBeta()`, `GetAlpha()`, `GetStdDev()`) to feed calculated coefficients directly to the main-chart bands wrapper, completely eliminating redundant loops and guaranteeing 100% data alignment.
When trading in a Multi-Timeframe (MTF) environment (e.g. tracking $M5$ cointegration on an $M1$ chart), a distinct structural divergence occurs between the main-chart bands and the separate-window oscillator:
* **Strict $O(1)$ Real-Time Tick Optimization:**
The calculator uses the platform's `prev_calculated` parameter to process only the newest incoming bar on every tick. This keeps CPU usage at absolute zero, allowing both the separate-window histogram and the main-chart bands to update live in real-time.
### A. The Discrepancy
* **VWAP-Style Anchored Resets:**
In addition to standard rolling windows (`InpLookback`), the indicators support dynamic resets:
* **Daily Reset (`ANCHOR_SESSION`):** Resets daily. Excellent for intraday trading.
* **Weekly Reset (`ANCHOR_WEEK`):** Resets weekly. Ideal for swing trading.
* **Custom Session (`ANCHOR_CUSTOM_SESSION`):** Resets at a user-defined broker-time range (e.g. `09:00` to `18:00`). It completely filters out overnight gaps and illiquid trading hours, plotting `EMPTY_VALUE` during inactive periods to keep statistics pure.
You may observe the lower timeframe price (M1) pierce the M5 outer band on the main chart, while the separate-window MTF Z-Score remains neutral (Gray).
* **Advanced Bar-Time Synchronization:**
Assets do not always share identical trading calendars or liquidity densities. `PairsTrading_Pro` aligns Symbol A and Symbol B prices perfectly by timestamp using `iBarShift(..., false)` and `iClose`, ensuring that different market open/close times do not distort the calculation. To ensure chart-independence, the synchronization uses a dedicated `iClose` fallback rather than the local chart's `close[0]`.
* **The Reason:** The main chart compares the **live, real-time lower-timeframe price ($P_{A, \text{ltf}}$)** against the static higher-timeframe band. If the price spikes violently during the 5-minute interval, it will visually pierce the band. However, the **Pure MTF Oscillator** computes the Z-Score using the **closed higher-timeframe price ($P_{A, \text{htf}}$)**. Since the 5-minute candle hasn't closed yet or its average close is lower, the pure HTF Z-Score remains neutral.
* **Hardlocked Separate Window Scale Bounds `[-3.5, 3.5]`:**
To prevent single extreme black-swan spikes (e.g., Z-score hitting $-10.0$ during weekend gaps) from squishing the entire historical chart into an unreadable flat line, the separate window's scale is fixed between `-3.5` and `3.5`. Outliers are simply clipped at the boundaries, maintaining a perfect, consistent visual aspect ratio across all timeframes.
### B. Pure MTF vs. Hybrid MTF Configuration
* **Pure MTF (Default):** Calculates everything strictly on the higher timeframe. It provides the highest statistical stability and filters out intraday/micro-timeframe false breakouts.
* **Hybrid MTF (Optional Custom Setup):** Uses the higher timeframe's stable structural parameters ($\beta_{\text{htf}}$, $\alpha_{\text{htf}}$, and $\sigma_{\text{spread, htf}}$), but computes the Z-Score numerator using the live lower-timeframe price ($P_{A, \text{ltf}}$).
$$\text{Z}_{\text{hybrid}} = \frac{P_{A, \text{ltf}} - \beta_{\text{htf}} P_{B, \text{ltf}} - \alpha_{\text{htf}}}{\sigma_{\text{spread, htf}}}$$
*Under this hybrid model, the separate window Z-Score is mathematically guaranteed to cross the $\pm 2.0$ boundaries at the exact second the price pierces the bands on the main chart.*
---
## 4. Parameters
## 5. Parameters
### A. Common Parameters
@@ -101,27 +103,6 @@ $$\text{Inner Lower Band (Warning / } Z=-M_{\text{inner}}\text{):} \quad \text{B
---
## 5. Advanced Statistical Arbitrage Strategies
### A. Classic Spread Execution (Mean Reversion)
* **Buy the Spread (Z-Score $\le -2.0$ or Price touches Lower Outer Band):** Symbol A is extremely underpriced relative to Symbol B.
* *Action:* **BUY Symbol A** (Long) and **SELL Symbol B** (Short) with equal cash exposure.
* **Sell the Spread (Z-Score $\ge 2.0$ or Price touches Upper Outer Band):** Symbol A is extremely overpriced relative to Symbol B.
* *Action:* **SELL Symbol A** (Short) and **BUY Symbol B** (Long) with equal cash exposure.
* **The Exit (Z-Score $\to 0.0$ or Price touches Center Line):** When the spread returns to its statistical equilibrium, close both legs simultaneously to lock in the mean-reversion profit.
### B. The Quant-Grade Synergy: Cointegration + LLD Pro (Single-Leg Trading)
A major drawback of classic pairs trading is that opening two legs is capital-intensive and subject to double-broker execution slippage. By combining `PairsTrading_Pro` with the **`LLD_Pro` (Lead-Lag Dominance)** indicator, you can trade **a single, high-probability leg**:
1. **Identify the Spread Extremes:** `PairsTrading_Pro` alerts you that the spread is extremely cheap (e.g., $Z = -2.5$, meaning Symbol A is cheap, Symbol B is expensive).
2. **Identify the Leader:** Open the `LLD_Pro` indicator for the two symbols.
* **If Symbol B (WTI) is the Leader (leads Symbol A / Brent):** WTI has already moved, and Brent (Symbol A) is mathematically guaranteed to follow to close the gap. Since Symbol A is currently too cheap, you simply **BUY Symbol A (Brent) as a single directional trade!**
* This allows you to trade with half the margin requirement and zero execution hassle, leveraging the leader's predictive momentum to capture the gap-reversal.
---
## 6. Optimized Global Multi-Asset Presets
To ensure statistical validity, only trade assets that share a **fundamental, structural, or macroeconomic link**. Below are the most robust, cointegrated global pairs optimized for live execution, mapped in `PairsTrading_Preset_Manager.mqh`:
@@ -133,5 +114,4 @@ To ensure statistical validity, only trade assets that share a **fundamental, st
| **Forex Majors** | `EURUSD` | `GBPUSD` | `M5` / `M15` | `120` / `ANCHOR_CUSTOM_SESSION` <br>*(e.g., 09:00 - 18:00)* | `1.5` / `2.0` | **European Relative Value.** High cointegration due to close UK-Eurozone macro ties. Custom session filters out overnight illiquidity. |
| **Forex Commodity** | `AUDUSD` | `NZDUSD` | `M15` / `H1` | `120` / `ANCHOR_SESSION` | `1.5` / `2.0` | **Aussie vs. Kiwi.** Commodity export-driven Oceanic currencies. Daily reset captures session shifts beautifully. |
| **Equity Indices** | `US100` (Nasdaq) | `US500` (S&P500) | `M15` / `H1` | `144` / `ANCHOR_WEEK` | `1.5` / `2.0` | **Growth vs. Broad Market.** Tech sector rotations vs. global indexing. Excellent weekly trend reversion. |
| **Equity Indices** | `DE40` (DAX) | `EU50` (Stoxx50) | `M15` / `H1` | `120` / `ANCHOR_WEEK` | `1.5` / `2.0` | **European Equity Arbitrage.** Germany's industrial core vs. broader Eurozone blue-chip baskets. |
| **MAG7 Tech** | `NVDA` (Nvidia) | `AMD` (AMD) | `H1` / `H4` | `60` / `ANCHOR_NONE` | `1.8` / `2.5` | **Semiconductor Sector Spread.** Extreme retail/AI hype valuation discrepancies. Higher multipliers filter stock gap volatility. |
| **Equity Indices** | `DE40` (DAX) | `EU50` (Stoxx50) | `M15` / `H1` | `120` / `ANCHOR_WEEK` | `1.5` / `2.0` | **Group Arbitrage.** High European index cointegration due to shared Eurozone macro factors. |