Code: Select all
//+------------------------------------------------------------------+
//| EURUSD_Quant_MultiRegime.mq5 |
//| 5-Layer Quantitative Multi-Regime Strategy for EUR/USD |
//+------------------------------------------------------------------+
#property copyright "Quantitative FX Architecture"
#property version "1.00"
#property strict
#include <Trade\Trade.mqh>
//--- Strategy Inputs
input group "=== 1. Regime & Cross-Asset Symbols ==="
input string InpSymCHF = "USDCHF"; // Correlated Factor 1
input string InpSymGBP = "GBPUSD"; // Correlated Factor 2
input string InpSymGold = "XAUUSD"; // Macro/Rate Proxy Factor 3
input double InpJumpVolMult = 3.2; // Shock Bar Multiplier (Jump Block)
input int InpMaxSpreadPoints = 18; // Max Allowed Spread (Points)
input group "=== 2. Kalman Fair-Value Engine ==="
input double InpKalmanQ = 1e-7; // Process Noise (Adaptation Speed)
input double InpKalmanR = 1e-5; // Measurement Noise
input double InpEntryZScore = 2.15; // Min |Z-Score| to Trigger Bias
input group "=== 3. L2 Order Book & VPIN Microstructure ==="
input double InpObiDecay = 0.45; // Depth Decay Across Top 5 DOM Levels
input double InpMinObiThreshold = 0.42; // Min Book Imbalance to Confirm Entry
input int InpVpinBucketTicks = 50; // Ticks per VPIN Volume Bucket
input int InpVpinBucketsCount = 20; // Rolling VPIN Window Size
input double InpMaxVpinToxicity = 0.72; // Block Entry Above This VPIN
input int InpSweepLookback = 24; // M5 Bars for Liquidity Sweep Check
input group "=== 4. Volatility-Targeted Risk & Execution ==="
input double InpBaseRiskPct = 1.0; // Base Risk per Trade (%)
input double InpKellyFraction = 0.20; // Fractional Kelly Multiplier
input double InpAtrStopMult = 1.35; // Stop Loss ATR Multiplier
input double InpRewardRiskRatio = 2.40; // Target Reward-to-Risk Ratio
input ulong InpMagicNumber = 884210; // EA Magic Number
input group "=== 5. Post-Trade TCA & CUSUM Kill-Switch ==="
input int InpMarkoutSeconds = 5; // Seconds After Fill to Measure Markout
input double InpCusumHaltSigma = 4.0; // CUSUM Drift Threshold to Halt Trading
//--- Regime Enumeration
enum ENUM_MARKET_REGIME
{
REGIME_TRENDING = 0,
REGIME_MEAN_REVERTING = 1,
REGIME_JUMP_BLOCKED = 2
};
//+------------------------------------------------------------------+
//| Layer 2: 4-Factor Recursive Kalman Filter |
//+------------------------------------------------------------------+
class CKalmanFairValue
{
private:
double m_beta[4];
double m_P[4][4];
double m_q;
double m_r;
bool m_initialized;
public:
void Init(double q, double r)
{
m_q = q;
m_r = r;
m_initialized = false;
ArrayInitialize(m_beta, 0.0);
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
m_P[i][j] = (i == j) ? 1.0 : 0.0;
}
double Update(double y_eur, double x_chf, double x_gbp, double x_gold)
{
double X[4];
X[0] = 1.0;
X[1] = x_chf;
X[2] = x_gbp;
X[3] = x_gold;
if(!m_initialized)
{
m_beta[0] = y_eur;
m_initialized = true;
return 0.0;
}
// 1. Predict covariance: P = P + Q*I
for(int i = 0; i < 4; i++)
m_P[i][i] += m_q;
// 2. Compute P * X
double PX[4];
for(int i = 0; i < 4; i++)
{
PX[i] = 0.0;
for(int j = 0; j < 4; j++)
PX[i] += m_P[i][j] * X[j];
}
// 3. Innovation variance S = X^T * P * X + R
double S = m_r;
for(int i = 0; i < 4; i++)
S += X[i] * PX[i];
if(S <= 1e-14)
return 0.0;
// 4. Prediction error & normalized Z-score
double y_hat = 0.0;
for(int i = 0; i < 4; i++)
y_hat += X[i] * m_beta[i];
double err = y_eur - y_hat;
double z_score = err / MathSqrt(S);
// 5. Kalman Gain K = PX / S
double K[4];
for(int i = 0; i < 4; i++)
K[i] = PX[i] / S;
// 6. Update state vector beta
for(int i = 0; i < 4; i++)
m_beta[i] += K[i] * err;
// 7. Update covariance matrix P = (I - K * X^T) * P
double P_next[4][4];
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
double sum = 0.0;
for(int k = 0; k < 4; k++)
{
double ikx = ((i == k) ? 1.0 : 0.0) - K[i] * X[k];
sum += ikx * m_P[k][j];
}
P_next[i][j] = sum;
}
}
ArrayCopy(m_P, P_next);
return z_score;
}
};
//+------------------------------------------------------------------+
//| Layer 3: Level-2 DOM Imbalance & VPIN Toxicity Tracker |
//+------------------------------------------------------------------+
class CMicrostructureEngine
{
private:
bool m_domSubscribed;
double m_lastMid;
int m_curBucketTicks;
int m_curBuyTicks;
int m_curSellTicks;
double m_bucketImbalances[];
int m_bucketIdx;
int m_bucketsFilled;
double m_recentTickFlow;
public:
void Init(string symbol, int bucketCount)
{
m_domSubscribed = MarketBookAdd(symbol);
m_lastMid = 0.0;
m_curBucketTicks = 0;
m_curBuyTicks = 0;
m_curSellTicks = 0;
m_bucketIdx = 0;
m_bucketsFilled = 0;
m_recentTickFlow = 0.0;
ArrayResize(m_bucketImbalances, bucketCount);
ArrayInitialize(m_bucketImbalances, 0.0);
}
void Release(string symbol)
{
if(m_domSubscribed)
MarketBookRelease(symbol);
}
void OnNewTick(double bid, double ask)
{
double mid = 0.5 * (bid + ask);
if(m_lastMid > 0.0 && mid != m_lastMid)
{
int dir = (mid > m_lastMid) ? 1 : -1;
if(dir > 0) m_curBuyTicks++;
else m_curSellTicks++;
m_recentTickFlow = 0.85 * m_recentTickFlow + 0.15 * dir;
m_curBucketTicks++;
if(m_curBucketTicks >= InpVpinBucketTicks)
{
double imbalance = MathAbs((double)(m_curBuyTicks - m_curSellTicks)) / (double)InpVpinBucketTicks;
m_bucketImbalances[m_bucketIdx] = imbalance;
m_bucketIdx = (m_bucketIdx + 1) % ArraySize(m_bucketImbalances);
if(m_bucketsFilled < ArraySize(m_bucketImbalances))
m_bucketsFilled++;
m_curBucketTicks = 0;
m_curBuyTicks = 0;
m_curSellTicks = 0;
}
}
m_lastMid = mid;
}
double GetVPIN()
{
if(m_bucketsFilled == 0)
return 0.0;
double sum = 0.0;
for(int i = 0; i < m_bucketsFilled; i++)
sum += m_bucketImbalances[i];
return sum / (double)m_bucketsFilled;
}
double GetOrderBookImbalance(string symbol)
{
MqlBookInfo book[];
if(m_domSubscribed && MarketBookGet(symbol, book))
{
int size = ArraySize(book);
if(size > 0)
{
double bidVol[5], askVol[5];
ArrayInitialize(bidVol, 0.0);
ArrayInitialize(askVol, 0.0);
int bIdx = 0, aIdx = 0;
for(int i = 0; i < size; i++)
{
if((book[i].type == BOOK_TYPE_SELL || book[i].type == BOOK_TYPE_SELL_MARKET) && aIdx < 5)
askVol[aIdx++] = (double)book[i].volume_real;
else if((book[i].type == BOOK_TYPE_BUY || book[i].type == BOOK_TYPE_BUY_MARKET) && bIdx < 5)
bidVol[bIdx++] = (double)book[i].volume_real;
}
double num = 0.0, den = 0.0;
for(int lvl = 0; lvl < 5; lvl++)
{
double w = MathExp(-InpObiDecay * lvl);
num += w * (bidVol[lvl] - askVol[lvl]);
den += w * (bidVol[lvl] + askVol[lvl]);
}
if(den > 0.0)
return num / den;
}
}
// Fallback to exponential tick-flow imbalance if broker suppresses FX DOM depth
return m_recentTickFlow;
}
};
//+------------------------------------------------------------------+
//| Layer 5: Post-Trade Markout & CUSUM Alpha-Decay Monitor |
//+------------------------------------------------------------------+
class CTcaMonitor
{
private:
bool m_pendingCheck;
datetime m_fillTime;
double m_fillPrice;
int m_fillSide; // +1 buy, -1 sell
double m_cusumPos;
double m_cusumNeg;
double m_rollingMarkout;
bool m_halted;
public:
void Init()
{
m_pendingCheck = false;
m_fillTime = 0;
m_fillPrice = 0.0;
m_fillSide = 0;
m_cusumPos = 0.0;
m_cusumNeg = 0.0;
m_rollingMarkout = 0.0;
m_halted = false;
}
void RecordFill(int side, double price)
{
m_pendingCheck = true;
m_fillTime = TimeCurrent();
m_fillPrice = price;
m_fillSide = side;
}
void Evaluate(double bid, double ask, double point)
{
if(!m_pendingCheck)
return;
if((TimeCurrent() - m_fillTime) >= InpMarkoutSeconds)
{
double mid = 0.5 * (bid + ask);
double markoutPts = m_fillSide * (mid - m_fillPrice) / point;
m_rollingMarkout = 0.80 * m_rollingMarkout + 0.20 * markoutPts;
// Update two-sided CUSUM drift detector
double standardized = markoutPts / 10.0;
m_cusumPos = MathMax(0.0, m_cusumPos + standardized - 0.25);
m_cusumNeg = MathMax(0.0, m_cusumNeg - standardized - 0.25);
if(m_cusumNeg > InpCusumHaltSigma)
{
m_halted = true;
Print("TCA KILL-SWITCH TRIGGERED: Adverse selection CUSUM breach (", DoubleToString(m_cusumNeg, 2), ")");
}
m_pendingCheck = false;
}
}
bool IsHalted() { return m_halted; }
double GetSizeMultiplier() { return (m_rollingMarkout < 0.0) ? 0.5 : 1.0; }
};
//--- Global Instances
CTrade g_trade;
CKalmanFairValue g_kalman;
CMicrostructureEngine g_micro;
CTcaMonitor g_tca;
int g_hAtrM5 = INVALID_HANDLE;
int g_hAtrH1 = INVALID_HANDLE;
int g_hAtrH4 = INVALID_HANDLE;
//+------------------------------------------------------------------+
//| Layer 1: Classify Market Regime (Trending / Mean-Rev / Jump) |
//+------------------------------------------------------------------+
ENUM_MARKET_REGIME DetectMacroRegime(double spreadPts)
{
if(spreadPts > InpMaxSpreadPoints)
return REGIME_JUMP_BLOCKED;
double closeArr[];
ArraySetAsSeries(closeArr, true);
if(CopyClose(_Symbol, PERIOD_M15, 0, 32, closeArr) < 32)
return REGIME_JUMP_BLOCKED;
// Check latest bar shock against average range (Jump State)
double lastMove = MathAbs(closeArr[0] - closeArr[1]);
double sumMove = 0.0;
for(int i = 1; i < 21; i++)
sumMove += MathAbs(closeArr[i] - closeArr[i + 1]);
double avgMove = sumMove / 20.0;
if(avgMove > 0.0 && lastMove > InpJumpVolMult * avgMove)
return REGIME_JUMP_BLOCKED;
// Variance-Ratio style persistence check across M15 bars
double netDisplacement = MathAbs(closeArr[0] - closeArr[16]);
double pathLength = 0.0;
for(int i = 0; i < 16; i++)
pathLength += MathAbs(closeArr[i] - closeArr[i + 1]);
double efficiencyRatio = (pathLength > 0.0) ? (netDisplacement / pathLength) : 0.0;
if(efficiencyRatio >= 0.38)
return REGIME_TRENDING;
return REGIME_MEAN_REVERTING;
}
//+------------------------------------------------------------------+
//| Layer 3 Helper: Check Recent Liquidity Sweep on M5 |
//+------------------------------------------------------------------+
int DetectLiquiditySweep()
{
MqlRates rates[];
ArraySetAsSeries(rates, true);
if(CopyRates(_Symbol, PERIOD_M5, 0, InpSweepLookback + 3, rates) < InpSweepLookback + 3)
return 0;
double priorHigh = rates[2].high;
double priorLow = rates[2].low;
for(int i = 3; i < InpSweepLookback + 2; i++)
{
if(rates[i].high > priorHigh) priorHigh = rates[i].high;
if(rates[i].low < priorLow) priorLow = rates[i].low;
}
// Bullish sweep: bar 1 wicked below prior swing low and closed back inside
if(rates[1].low < priorLow && rates[1].close > priorLow)
return 1;
// Bearish sweep: bar 1 wicked above prior swing high and closed back inside
if(rates[1].high > priorHigh && rates[1].close < priorHigh)
return -1;
return 0;
}
//+------------------------------------------------------------------+
//| Layer 4: HAR-RV Volatility & Fractional Kelly Position Sizing |
//+------------------------------------------------------------------+
double CalculatePositionLots(double stopDistancePrice, double tcaScale)
{
double atr5[1], atr60[1], atr240[1];
if(CopyBuffer(g_hAtrM5, 0, 0, 1, atr5) < 1 ||
CopyBuffer(g_hAtrH1, 0, 0, 1, atr60) < 1 ||
CopyBuffer(g_hAtrH4, 0, 0, 1, atr240) < 1)
return 0.0;
// Heterogeneous volatility blend (5m, 1h, 4h)
double harVol = 0.50 * atr5[0] + 0.30 * (atr60[0] / 3.5) + 0.20 * (atr240[0] / 7.0);
double volScalar = (harVol > 0.0) ? MathMin(1.0, atr5[0] / harVol) : 1.0;
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double riskPct = InpBaseRiskPct * InpKellyFraction * 5.0 * volScalar * tcaScale;
double riskMoney = equity * (riskPct / 100.0);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
if(tickSize <= 0.0 || tickValue <= 0.0 || stopDistancePrice <= 0.0)
return 0.0;
double lossPerLot = (stopDistancePrice / tickSize) * tickValue;
double rawLots = riskMoney / lossPerLot;
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double lots = MathFloor(rawLots / lotStep) * lotStep;
return MathMax(minLot, MathMin(maxLot, lots));
}
//+------------------------------------------------------------------+
//| Expert Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
SymbolSelect(InpSymCHF, true);
SymbolSelect(InpSymGBP, true);
SymbolSelect(InpSymGold, true);
g_trade.SetExpertMagicNumber(InpMagicNumber);
g_trade.SetDeviationInPoints(10);
g_kalman.Init(InpKalmanQ, InpKalmanR);
g_micro.Init(_Symbol, InpVpinBucketsCount);
g_tca.Init();
g_hAtrM5 = iATR(_Symbol, PERIOD_M5, 14);
g_hAtrH1 = iATR(_Symbol, PERIOD_H1, 14);
g_hAtrH4 = iATR(_Symbol, PERIOD_H4, 14);
if(g_hAtrM5 == INVALID_HANDLE || g_hAtrH1 == INVALID_HANDLE || g_hAtrH4 == INVALID_HANDLE)
return INIT_FAILED;
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Expert Deinitialization |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
g_micro.Release(_Symbol);
IndicatorRelease(g_hAtrM5);
IndicatorRelease(g_hAtrH1);
IndicatorRelease(g_hAtrH4);
}
//+------------------------------------------------------------------+
//| Main Tick Pipeline |
//+------------------------------------------------------------------+
void OnTick()
{
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
if(bid <= 0.0 || ask <= 0.0 || point <= 0.0)
return;
// Update microstructure & post-trade TCA every tick
g_micro.OnNewTick(bid, ask);
g_tca.Evaluate(bid, ask, point);
if(g_tca.IsHalted())
return;
// Only allow 1 active position at a time
if(PositionSelect(_Symbol))
return;
// Gate 1: Macro & Volatility Regime
double spreadPts = (ask - bid) / point;
ENUM_MARKET_REGIME regime = DetectMacroRegime(spreadPts);
if(regime == REGIME_JUMP_BLOCKED)
return;
// Gate 2: Kalman Fair-Value Innovation Z-Score
double pChf = SymbolInfoDouble(InpSymCHF, SYMBOL_BID);
double pGbp = SymbolInfoDouble(InpSymGBP, SYMBOL_BID);
double pGold = SymbolInfoDouble(InpSymGold, SYMBOL_BID);
if(pChf <= 0.0 || pGbp <= 0.0 || pGold <= 0.0)
return;
double zScore = g_kalman.Update(MathLog(bid), MathLog(pChf), MathLog(pGbp), MathLog(pGold));
if(MathAbs(zScore) < InpEntryZScore)
return;
// Regime-conditional directional signal
int signalDir = 0;
if(regime == REGIME_MEAN_REVERTING)
signalDir = (zScore < -InpEntryZScore) ? 1 : -1; // Fade mispricing back to fair value
else if(regime == REGIME_TRENDING)
signalDir = (zScore > InpEntryZScore) ? 1 : -1; // Ride structural breakout
// Gate 3: VPIN Toxicity, L2 Order Book Imbalance & Liquidity Sweep
double vpin = g_micro.GetVPIN();
if(vpin > InpMaxVpinToxicity)
return;
double obi = g_micro.GetOrderBookImbalance(_Symbol);
int sweep = DetectLiquiditySweep();
bool buyConfirmed = (signalDir == 1 && obi >= InpMinObiThreshold && sweep == 1);
bool sellConfirmed = (signalDir == -1 && obi <= -InpMinObiThreshold && sweep == -1);
if(!buyConfirmed && !sellConfirmed)
return;
// Gate 4: ATR Stop, 1:2.4 R:R Target & Volatility-Adjusted Sizing
double atr5[1];
if(CopyBuffer(g_hAtrM5, 0, 0, 1, atr5) < 1 || atr5[0] <= 0.0)
return;
double slDist = InpAtrStopMult * atr5[0];
double tpDist = slDist * InpRewardRiskRatio;
double lots = CalculatePositionLots(slDist, g_tca.GetSizeMultiplier());
if(lots <= 0.0)
return;
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
if(buyConfirmed)
{
double sl = NormalizeDouble(ask - slDist, digits);
double tp = NormalizeDouble(ask + tpDist, digits);
if(g_trade.Buy(lots, _Symbol, ask, sl, tp, "Quant5L_Long"))
g_tca.RecordFill(1, ask);
}
else if(sellConfirmed)
{
double sl = NormalizeDouble(bid + slDist, digits);
double tp = NormalizeDouble(bid - tpDist, digits);
if(g_trade.Sell(lots, _Symbol, bid, sl, tp, "Quant5L_Short"))
g_tca.RecordFill(-1, bid);
}
}