Kalman Dynamic Beta Engine MT4
- Indicatori
-
Anthony Cooke
Quantitative Systems Architect and C++, Python, MQL5, MQL4, and Pine Script developer specializing in non-repainting mathematical indicators, Expert Advisors, and statistical strategy audits. I combine industrial quality-control engineering and Applied Mathematics with multi-physics market modeling - Versione: 1.20
- Attivazioni: 5
OVERVIEW AND SCIENTIFIC ORIGIN
The Kalman Dynamic Beta Engine is a quantitative statistical arbitrage and state-space indicator engineered from Control Theory and Financial Econometrics (Recursive Kalman Filtering). Originally developed for aerospace navigation and radar tracking to estimate hidden moving states from noisy measurements, the Kalman Filter is widely applied in quantitative pairs trading to track how the hedge ratio (Beta) between two correlated markets evolves in real time.
Unlike static correlation or fixed-window regression tools that react slowly when macro regimes shift, this indicator runs a strictly causal, non-repainting orthogonal centered state-space Kalman Filter on log-prices. On every bar, it centers both the chart asset (Y) and the benchmark asset (X) around their rolling equilibrium EMAs (InpPeriod = 55) to eliminate intercept and slope collinearity, keeping the Kalman adaptation gain mathematically stable and scale-invariant across Forex pairs, Gold (XAUUSD), Silver (XAGUSD), and Indices.
MATHEMATICAL ENGINE AND TWO AUTOMATIC OPERATING MODES
On each bar, the state-space filter updates the live dynamic hedge ratio (Beta), extracts the out-of-sample spread residual (dy - Beta * dx), standardizes the residual into a causal rolling Z-score, and tracks the Z-score drift of Beta itself.
The indicator operates seamlessly across two automatic modes:
1. Cross-Asset Pairs Mode (Default: InpRefSymbol = "EURUSD"): Measures your chart symbol dynamically against any benchmark available in Market Watch, such as AUDUSD vs EURUSD, EURJPY vs EURUSD, XAUUSD vs EURUSD, or XAUUSD vs XAGUSD. Set InpInvertRef = true when comparing against inversely correlated benchmarks such as USDCHF, USDJPY, or DXY/USDX.
2. Automatic SELF-MODE Fallback: If attached directly to the benchmark symbol itself (for example, placing default settings on EURUSD), if InpRefSymbol is left blank, or if cross-symbol history is unavailable (such as single-symbol Strategy Tester runs), the engine automatically switches to single-asset adaptive state-space tracking against a 21-period log-price reference so calculation and testing never interrupt.
SUBWINDOW VISUAL GUIDE
Subwindow Scale (-4.5 to +4.5, with dashed reference levels at +2.0, 0.0, and -2.0):
- DeepSkyBlue Histogram (Kalman_Spread_Pos): Positive Kalman spread Z-score showing the chart asset stretched above its Beta-implied equilibrium.
- Crimson Histogram (Kalman_Spread_Neg): Negative Kalman spread Z-score showing the chart asset stretched below its Beta-implied equilibrium.
- Gold Smooth Line (Beta_Drift_Wave): Standardized Z-score of dynamic Beta movement showing whether hedge sensitivity is expanding or contracting relative to its recent rolling baseline.
- Cyan Dot (Upper_Spread_Lock) and HotPink Dot (Lower_Spread_Lock): Reversal-locked extreme spread confirmation dots plotted strictly on clean regime flips beyond +2.0 or -2.0 (InpBandLevel) to avoid mid-swing dot clutter.
DARK TELEMETRY HUD BOX LINE-BY-LINE GUIDE
Located in the upper-right subwindow inside a solid dark slate panel with a DodgerBlue border so tall histogram bars never obscure the readout:
- Line 1 (KALMAN SPREAD): Displays the live spread mispricing state (UPPER STRETCH, LOWER STRETCH, POS SPREAD, NEG SPREAD, or EQUILIBRIUM) and standardized Z-score value. Text illuminates Cyan at or above +2.0 and HotPink at or below -2.0.
- Line 2 (PAIR and BETA): Confirms the active asset pairing (such as AUDUSD vs EURUSD, or EURUSD SELF-MODE), the live Kalman dynamic hedge ratio (BETA), and its 10-bar directional change in parentheses.
- Line 3 (BETA DRIFT): Summarizes the Gold Beta_Drift_Wave line directly as STABLE HEDGE, BETA EXPANDING, or BETA CONTRACTING with its Z-score reading. Highlights in Gold when structural hedge sensitivity shifts beyond +/-1.2.
- Line 4 (KALMAN GAIN): Reports the live normalized scalar Kalman adaptation rate (typically 3% to 15%), showing how actively the state-space filter updates Beta on each new bar while filtering out tick noise.
PRACTICAL USAGE
Mean-Reversion Extremes (+/-2.0 Band and Lock Dots):
When DeepSkyBlue bars stretch above +2.0 and lock a Cyan Upper_Spread_Lock dot (HUD Line 1 reads UPPER STRETCH), the chart symbol is statistically overextended relative to its benchmark. Wait for histogram bars to peak and shrink back toward 0.0 for short mean-reversion confirmation. Conversely, when Crimson bars plunge below -2.0 and lock a HotPink Lower_Spread_Lock dot (LOWER STRETCH), watch for bars to contract back toward 0.0 for long mean-reversion confirmation.
Checking Hedge Stability Before Trading (Gold Line and HUD Line 3):
Mean-reversion setups carry cleaner statistical structure when Line 3 reads STABLE HEDGE (Gold curve inside -1.2 to +1.2). When the Gold curve surges strongly past +/-1.2 and Line 3 warns BETA EXPANDING or BETA CONTRACTING, the correlation relationship between the two assets is actively shifting—signaling traders to wait for Beta to stabilize or use wider stops.
TECHNICAL SPECIFICATIONS AND INPUT PARAMETERS
Calculation Engine:
100 percent causal bar-by-bar indexing with zero repainting, zero backpainting, and zero external DLL calls. Subwindow short name: Kalman_Beta(EURUSD,55) or Kalman_Beta(SELF,55).
Core Input Parameters:
- InpRefSymbol (Default: "EURUSD"): Reference benchmark symbol in Market Watch (match your broker symbol suffix if applicable; leave blank for SELF-MODE).
- InpInvertRef (Default: false): Inverts benchmark log-price polarity; set true for inversely correlated pairs such as USDCHF or DXY.
- InpPeriod (Default: 55): Rolling lookback window for equilibrium centering, spread Z-score normalization, and Beta drift scaling.
- InpAdaptSpeed (Default: 1.00, Range 0.25 to 3.00): Scales the Kalman state-space process noise variance to control how fast Beta adapts to regime shifts.
- InpBandLevel (Default: 2.00): Symmetric upper and lower Z-score bands for extreme stretch HUD alerts and reversal-locked confirmation dots.
- InpShowHUD (Default: true): Toggles the 4-line dark telemetry panel (automatically bypassed during Strategy Tester optimization).
Expert Advisor Integration (iCustom Buffer Map):
- Buffer 0: Kalman_Spread_Pos (DeepSkyBlue positive spread Z-score bars)
- Buffer 1: Kalman_Spread_Neg (Crimson negative spread Z-score bars)
- Buffer 2: Beta_Drift_Wave (Gold dynamic Beta drift curve)
- Buffer 3: Upper_Spread_Lock (Cyan upper reversal-locked dot)
- Buffer 4: Lower_Spread_Lock (HotPink lower reversal-locked dot)
- Buffer 5: Kalman_Beta_Raw (Hidden continuous exact live hedge ratio Beta)
- Buffer 6: Kalman_Spread_Z (Hidden continuous standardized spread Z-score)
TIMEFRAME AND VOLATILITY CALIBRATION (CUSTOMIZE TO YOUR CHART)
The default settings (55 period, 1.00 adaptation speed, 2.00 extreme band against EURUSD) provide a balanced M15 to H1 baseline across Major Forex pairs, Gold, and Indices, and every parameter can be calibrated to your market:
- Pairing Ideas: Attach to XAUUSD with InpRefSymbol = "XAGUSD" or "EURUSD", attach to AUDUSD or GBPUSD against "EURUSD", or compare correlated indices such as US100 against US500.
- Faster Intraday Sensitivity (M5 to M15): Lower InpPeriod to 34, increase InpAdaptSpeed to 1.50 to 2.00 for quicker Beta tracking, or narrow InpBandLevel to 1.75 on quieter sessions.
- Institutional Swing Pairs Trading (H1 to D1): Increase InpPeriod to 89, lower InpAdaptSpeed to 0.50 to 0.75 for smoother long-horizon hedge ratios, and widen InpBandLevel to 2.25 to 2.50 to isolate only major macro divergences.
-----ALSO AVAILABLE FOR METATRADER 5 (MT5)
Trading on MetaTrader 5 instead of MetaTrader 4? The identically engineered MetaTrader 5 edition of Kalman Dynamic Beta Engine is published on my MQL5 Seller Profile with the exact same thumbnail, orthogonal state-space Kalman filter, SELF-MODE fallback, dark telemetry HUD, and parameter set. Visit my seller profile to access the MT5 version.
