Article-22598-Market-Micros.../MicroStructure_Foundation.mqh
3013 lines
130 KiB
MQL5
//+------------------------------------------------------------------+
//| MicroStructure_Foundation.mqh |
//| Market Microstructure in MQL5 — Standalone header: Parts 1–7 |
//| |
//| STANDALONE FILE — no other includes required. |
//| Drop this single file into your Includes folder and use: |
//| #include "Includes\MicroStructure_Foundation_v8.mqh" |
//| |
//| CONTAINS |
//| Parts 1–4: safe math, validation, statistical primitives, FFT, |
//| Hurst estimators, GPH, MFDFA, volatility suite. |
//| Part 5: MicrostructureAnalysis struct + noise functions. |
//| Part 6: OrderFlowAnalysis struct + order flow functions. |
//| Part 7: MARKET_REGIME enum, RegimeAnalysis struct, |
//| RegimeClassifier, PopulateRegimeAnalysis (x2). |
//| |
//| DEPENDS ON : nothing |
//+------------------------------------------------------------------+
#property copyright "Max Brown"
#property version "9.00"
#ifndef MICROSTRUCTURE_FOUNDATION_V9_MQH
#define MICROSTRUCTURE_FOUNDATION_V9_MQH
//+------------------------------------------------------------------+
//| MicroStructure_Foundation.mqh |
//| Market Microstructure in MQL5: Robust Foundation — Part 1 of 12 |
//| |
//| PURPOSE |
//| Provides the shared numerical foundation for all subsequent |
//| articles in the series. Every function here is designed to |
//| fail safely rather than silently when given bad data. |
//| |
//| USAGE |
//| Place this file in: |
//| MQL5\Indicators\MicroStructure\Includes\ |
//| Reference from your indicator or EA: |
//| #include "Includes\MicroStructure_Foundation.mqh" |
//| |
//| DEPENDS ON : nothing |
//| REQUIRED BY : Parts 2 through 12 |
//+------------------------------------------------------------------+
// Parts 1–4 foundation (originally MicroStructure_Foundation.mqh)
//+------------------------------------------------------------------+
//| CONSTANTS |
//+------------------------------------------------------------------+
#define DBL_MIN_POSITIVE 1e-20 // Smallest value treated as non-zero in division and log guards
#define MS_DBL_EPSILON 1e-10 // General floating-point comparison tolerance
#define MATH_PI 3.14159265358979323846 // Pi to full double precision for FFT and trigonometric use
#define MIN_SAMPLE_SIZE 8 // Minimum bars required before any statistical calculation proceeds
#define MAX_SAMPLE_SIZE 5000 // Maximum bars fetched in a single CopyClose call
#define MAX_AGGREGATION_LEVEL 10 // Maximum scale levels used in aggregated variance estimators
#define NUMERICAL_STABILITY_BOUND 1e100 // Any result exceeding this is treated as a numerical failure
#define GMT_OFFSET_HOURS 2 // Broker GMT offset; adjust if your broker runs on a different zone
//+------------------------------------------------------------------+
//| STRUCTURES |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Primary result container for fractal and long-memory analysis. |
//| Confidence fields support weighted blending of estimators. |
//| computation_status: 0 = success, non-zero = specific failure. |
//+------------------------------------------------------------------+
struct RobustFractalAnalysis
{
double hurst_exponent; // Weighted-average Hurst exponent across estimators
double hurst_confidence; // Confidence weight for the Hurst estimate (0–1)
double fractal_dimension; // Higuchi fractal dimension blended with Hurst fallback
double dimension_confidence; // Confidence weight for the fractal dimension estimate
double arfima_d; // GPH fractional differencing parameter d
double arfima_confidence; // R² of the GPH log-periodogram regression (0–1)
double multifractal_width; // Spectrum width from MFDFA-style tau(q) regression
double volatility_persistence; // Normalised persistence: 2 * |H - 0.5|
double microstructure_noise; // Enhanced noise estimate from range, body, and close-open
double seasonality_strength; // Intraday seasonality ratio (edge vs midday variance)
double volatility_confidence; // Overall confidence in volatility estimates (0–1)
int computation_status; // 0 = success; non-zero codes indicate failure mode
string validation_message; // Human-readable description of any failure condition
};
//+------------------------------------------------------------------+
//| Backward-compatible alias for older call sites. |
//| Use RobustFractalAnalysis in all new code. |
//+------------------------------------------------------------------+
struct FractalAnalysis
{
double hurst_exponent;
double fractal_dimension;
double arfima_d;
double local_whittle_h;
double multifractal_width;
double stability_alpha;
double volatility_persistence;
double microstructure_noise;
double seasonality_strength;
};
//+------------------------------------------------------------------+
//| Container for realized and modelled volatility estimates. |
//+------------------------------------------------------------------+
struct VolatilityAnalysis
{
double realized_vol; // Square root of sum of squared log-returns
double fractional_vol; // ARFIMA-weighted realized volatility
double figarch_vol; // Power-law decay weighted conditional volatility
double duration_vol; // Annualized volatility scaled by timeframe seconds
double clustering_index; // Lag-1 autocorrelation of squared returns
double asymmetry; // Signed skewness of the return distribution
double leverage_effect; // Negative-vs-positive return volatility asymmetry
double jump_intensity; // Proportion of returns exceeding three standard deviations
};
//+------------------------------------------------------------------+
//| Composite order flow signal combining directional pressure, |
//| momentum, exhaustion, and smart-money contribution. |
//| direction_numeric enables downstream arithmetic without |
//| string comparisons. |
//+------------------------------------------------------------------+
struct OrderFlowSignal
{
double strength; // Volume-weighted directional imbalance (-1 to +1)
double momentum; // Short-window minus long-window flow differential
double exhaustion; // Current absolute flow relative to recent peak
double smart_money; // Large-bar directional bias (signed volume ratio)
double convergence; // Mean signal score across sub-indicators
double confidence; // Signal reliability weight (0–1)
string direction; // "BULLISH", "BEARISH", or "NEUTRAL"
double direction_numeric; // +1.0, -1.0, or 0.0 for use in calculations
};
//+------------------------------------------------------------------+
//| Time-aware composite signal layering session context over flow. |
//| Embeds OrderFlowSignal and adds regime, liquidity, and event |
//| adjustments for session-adaptive position sizing. |
//+------------------------------------------------------------------+
struct TimeAwareSignal
{
OrderFlowSignal flow_signal; // Underlying order flow analysis
double fractal_synergy; // Hurst-regime aligned with flow direction
double time_regime_multiplier; // Session weight: 1.5 at NY open, 0.5 off-peak
double session_liquidity_factor; // Spread-based liquidity scaling (0.3–1.2)
double pre_event_boost; // Additive boost near scheduled events
double final_signal; // Combined directional signal (-2 to +2)
double time_adjusted_confidence; // Confidence scaled by regime and liquidity
string time_context; // Human-readable session label
datetime signal_time; // TimeCurrent() at signal generation
double time_until_event; // Minutes until next scheduled event
double max_position_size; // Suggested size fraction (0–1)
double stop_loss_multiplier; // ATR stop multiplier based on confidence
};
//+------------------------------------------------------------------+
//| Output of MakeTradingDecision: action, sizing, and levels. |
//+------------------------------------------------------------------+
struct TradingDecision
{
int action; // +1 = buy, -1 = sell, 0 = no trade
double size; // Position size fraction (0–1)
double stop_loss_pips; // Stop loss in points
double take_profit_pips; // Take profit in points
double confidence; // Decision confidence (0–1)
string rationale; // Textual description of decision basis
};
//+------------------------------------------------------------------+
//| SAFE MATH FUNCTIONS |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SafeDivide: two-gate guard. |
//| Gate 1 checks denominator before division. |
//| Gate 2 checks result for overflow or NaN after division. |
//+------------------------------------------------------------------+
double SafeDivide(double numerator, double denominator,
double fallback = 0.0)
{
if(!MathIsValidNumber(denominator) ||
MathAbs(denominator) < DBL_MIN_POSITIVE)
return fallback;
double result = numerator / denominator;
if(!MathIsValidNumber(result) ||
MathAbs(result) > NUMERICAL_STABILITY_BOUND)
return fallback;
return result;
}
//+------------------------------------------------------------------+
//| SafeLog: guards against non-positive input. |
//| Fallback of -20.0 signals "invalid point" to downstream |
//| regression slope calculations without distorting the fit. |
//+------------------------------------------------------------------+
double SafeLog(double x, double fallback = -20.0)
{
if(!MathIsValidNumber(x) || x <= 0)
return fallback;
double result = MathLog(x);
if(!MathIsValidNumber(result))
return fallback;
return result;
}
//+------------------------------------------------------------------+
//| SafeSqrt: guards against negative radicand. |
//+------------------------------------------------------------------+
double SafeSqrt(double x, double fallback = 0.0)
{
if(!MathIsValidNumber(x) || x < 0)
return fallback;
double result = MathSqrt(x);
if(!MathIsValidNumber(result))
return fallback;
return result;
}
//+------------------------------------------------------------------+
//| SafeExp: soft-clips extreme inputs rather than hard-failing. |
//| Large inputs are not always bad data; they can be valid |
//| log-return values. Clamping preserves scale while avoiding NaN. |
//+------------------------------------------------------------------+
double SafeExp(double x, double fallback = 0.0)
{
if(!MathIsValidNumber(x))
return fallback;
if(x > 100)
return 1e100;
if(x < -100)
return 1e-100;
double result = MathExp(x);
if(!MathIsValidNumber(result))
return fallback;
return result;
}
//+------------------------------------------------------------------+
//| SafeTanh: soft-bounding operator used throughout order flow. |
//| Compresses signals smoothly to [-1, +1] without hard clipping. |
//| DBL_MIN_POSITIVE in the denominator prevents degenerate zero. |
//+------------------------------------------------------------------+
double SafeTanh(double x)
{
if(!MathIsValidNumber(x))
return 0.0;
if(x > 10.0)
return 1.0;
if(x < -10.0)
return -1.0;
double ex = SafeExp(x);
double emx = SafeExp(-x);
return (ex - emx) / (ex + emx + DBL_MIN_POSITIVE);
}
//+------------------------------------------------------------------+
//| MathSign: returns +1.0, -1.0, or 0.0 for the sign of x. |
//+------------------------------------------------------------------+
double MathSign(double x)
{
if(x > 0)
return 1.0;
if(x < 0)
return -1.0;
return 0.0;
}
//+------------------------------------------------------------------+
//| DATA VALIDATION AND ACCESS |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| ValidateSymbolV2: three-attempt validation with spread check. |
//| Returns true immediately for the current chart symbol. |
//| Spread above 10000 points indicates a data feed problem. |
//+------------------------------------------------------------------+
bool ValidateSymbolV2(const string symbol)
{
if(symbol == NULL || symbol == "")
return false;
if(symbol == Symbol())
return true;
for(int i = 0; i < 3; i++)
{
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
if(bid > 0 && ask > 0 && ask > bid && point > 0)
{
double spread = (ask - bid) / point;
if(spread < 10000)
return true;
}
Sleep(10);
}
return false;
}
//+------------------------------------------------------------------+
//| Backward-compatible alias for ValidateSymbolV2. |
//+------------------------------------------------------------------+
bool ValidateSymbol(const string symbol) { return ValidateSymbolV2(symbol); }
//+------------------------------------------------------------------+
//| SafeCopyClose: validated data fetch with per-value zero check. |
//| Caps request at MAX_SAMPLE_SIZE to prevent memory overrun. |
//| Returns 0 if any copied bar has a non-positive close price. |
//+------------------------------------------------------------------+
int SafeCopyClose(const string symbol, const int tf,
const int start, const int count,
double &out[])
{
if(!ValidateSymbolV2(symbol) || count <= 0)
return 0;
int safe_count = MathMin(count, MAX_SAMPLE_SIZE);
ArraySetAsSeries(out, true);
int copied = CopyClose(symbol, (ENUM_TIMEFRAMES)tf, start, safe_count, out);
if(copied <= 0)
return 0;
for(int i = 0; i < copied; i++)
if(out[i] <= 0)
return 0;
return copied;
}
//+------------------------------------------------------------------+
//| Backward-compatible alias for SafeCopyClose. |
//+------------------------------------------------------------------+
int SafeCopyClosev2(const string symbol, const int tf,
const int start, const int count,
double &out[])
{
return SafeCopyClose(symbol, tf, start, count, out);
}
//+------------------------------------------------------------------+
//| STATISTICAL PRIMITIVES |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| mean_var: two-pass variance estimation. |
//| Two passes avoid numerical instability when the mean is large |
//| relative to the variance, as is typical with price data. |
//+------------------------------------------------------------------+
void mean_var(const double &arr[], const int n,
double &mean, double &var)
{
mean = 0;
var = 0;
if(n <= 0)
return;
for(int i = 0; i < n; i++)
mean += arr[i];
mean /= n;
for(int i = 0; i < n; i++)
var += (arr[i] - mean) * (arr[i] - mean);
var /= n;
}
//+------------------------------------------------------------------+
//| robust_mean_var: trimmed mean and variance with higher moments. |
//| Removes the most extreme 10% of values symmetrically before |
//| computing mean, variance, skewness, and excess kurtosis. |
//| Falls back to mean_var if the trimmed sample is too small. |
//+------------------------------------------------------------------+
void robust_mean_var(const double &arr[], const int n,
double &mean, double &var,
double &skew, double &kurt)
{
mean = 0;
var = 0;
skew = 0;
kurt = 0;
if(n < 4)
return;
double sorted[];
ArrayResize(sorted, n);
ArrayCopy(sorted, arr, 0, 0, n);
ArraySort(sorted);
int trim = MathMax(1, (int)(n * 0.10));
int used = n - 2 * trim;
if(used < 4)
{
mean_var(arr, n, mean, var);
return;
}
for(int i = trim; i < n - trim; i++)
mean += sorted[i];
mean /= used;
for(int i = trim; i < n - trim; i++)
var += MathPow(sorted[i] - mean, 2);
var /= used;
double sd = SafeSqrt(var);
if(sd > DBL_MIN_POSITIVE)
{
for(int i = trim; i < n - trim; i++)
{
double z = (sorted[i] - mean) / sd;
skew += MathPow(z, 3);
kurt += MathPow(z, 4);
}
skew /= used;
kurt = kurt / used - 3.0;
}
}
//+------------------------------------------------------------------+
//| LinearRegressionSlope: ordinary least squares slope estimate. |
//| Used by Hurst estimators (Part 2), fractal dimension (Part 3), |
//| and multifractal spectrum (Part 3). Centralising here ensures |
//| identical arithmetic across all three. SafeDivide guards against |
//| the degenerate case where all x values are identical. |
//+------------------------------------------------------------------+
double LinearRegressionSlope(const double &x[],
const double &y[], int n)
{
if(n < 2)
return 0.0;
double sx = 0, sy = 0, sxy = 0, sxx = 0;
for(int i = 0; i < n; i++)
{
sx += x[i];
sy += y[i];
sxy += x[i] * y[i];
sxx += x[i] * x[i];
}
double denom = n * sxx - sx * sx;
return SafeDivide(n * sxy - sx * sy, denom);
}
//+------------------------------------------------------------------+
//| FFT IMPLEMENTATION |
//| Cooley-Tukey radix-2 in-place. Input length must be power of 2. |
//| Reused by: Part 3 (multifractal), Part 10 (Fourier seasonality), |
//| Part 11 (fractional Gaussian noise generation). |
//+------------------------------------------------------------------+
void fft(const double &real_in[], const double &imag_in[],
double &real_out[], double &imag_out[],
int n, bool inverse)
{
ArrayResize(real_out, n);
ArrayResize(imag_out, n);
ArrayCopy(real_out, real_in, 0, 0, n);
ArrayCopy(imag_out, imag_in, 0, 0, n);
//--- Bit-reversal permutation
int j = 0;
for(int i = 1; i < n; i++)
{
int bit = n >> 1;
for(; (j & bit) != 0; bit >>= 1)
j ^= bit;
j ^= bit;
if(i < j)
{
double tr = real_out[i];
real_out[i] = real_out[j];
real_out[j] = tr;
double ti = imag_out[i];
imag_out[i] = imag_out[j];
imag_out[j] = ti;
}
}
//--- Cooley-Tukey butterfly
for(int len = 2; len <= n; len <<= 1)
{
double ang = 2.0 * MATH_PI / len * (inverse ? -1 : 1);
double wr = MathCos(ang);
double wi = MathSin(ang);
for(int i = 0; i < n; i += len)
{
double cr = 1.0, ci = 0.0;
for(int k = 0; k < len / 2; k++)
{
double ur = real_out[i + k];
double ui = imag_out[i + k];
double vr = real_out[i + k + len / 2];
double vi = imag_out[i + k + len / 2];
double pvr = vr * cr - vi * ci;
double pvi = vr * ci + vi * cr;
real_out[i + k] = ur + pvr;
imag_out[i + k] = ui + pvi;
real_out[i + k + len / 2] = ur - pvr;
imag_out[i + k + len / 2] = ui - pvi;
double ncr = cr * wr - ci * wi;
ci = cr * wi + ci * wr;
cr = ncr;
}
}
}
//--- Normalise output for inverse transform
if(inverse)
for(int i = 0; i < n; i++)
{
real_out[i] /= n;
imag_out[i] /= n;
}
}
//+------------------------------------------------------------------+
//| PeriodSeconds: converts a timeframe constant to seconds. |
//| Used by volatility scaling functions in Part 4. |
//+------------------------------------------------------------------+
int PeriodSeconds(int tf)
{
switch(tf)
{
case PERIOD_M1:
return 60;
case PERIOD_M5:
return 300;
case PERIOD_M15:
return 900;
case PERIOD_M30:
return 1800;
case PERIOD_H1:
return 3600;
case PERIOD_H4:
return 14400;
case PERIOD_D1:
return 86400;
case PERIOD_W1:
return 604800;
default:
return 86400;
}
}
//+---------------------------------------------------------------------+
// PART 2 ADDITIONS — MicroStructure_Foundation.mqh |
// Market Microstructure in MQL5: Measuring Long Memory (Part 2) |
// |
// |
// Functions added in this part: |
// HurstExponentRS() — classical rescaled-range estimator |
// AdvancedHurstExponent()— aggregated-variance and absolute- |
// moments estimators (method-switched) |
// HurstExponentRobust() — confidence-weighted blend of all three |
// PopulateHurstAnalysis()— fills RobustFractalAnalysis from one call |
// |
// Part 2 constants added: |
// HURST_MIN_BARS — minimum post-reset bars before H is valid |
// HURST_CONF_THRESHOLD — minimum per-estimator confidence to blend |
// HURST_RS_MAX_SCALES — log-log regression point cap, R/S path |
// HURST_AV_MAX_SCALES — log-log regression point cap, AggVar path |
// HURST_AM_MAX_SCALES — log-log regression point cap, AbsMom path |
//+---------------------------------------------------------------------+
// ==================================================================
// Part 2 — Long Memory: Hurst Exponent Estimators
// ==================================================================
//--- Part 2 constants
#define HURST_MIN_BARS 40 // Minimum session bars before any estimator is trusted
#define HURST_CONF_THRESHOLD 0.1 // Estimators below this confidence are excluded from blend
#define HURST_RS_MAX_SCALES 10 // Maximum log-log regression points for R/S estimator
#define HURST_AV_MAX_SCALES 10 // Maximum log-log regression points for AggVar estimator
#define HURST_AM_MAX_SCALES 10 // Maximum log-log regression points for AbsMom estimator
//+------------------------------------------------------------------+
//| HurstExponentRS: classical rescaled-range (R/S) estimator. |
//| Computes log(E[R/S]) ~ H * log(n) across geometrically spaced |
//| window sizes. Each scale is averaged over non-overlapping |
//| segments so that the estimate is less sensitive to a single |
//| anomalous window. |
//| |
//| Parameters |
//| returns[] — log-return array, oldest first |
//| n — number of valid returns |
//| confidence — output: k / HURST_RS_MAX_SCALES where k = valid |
//| regression points. Reflects data sufficiency. |
//| |
//| Returns H in [0.01, 0.99]. Returns 0.5 with confidence = 0.0 |
//| when fewer than 3 valid regression points are obtained. |
//+------------------------------------------------------------------+
double HurstExponentRS(const double &returns[], int n, double &confidence)
{
confidence = 0.0;
//--- Need at least one complete segment at minimum scale 8
if(n < 30)
return 0.5;
int m_max = (int)MathMax(10, n / 4);
double log_n[10], log_rs[10];
int k = 0;
int scale = 8;
while(scale <= m_max && k < HURST_RS_MAX_SCALES)
{
int segs = n / scale;
if(segs < 2)
{
scale *= 2;
continue;
}
double rs_sum = 0.0;
int v = 0;
for(int seg = 0; seg < segs; seg++)
{
int st = seg * scale;
double s1 = 0.0, s2 = 0.0;
for(int j = 0; j < scale; j++)
{
s1 += returns[st + j];
s2 += returns[st + j] * returns[st + j];
}
double mu = s1 / scale;
//--- Two-pass variance: stable against catastrophic cancellation
double var = (s2 - scale * mu * mu) / (scale - 1);
if(var <= 0)
continue;
double mx = -1e100, mn = 1e100, cum = 0.0;
for(int j = 0; j < scale; j++)
{
cum += returns[st + j] - mu;
if(cum > mx)
mx = cum;
if(cum < mn)
mn = cum;
}
double rng = mx - mn;
if(rng > 0)
{
rs_sum += SafeLog(rng / SafeSqrt(var));
v++;
}
}
if(v > 0)
{
log_n [k] = SafeLog((double)scale);
log_rs[k] = rs_sum / v;
k++;
}
scale *= 2;
}
if(k < 3)
return 0.5;
double h = LinearRegressionSlope(log_n, log_rs, k);
confidence = (double)k / HURST_RS_MAX_SCALES;
return MathMax(0.01, MathMin(0.99, h));
}
//+------------------------------------------------------------------+
//| AdvancedHurstExponent: aggregated variance (method = 0) or |
//| absolute moments (method = 1) estimator. |
//| |
//| AggVar: variance of non-overlapping block averages scales as |
//| sigma^2(m) ~ m^(2H-2), so H = 1 + slope/2. |
//| |
//| AbsMom: mean absolute block average scales as |
//| E[|x_bar(m)|] ~ m^(H-1), so H = 1 + slope. |
//| |
//| Parameters |
//| returns[] — log-return array, oldest first |
//| n — number of valid returns |
//| method — 0 = AggVar, 1 = AbsMom |
//| confidence — output: k / max_scales |
//| |
//| Returns H in [0.01, 0.99]; 0.5 with confidence = 0.0 on failure. |
//+------------------------------------------------------------------+
double AdvancedHurstExponent(const double &returns[], int n,
int method, double &confidence)
{
confidence = 0.0;
//--- AggVar needs at least 10 returns per aggregation level
//--- AbsMom needs at least 15 per level — tighter requirement
int min_per_seg = (method == 0) ? 10 : 15;
if(n < min_per_seg * 2)
return 0.5;
int max_scales = (method == 0) ? HURST_AV_MAX_SCALES
: HURST_AM_MAX_SCALES;
int max_agg = (int)MathMin(max_scales + 1, n / min_per_seg);
double log_m[10], log_stat[10];
int k = 0;
for(int m = 2; m <= max_agg && k < max_scales; m++)
{
int segs = n / m;
if(segs < 2)
continue;
double stat = 0.0;
for(int seg = 0; seg < segs; seg++)
{
int st = seg * m;
double sum = 0.0;
for(int j = 0; j < m; j++)
sum += returns[st + j];
double xbar = sum / m;
if(method == 0)
stat += xbar * xbar; // AggVar: squared block mean
else
stat += MathAbs(xbar); // AbsMom: absolute block mean
}
stat /= segs;
if(stat <= 0)
continue;
log_m [k] = SafeLog((double)m);
log_stat[k] = SafeLog(stat);
k++;
}
if(k < 3)
return 0.5;
double beta = LinearRegressionSlope(log_m, log_stat, k);
double h = (method == 0) ? 1.0 + beta / 2.0 // AggVar
: 1.0 + beta; // AbsMom
confidence = (double)k / max_scales;
return MathMax(0.01, MathMin(0.99, h));
}
//+------------------------------------------------------------------+
//| HurstExponentRobust: confidence-weighted blend of three |
//| independent Hurst estimators. |
//| |
//| Three estimators are computed independently: |
//| (1) Classical R/S (Hurst 1951) |
//| (2) Aggregated Variance |
//| (3) Absolute Moments |
//| |
//| Each estimator earns a confidence proportional to the number of |
//| valid log-log regression points it produced relative to the |
//| maximum possible. Estimators below HURST_CONF_THRESHOLD are |
//| excluded from the blend. The final confidence is the sum of all |
//| participating weights normalised to [0, 1]. |
//| |
//| Session reset requirement: the log-return array passed here |
//| must contain only bars from the current trading session. Mixing |
//| pre-open and post-open bars across the session boundary causes |
//| a structural break in the return distribution that artificially |
//| compresses H toward 0.5. Call SafeCopyClose with start = 0 and |
//| count limited to bars elapsed since session open. |
//| |
//| Parameters |
//| symbol — instrument to analyse |
//| tf — timeframe |
//| period — lookback bars (recommend 90 for M1 intraday) |
//| confidence — output: blended confidence weight (0 to 1) |
//| |
//| Returns H in [0.01, 0.99]. Returns 0.5 (random walk boundary) |
//| with confidence = 0.0 when HURST_MIN_BARS is not satisfied. |
//+------------------------------------------------------------------+
double HurstExponentRobust(const string symbol, const int tf,
const int period, double &confidence)
{
confidence = 0.0;
//--- Validate inputs before touching the price feed
if(!ValidateSymbolV2(symbol) || period < HURST_MIN_BARS)
return 0.5;
//--- Fetch close prices; SafeCopyClose validates each bar
double close[];
int n = SafeCopyClose(symbol, tf, 0, period, close);
if(n < HURST_MIN_BARS)
return 0.5;
//--- Build log-return array
//--- Filter returns whose absolute value exceeds 0.1: these are
//--- almost certainly data artefacts on futures/CFD M1 feeds.
double returns[];
ArrayResize(returns, n - 1);
int valid = 0;
for(int i = 0; i < n - 1; i++)
{
if(close[i] <= 0 || close[i + 1] <= 0)
continue;
double r = SafeLog(close[i]) - SafeLog(close[i + 1]);
if(MathAbs(r) < 0.1)
returns[valid++] = r;
}
if(valid < HURST_MIN_BARS)
{
confidence = 0.1;
return 0.5;
}
ArrayResize(returns, valid);
//--- Estimator 1: R/S
double conf_rs, conf_av, conf_am;
double h_rs = HurstExponentRS(returns, valid, conf_rs);
//--- Estimator 2: Aggregated Variance (method = 0)
double h_av = AdvancedHurstExponent(returns, valid, 0, conf_av);
//--- Estimator 3: Absolute Moments (method = 1)
double h_am = AdvancedHurstExponent(returns, valid, 1, conf_am);
//--- Confidence-weighted blend
//--- Exclude any estimator whose regression was too sparse to trust
double weighted_sum = 0.0, total_weight = 0.0;
if(conf_rs > HURST_CONF_THRESHOLD)
{ weighted_sum += h_rs * conf_rs; total_weight += conf_rs; }
if(conf_av > HURST_CONF_THRESHOLD)
{ weighted_sum += h_av * conf_av; total_weight += conf_av; }
if(conf_am > HURST_CONF_THRESHOLD)
{ weighted_sum += h_am * conf_am; total_weight += conf_am; }
if(total_weight <= 0)
{
confidence = 0.1;
return 0.5;
}
double h_final = weighted_sum / total_weight;
confidence = MathMin(1.0, total_weight / 3.0); // Normalise to [0, 1]
h_final = MathMax(0.01, MathMin(0.99, h_final));
confidence = MathMax(0.0, MathMin(1.0, confidence));
return h_final;
}
//+------------------------------------------------------------------+
//| PopulateHurstAnalysis: convenience wrapper that calls |
//| HurstExponentRobust and writes results into the shared |
//| RobustFractalAnalysis struct. |
//| |
//| Fields written: |
//| result.hurst_exponent — blended H |
//| result.hurst_confidence — blended confidence |
//| result.volatility_persistence — 2 * |H - 0.5|, range [0, 1] |
//| result.computation_status — 0 on success, 1 on failure |
//| result.validation_message — diagnostic text on failure |
//| |
//| All other fields in result are left unchanged so that later |
//| parts of the series can call their own Populate* functions on |
//| the same struct without overwriting Hurst output. |
//+------------------------------------------------------------------+
void PopulateHurstAnalysis(const string symbol, const int tf,
const int period,
RobustFractalAnalysis &result)
{
double confidence = 0.0;
double h = HurstExponentRobust(symbol, tf, period, confidence);
//--- Write Hurst fields
result.hurst_exponent = h;
result.hurst_confidence = confidence;
result.volatility_persistence = 2.0 * MathAbs(h - 0.5);
//--- Diagnostics
if(confidence < HURST_CONF_THRESHOLD)
{
result.computation_status = 1;
result.validation_message =
StringFormat("HurstExponentRobust: confidence %.3f below threshold "
"%.3f — insufficient session data for symbol %s tf %d",
confidence, HURST_CONF_THRESHOLD, symbol, tf);
}
else
{
result.computation_status = 0;
result.validation_message = "OK";
}
}
// ==================================================================
// Part 3 additions — TWO steps required before pasting this block.
//
// STEP 1 — Add arfima_confidence to RobustFractalAnalysis.
// Open MicroStructure_Foundation.mqh, locate the struct definition,
// and insert the new field immediately after the existing arfima_d:
//
// double arfima_d; // GPH fractional differencing parameter d
// double arfima_confidence; // R² of the GPH log-periodogram regression (0–1) <-- ADD THIS
// double multifractal_width; // ...
//
// STEP 2 — Paste everything below this comment block before the
// closing #endif of MicroStructure_Foundation.mqh.
// ==================================================================
//+------------------------------------------------------------------+
//| CONSTANTS — Part 3 |
//+------------------------------------------------------------------+
#define GPH_MIN_BARS 40 // Minimum returns required before GPH activates
#define GPH_BANDWIDTH_EXP 0.65 // Fourier frequency bandwidth exponent (m = N^0.65)
#define GPH_MIN_FREQ 15 // Minimum frequency points for a valid regression
#define GPH_CONF_THRESHOLD 0.05 // Minimum R² accepted as a meaningful confidence value
#define GPH_D_CONSISTENCY 0.1 // Maximum |H − (d + 0.5)| before a warning is raised
//+------------------------------------------------------------------+
//| GPHEstimator: Geweke-Porter-Hudak log-periodogram regression. |
//| Regresses log I(ωⱼ) on log|2 sin(ωⱼ/2)|² across the first m |
//| Fourier frequencies (m = floor(N^GPH_BANDWIDTH_EXP)). The OLS |
//| slope gives −d directly. R² of the regression is returned via |
//| the confidence output parameter. |
//| |
//| Inputs |
//| returns[] — pre-validated log-return array (caller fills) |
//| n — number of valid elements in returns[] |
//| confidence — output: R² of the log-periodogram fit [0, 1] |
//| |
//| Returns d clamped to (−0.49, 0.49). Returns 0.0 with |
//| confidence = 0.0 on any validation failure. |
//+------------------------------------------------------------------+
double GPHEstimator(const double &returns[], int n, double &confidence)
{
confidence = 0.0;
//--- Minimum data guard
if(n < GPH_MIN_BARS)
return 0.0;
//--- Bandwidth: m = floor(N ^ GPH_BANDWIDTH_EXP), clamped
int m = (int)MathFloor(MathPow((double)n, GPH_BANDWIDTH_EXP));
m = (int)MathMax(GPH_MIN_FREQ, MathMin(m, n / 3));
if(m < 5)
return 0.0;
//--- Compute periodogram at the first m Fourier frequencies
double log_I[];
double log_sin_sq[];
ArrayResize(log_I, m);
ArrayResize(log_sin_sq, m);
int valid_points = 0;
for(int j = 1; j <= m; j++)
{
double omega_j = 2.0 * MATH_PI * (double)j / (double)n;
//--- DFT at frequency ωⱼ
double re = 0.0;
double im = 0.0;
for(int t = 0; t < n; t++)
{
double angle = omega_j * (double)t;
re += returns[t] * MathCos(angle);
im += returns[t] * MathSin(angle);
}
//--- Periodogram ordinate I(ωⱼ) = (re² + im²) / (2π N)
double I_j = SafeDivide(re * re + im * im, 2.0 * MATH_PI * (double)n);
if(I_j <= DBL_MIN_POSITIVE)
continue;
//--- Regressor: log|2 sin(ωⱼ/2)|²
double sin_half = MathSin(omega_j / 2.0);
double sin_sq = sin_half * sin_half;
if(sin_sq <= DBL_MIN_POSITIVE)
continue;
log_I [valid_points] = SafeLog(I_j);
log_sin_sq [valid_points] = SafeLog(4.0 * sin_sq);
valid_points++;
}
if(valid_points < 5)
return 0.0;
//--- Resize to actual valid count
ArrayResize(log_I, valid_points);
ArrayResize(log_sin_sq, valid_points);
//--- OLS regression: log I(ωⱼ) = c − d · log|2 sin(ωⱼ/2)|² + ε
//--- Slope of OLS = −d, so d = −slope
double sum_x = 0.0;
double sum_y = 0.0;
double sum_xx = 0.0;
double sum_xy = 0.0;
for(int k = 0; k < valid_points; k++)
{
sum_x += log_sin_sq[k];
sum_y += log_I[k];
sum_xx += log_sin_sq[k] * log_sin_sq[k];
sum_xy += log_sin_sq[k] * log_I[k];
}
double denom = (double)valid_points * sum_xx - sum_x * sum_x;
if(MathAbs(denom) < DBL_MIN_POSITIVE)
return 0.0;
double slope = SafeDivide((double)valid_points * sum_xy - sum_x * sum_y, denom);
double d_hat = -slope; // GPH: slope = -d
double intercept = SafeDivide(sum_y - slope * sum_x, (double)valid_points);
//--- R² as confidence measure
double y_mean = SafeDivide(sum_y, (double)valid_points);
double ss_tot = 0.0;
double ss_res = 0.0;
for(int k = 0; k < valid_points; k++)
{
double y_hat = intercept + slope * log_sin_sq[k];
double res = log_I[k] - y_hat;
ss_res += res * res;
ss_tot += (log_I[k] - y_mean) * (log_I[k] - y_mean);
}
if(ss_tot > DBL_MIN_POSITIVE)
confidence = 1.0 - SafeDivide(ss_res, ss_tot);
confidence = MathMax(0.0, MathMin(1.0, confidence));
//--- Clamp d to the admissible ARFIMA range
d_hat = MathMax(-0.49, MathMin(0.49, d_hat));
return d_hat;
}
//+------------------------------------------------------------------+
//| PopulateARFIMAAnalysis: fetches price data, computes log-returns,|
//| calls GPHEstimator(), writes results into RobustFractalAnalysis, |
//| and validates H-d consistency against the Hurst output written |
//| by PopulateHurstAnalysis(). |
//| |
//| Fields written: |
//| result.arfima_d — GPH fractional differencing param |
//| result.arfima_confidence — R² of the log-periodogram fit |
//| result.computation_status — 0 on success, 2 on failure |
//| result.validation_message — diagnostic text on any anomaly |
//| |
//| Call PopulateHurstAnalysis() first so the H-d consistency check |
//| has a valid hurst_exponent to compare against. |
//+------------------------------------------------------------------+
void PopulateARFIMAAnalysis(const string symbol, const int tf,
const int period, RobustFractalAnalysis &result)
{
//--- Validate symbol and minimum period
if(!ValidateSymbolV2(symbol) || period < GPH_MIN_BARS + 1)
{
result.arfima_d = 0.0;
result.arfima_confidence = 0.0;
result.computation_status = 2;
result.validation_message =
StringFormat("PopulateARFIMAAnalysis: invalid symbol or period too small "
"(need >= %d, got %d)", GPH_MIN_BARS + 1, period);
return;
}
//--- Fetch closing prices
double close[];
int copied = SafeCopyClose(symbol, tf, 0, period, close);
if(copied < GPH_MIN_BARS + 1)
{
result.arfima_d = 0.0;
result.arfima_confidence = 0.0;
result.computation_status = 2;
result.validation_message =
StringFormat("PopulateARFIMAAnalysis: SafeCopyClose returned %d bars, "
"need >= %d", copied, GPH_MIN_BARS + 1);
return;
}
//--- Build log-return array, filtering invalid prices and data artifacts
int n_closes = ArraySize(close);
double returns[];
ArrayResize(returns, n_closes - 1);
int valid_count = 0;
for(int i = 0; i < n_closes - 1; i++)
{
if(close[i] <= 0.0 || close[i + 1] <= 0.0)
continue;
//--- Standard log-return: r = log(P_t+1) - log(P_t)
double r = SafeLog(close[i + 1]) - SafeLog(close[i]);
//--- Reject data artifacts: genuine M1 returns do not exceed ±10 %
if(MathAbs(r) >= 0.1)
continue;
returns[valid_count] = r;
valid_count++;
}
ArrayResize(returns, valid_count);
if(valid_count < GPH_MIN_BARS)
{
result.arfima_d = 0.0;
result.arfima_confidence = 0.0;
result.computation_status = 2;
result.validation_message =
StringFormat("PopulateARFIMAAnalysis: only %d valid returns after filtering, "
"need >= %d", valid_count, GPH_MIN_BARS);
return;
}
//--- Estimate d via GPH log-periodogram regression
double conf = 0.0;
double d = GPHEstimator(returns, valid_count, conf);
result.arfima_d = d;
result.arfima_confidence = conf;
//--- H-d consistency check: theory requires H = d + 0.5
//--- Only runs when Hurst output is already populated
if(result.hurst_confidence > HURST_CONF_THRESHOLD)
{
double h_from_d = d + 0.5;
double discrepancy = MathAbs(result.hurst_exponent - h_from_d);
if(discrepancy > GPH_D_CONSISTENCY)
{
result.computation_status = 0; // success with diagnostic note
result.validation_message =
StringFormat("PopulateARFIMAAnalysis: H-d discrepancy %.3f exceeds "
"threshold %.3f — H(Hurst)=%.3f, H(GPH)=d+0.5=%.3f. "
"Session mixing or non-stationarity suspected.",
discrepancy, GPH_D_CONSISTENCY,
result.hurst_exponent, h_from_d);
return;
}
}
//--- Confidence threshold check
if(conf < GPH_CONF_THRESHOLD)
{
result.computation_status = 2;
result.validation_message =
StringFormat("PopulateARFIMAAnalysis: R²=%.4f below threshold %.4f — "
"log-periodogram regression unreliable for symbol %s tf %d",
conf, GPH_CONF_THRESHOLD, symbol, tf);
return;
}
result.computation_status = 0;
result.validation_message = "OK";
}
//+------------------------------------------------------------------+
//| PART 4 — VOLATILITY ANALYSIS |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| MultifractalSpectrum: MFDFA returning Legendre-transform Δα. |
//| confidence = mean R² of the log(F(q,s)) ~ log(s) regressions. |
//| Returns Δα = max(α) − min(α). Returns 0.0 on failure. |
//| |
//| Outlier filter: |r| >= 0.1 removed before profile construction. |
//| MFDFA is sensitive to extreme values at negative q because large |
//| fluctuations dominate the q-th moment. Rollovers and bad ticks |
//| must be excluded before the profile is built. |
//| |
//| Scale choices: minimum = 16 (below this, OLS detrending is |
//| unreliable on noisy M1 data); geometric steps (powers of 2); |
//| maximum = valid/4 guarantees at least 4 non-overlapping segments.|
//| q range [-5, +5]: default captures the standard spectrum width |
//| without divergence issues at large |q| on short M1 sessions. |
//+------------------------------------------------------------------+
double MultifractalSpectrum(const string symbol, const int tf,
const int period, double &confidence,
int q_min = -5, int q_max = 5)
{
confidence = 0.0;
if(!ValidateSymbolV2(symbol) || period < 100)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, 0, period + 1, close) < period + 1)
return 0.0;
//--- Build log-return array; filter gross outliers
double returns[];
ArrayResize(returns, period);
int valid = 0;
for(int i = 0; i < period; i++)
{
if(close[i] <= 0.0 || close[i + 1] <= 0.0)
continue;
double r = SafeLog(close[i + 1]) - SafeLog(close[i]);
if(MathAbs(r) < 0.1)
returns[valid++] = r;
}
if(valid < 100)
return 0.0;
ArrayResize(returns, valid);
//--- Cumulative sum profile (demeaned)
double mean_r = 0.0;
for(int i = 0; i < valid; i++)
mean_r += returns[i];
mean_r /= valid;
double y[];
ArrayResize(y, valid);
double cum = 0.0;
for(int i = 0; i < valid; i++)
{
cum += returns[i] - mean_r;
y[i] = cum;
}
//--- Geometric scales: powers of 2; minimum 4 full segments
int scales[];
int max_scale = valid / 4, s = 16, scale_count = 0;
while(s <= max_scale)
{ ArrayResize(scales, scale_count + 1); scales[scale_count++] = s; s *= 2; }
if(scale_count < 2)
return 0.0;
//--- q values
int q_cnt = q_max - q_min + 1;
double q_vals[], h_q[];
ArrayResize(q_vals, q_cnt);
ArrayResize(h_q, q_cnt);
ArrayInitialize(h_q, 0.0);
for(int qi = 0; qi < q_cnt; qi++)
q_vals[qi] = q_min + qi;
double r2_sum = 0.0;
int r2_cnt = 0;
for(int qi = 0; qi < q_cnt; qi++)
{
double q = q_vals[qi];
double logF[], logS[];
int points = 0;
for(int sidx = 0; sidx < scale_count; sidx++)
{
int seg_s = scales[sidx], n_seg = valid / seg_s;
if(n_seg < 2)
continue;
double F_sum = 0.0;
int seg_cnt = 0;
for(int v = 0; v < n_seg; v++)
{
int start = v * seg_s;
double sx = 0.0, sy = 0.0, sxy = 0.0, sxx = 0.0;
for(int k = 0; k < seg_s; k++)
{ sx += k; sy += y[start+k]; sxy += k*y[start+k]; sxx += k*k; }
double dn = seg_s * sxx - sx * sx;
if(MathAbs(dn) < DBL_MIN_POSITIVE)
continue;
double sl = (seg_s*sxy - sx*sy)/dn, ic = (sy - sl*sx)/seg_s;
double var = 0.0;
for(int k = 0; k < seg_s; k++)
{ double res = y[start+k] - (ic + sl*k); var += res*res; }
var /= seg_s;
if(q == 0.0)
F_sum += MathLog(MathMax(var, DBL_MIN_POSITIVE));
else
F_sum += MathPow(MathMax(var, DBL_MIN_POSITIVE), q/2.0);
seg_cnt++;
}
if(seg_cnt == 0)
continue;
double Fq = (q == 0.0) ? MathExp(F_sum/seg_cnt)
: MathPow(F_sum/seg_cnt, 1.0/q);
if(Fq <= DBL_MIN_POSITIVE)
continue;
ArrayResize(logF, points+1);
ArrayResize(logS, points+1);
logF[points] = MathLog(Fq);
logS[points] = MathLog((double)seg_s);
points++;
}
if(points < 2)
continue;
double lsx=0,lsy=0,lsxy=0,lsxx=0;
for(int p=0;p<points;p++)
{
lsx+=logS[p];
lsy+=logF[p];
lsxy+=logS[p]*logF[p];
lsxx+=logS[p]*logS[p];
}
double den = points*lsxx - lsx*lsx;
if(MathAbs(den) < DBL_MIN_POSITIVE)
continue;
h_q[qi] = (points*lsxy - lsx*lsy) / den;
//--- R² for this q regression
double ym=lsy/points, ss_tot=0, ss_res=0;
double pi_int = (lsy - h_q[qi]*lsx)/points;
for(int p=0;p<points;p++)
{
double pr = pi_int + h_q[qi]*logS[p];
ss_res += (logF[p]-pr)*(logF[p]-pr);
ss_tot += (logF[p]-ym)*(logF[p]-ym);
}
if(ss_tot > DBL_MIN_POSITIVE)
{
r2_sum += 1.0 - ss_res/ss_tot;
r2_cnt++;
}
}
if(r2_cnt > 0)
confidence = r2_sum / r2_cnt;
//--- Legendre transform: α(q) = h(q) + q·h'(q)
//--- h'(q) approximated by central finite differences
double alpha[];
ArrayResize(alpha, q_cnt);
for(int qi = 0; qi < q_cnt; qi++)
{
double dh;
if(qi == 0)
dh = h_q[1] - h_q[0];
else
if(qi == q_cnt-1)
dh = h_q[q_cnt-1] - h_q[q_cnt-2];
else
dh = (h_q[qi+1] - h_q[qi-1]) / 2.0;
alpha[qi] = h_q[qi] + q_vals[qi] * dh;
}
double amax = alpha[0], amin = alpha[0];
for(int qi = 1; qi < q_cnt; qi++)
{ if(alpha[qi] > amax) amax=alpha[qi]; if(alpha[qi] < amin) amin=alpha[qi]; }
double delta_alpha = amax - amin;
if(!MathIsValidNumber(delta_alpha) || delta_alpha > 10.0)
return 0.0;
return MathMax(0.0, delta_alpha);
}
//+------------------------------------------------------------------+
//| PopulateMultifractalAnalysis: writes multifractal_width (Δα) and |
//| dimension_confidence (mean R²) into RobustFractalAnalysis. |
//| Sessions with dimension_confidence < 0.65 have unreliable Δα. |
//+------------------------------------------------------------------+
void PopulateMultifractalAnalysis(const string symbol, const int tf,
const int period, RobustFractalAnalysis &result)
{
result.multifractal_width = 0.0;
result.dimension_confidence = 0.0;
if(!ValidateSymbolV2(symbol) || period < 100)
return;
double conf = 0.0;
double width = MultifractalSpectrum(symbol, tf, period, conf);
if(MathIsValidNumber(width))
result.multifractal_width = width;
if(MathIsValidNumber(conf))
result.dimension_confidence = conf;
}
//+------------------------------------------------------------------+
//| RealizedVolatility: standard realized volatility from log-returns|
//| Returns sqrt(mean(squared log-returns)) |
//+------------------------------------------------------------------+
double RealizedVolatility(const string symbol, const int tf,
const int window, int shift = 0)
{
if(!ValidateSymbolV2(symbol) || window < 2)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, shift, window + 1, close) < window + 1)
return 0.0;
int n_returns = ArraySize(close) - 1;
if(n_returns < 1)
return 0.0;
double sum_sq = 0.0;
int valid = 0;
for(int i = 0; i < n_returns; i++)
{
if(close[i] <= 0.0 || close[i+1] <= 0.0)
continue;
double r = SafeLog(close[i+1]) - SafeLog(close[i]);
sum_sq += r * r;
valid++;
}
if(valid == 0)
return 0.0;
return MathSqrt(sum_sq / valid);
}
//+------------------------------------------------------------------+
//| DurationVolatility: annualized volatility scaled by bar duration |
//| Returns annualized volatility (252 trading days) |
//+------------------------------------------------------------------+
double DurationVolatility(const string symbol, const int tf,
const int bars, int shift = 0)
{
if(!ValidateSymbolV2(symbol) || bars < 2)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, shift, bars + 1, close) < bars + 1)
return 0.0;
int n_returns = ArraySize(close) - 1;
if(n_returns < 1)
return 0.0;
double sum_sq = 0.0;
int valid = 0;
for(int i = 0; i < n_returns; i++)
{
if(close[i] <= 0.0 || close[i+1] <= 0.0)
continue;
double r = SafeLog(close[i+1]) - SafeLog(close[i]);
sum_sq += r * r;
valid++;
}
if(valid == 0)
return 0.0;
double realized = MathSqrt(sum_sq / valid);
int tf_sec = PeriodSeconds(tf);
if(tf_sec <= 0)
return 0.0;
double ann_factor = MathSqrt(252.0 * 86400.0 / tf_sec);
return realized * ann_factor;
}
//+------------------------------------------------------------------+
//| FractionalVolatility: long‑memory weighted volatility using d |
//| If d <= -0.5 or d >= 0.5, defaults to realized volatility |
//+------------------------------------------------------------------+
double FractionalVolatility(const string symbol, const int tf,
const int window, double d = -1.0)
{
if(!ValidateSymbolV2(symbol) || window < 5)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, 0, window + 1, close) < window + 1)
return 0.0;
int n_returns = ArraySize(close) - 1;
if(n_returns < 4)
return 0.0;
//--- Build log‑return array
double returns[];
ArrayResize(returns, n_returns);
int valid_ret = 0;
for(int i = 0; i < n_returns; i++)
{
if(close[i] <= 0.0 || close[i+1] <= 0.0)
continue;
double r = SafeLog(close[i+1]) - SafeLog(close[i]);
if(MathAbs(r) < 0.1) // filter outliers as in Part 2/3
returns[valid_ret++] = r;
}
if(valid_ret < 5)
return 0.0;
ArrayResize(returns, valid_ret);
//--- Estimate d if not provided or invalid
if(d <= -0.49 || d >= 0.49)
{
double conf_dummy;
d = GPHEstimator(returns, valid_ret, conf_dummy);
}
d = MathMax(-0.49, MathMin(0.49, d));
//--- Compute weighted sum of squared returns (weights = k^(d-1))
double sum_w = 0.0, sum_wrr = 0.0;
for(int k = 1; k <= valid_ret; k++)
{
double w = MathPow((double)k, d - 1.0);
if(!MathIsValidNumber(w) || w > 1e10)
w = 1.0;
sum_w += w;
sum_wrr += w * returns[valid_ret - k] * returns[valid_ret - k];
}
if(sum_w <= DBL_MIN_POSITIVE)
return 0.0;
double frac_var = sum_wrr / sum_w;
return MathSqrt(MathMax(0.0, frac_var));
}
//+------------------------------------------------------------------+
//| FIGARCHVolatility: truncated power‑law weighted conditional var |
//| Uses d from the return series (estimated or provided) |
//+------------------------------------------------------------------+
double FIGARCHVolatility(const string symbol, const int tf,
const int window, double d = -1.0)
{
if(!ValidateSymbolV2(symbol) || window < 20)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, 0, window + 2, close) < window + 2)
return 0.0;
int n_returns = ArraySize(close) - 1;
if(n_returns < 20)
return 0.0;
//--- Build log‑return array
double returns[];
ArrayResize(returns, n_returns);
int valid_ret = 0;
for(int i = 0; i < n_returns; i++)
{
if(close[i] <= 0.0 || close[i+1] <= 0.0)
continue;
double r = SafeLog(close[i+1]) - SafeLog(close[i]);
if(MathAbs(r) < 0.1)
returns[valid_ret++] = r;
}
if(valid_ret < 20)
return 0.0;
ArrayResize(returns, valid_ret);
//--- Estimate d if needed
if(d <= -0.49 || d >= 0.49)
{
double conf_dummy;
d = GPHEstimator(returns, valid_ret, conf_dummy);
}
d = MathMax(-0.49, MathMin(0.49, d));
//--- Fixed FIGARCH parameters (approximation, not full MLE)
double omega = 0.000001; // small constant
double beta = 0.85; // persistence
int L = MathMin(100, valid_ret - 1);
//--- Compute weights via recursion: w0 = 1, wj = w(j-1) * (j-1-d)/j
double weights[];
ArrayResize(weights, L);
weights[0] = 1.0;
for(int j = 1; j < L; j++)
{
weights[j] = weights[j-1] * (j - 1.0 - d) / (double)j;
if(!MathIsValidNumber(weights[j]))
weights[j] = 0.0;
}
//--- Compute conditional variance using last L squared returns
double cond_var = 0.0;
double sum_w = 0.0;
for(int j = 0; j < L; j++)
{
int idx = valid_ret - 1 - j;
if(idx < 0)
break;
double sq_ret = returns[idx] * returns[idx];
cond_var += weights[j] * sq_ret;
sum_w += weights[j];
}
if(sum_w > DBL_MIN_POSITIVE)
cond_var = omega + beta * (cond_var / sum_w);
else
cond_var = omega;
if(cond_var <= 0.0)
return 0.0;
return MathSqrt(cond_var);
}
//+------------------------------------------------------------------+
//| VolatilityClusteringIndex: lag-1 autocorrelation of squared rets |
//| Returns value in [-1, 1]. High positive values indicate GARCH |
//+------------------------------------------------------------------+
double VolatilityClusteringIndex(const string symbol, const int tf,
const int window)
{
if(!ValidateSymbolV2(symbol) || window < 3)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, 0, window + 1, close) < window + 1)
return 0.0;
int n_returns = ArraySize(close) - 1;
if(n_returns < 3)
return 0.0;
double sq_ret[];
ArrayResize(sq_ret, n_returns);
int valid = 0;
for(int i = 0; i < n_returns; i++)
{
if(close[i] <= 0.0 || close[i+1] <= 0.0)
continue;
double r = SafeLog(close[i+1]) - SafeLog(close[i]);
sq_ret[valid++] = r * r;
}
if(valid < 3)
return 0.0;
ArrayResize(sq_ret, valid);
double mean = 0.0;
for(int i = 0; i < valid; i++)
mean += sq_ret[i];
mean /= valid;
double num = 0.0, den = 0.0;
for(int i = 0; i < valid - 1; i++)
{
num += (sq_ret[i] - mean) * (sq_ret[i+1] - mean);
den += (sq_ret[i] - mean) * (sq_ret[i] - mean);
}
if(den <= DBL_MIN_POSITIVE)
return 0.0;
double acf = num / den;
return MathMax(-1.0, MathMin(1.0, acf));
}
//+------------------------------------------------------------------+
//| LeverageEffect: asymmetric volatility response |
//| Returns (σ²_neg - σ²_pos) / (σ²_neg + σ²_pos) in [-1,1] |
//+------------------------------------------------------------------+
double LeverageEffect(const string symbol, const int tf,
const int window)
{
if(!ValidateSymbolV2(symbol) || window < 10)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, 0, window + 2, close) < window + 2)
return 0.0;
int n_returns = ArraySize(close) - 1;
if(n_returns < 10)
return 0.0;
double sum_sq_neg = 0.0, sum_sq_pos = 0.0;
int cnt_neg = 0, cnt_pos = 0;
for(int i = 0; i < n_returns - 1; i++)
{
if(close[i] <= 0.0 || close[i+1] <= 0.0 || close[i+2] <= 0.0)
continue;
double ret_t = SafeLog(close[i+1]) - SafeLog(close[i]);
double ret_t1 = SafeLog(close[i+2]) - SafeLog(close[i+1]);
if(!MathIsValidNumber(ret_t) || !MathIsValidNumber(ret_t1))
continue;
double vol_t1_sq = ret_t1 * ret_t1;
if(ret_t < 0)
{ sum_sq_neg += vol_t1_sq; cnt_neg++; }
else
{ sum_sq_pos += vol_t1_sq; cnt_pos++; }
}
if(cnt_neg == 0 || cnt_pos == 0)
return 0.0;
double var_neg = sum_sq_neg / cnt_neg;
double var_pos = sum_sq_pos / cnt_pos;
double denom = var_neg + var_pos;
if(denom <= DBL_MIN_POSITIVE)
return 0.0;
double leverage = (var_neg - var_pos) / denom;
return MathMax(-1.0, MathMin(1.0, leverage));
}
//+------------------------------------------------------------------+
//| JumpIntensity: proportion of returns exceeding sigma_mult * σ |
//| sigma_mult = 3.0 by default (3-sigma event) |
//+------------------------------------------------------------------+
double JumpIntensity(const string symbol, const int tf,
const int window, double sigma_mult = 3.0)
{
if(!ValidateSymbolV2(symbol) || window < 5 || sigma_mult <= 0.0)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, 0, window + 1, close) < window + 1)
return 0.0;
int n_returns = ArraySize(close) - 1;
if(n_returns < 5)
return 0.0;
double returns[];
ArrayResize(returns, n_returns);
int valid = 0;
for(int i = 0; i < n_returns; i++)
{
if(close[i] <= 0.0 || close[i+1] <= 0.0)
continue;
double r = SafeLog(close[i+1]) - SafeLog(close[i]);
if(MathIsValidNumber(r))
returns[valid++] = r;
}
if(valid < 5)
return 0.0;
ArrayResize(returns, valid);
double mean = 0.0, var = 0.0;
mean_var(returns, valid, mean, var);
double sd = MathSqrt(var);
if(sd <= DBL_MIN_POSITIVE)
return 0.0;
int jumps = 0;
double threshold = sigma_mult * sd;
for(int i = 0; i < valid; i++)
{
if(MathAbs(returns[i] - mean) > threshold)
jumps++;
}
return (double)jumps / valid;
}
//+------------------------------------------------------------------+
//| PopulateVolatilityAnalysis: fills VolatilityAnalysis struct |
//| in one call. Uses default shift=0 (current incomplete bar). |
//+------------------------------------------------------------------+
void PopulateVolatilityAnalysis(const string symbol, const int tf,
const int period, VolatilityAnalysis &result)
{
result.realized_vol = RealizedVolatility(symbol, tf, period, 0);
result.duration_vol = DurationVolatility(symbol, tf, period, 0);
result.fractional_vol = FractionalVolatility(symbol, tf, period, -1.0);
result.figarch_vol = FIGARCHVolatility(symbol, tf, period, -1.0);
result.clustering_index = VolatilityClusteringIndex(symbol, tf, period);
result.leverage_effect = LeverageEffect(symbol, tf, period);
result.jump_intensity = JumpIntensity(symbol, tf, period, 3.0);
//--- Asymmetry (skewness) is not directly computed here; set to 0 placeholder
result.asymmetry = 0.0;
//--- Validate outputs: replace any NaN/Inf with 0.0
if(!MathIsValidNumber(result.realized_vol))
result.realized_vol = 0.0;
if(!MathIsValidNumber(result.duration_vol))
result.duration_vol = 0.0;
if(!MathIsValidNumber(result.fractional_vol))
result.fractional_vol = 0.0;
if(!MathIsValidNumber(result.figarch_vol))
result.figarch_vol = 0.0;
if(!MathIsValidNumber(result.clustering_index))
result.clustering_index = 0.0;
if(!MathIsValidNumber(result.leverage_effect))
result.leverage_effect = 0.0;
if(!MathIsValidNumber(result.jump_intensity))
result.jump_intensity = 0.0;
}
//+------------------------------------------------------------------+
//| MicrostructureAnalysis: noise and spread decomposition results. |
//| Populated by PopulateMicrostructureAnalysis(). |
//| adverse_selection = quoted_spread - roll_spread. |
//| roll_confidence = |correlation| of adjacent returns [0,1]. |
//| On NQ M1 data, roll_spread approaches zero because intrabar |
//| price discovery absorbs the bid-ask bounce at 1-min aggregation. |
//+------------------------------------------------------------------+
struct MicrostructureAnalysis
{
double quoted_spread; // Mean bar range as spread proxy (points)
double roll_spread; // Roll (1984) implied spread (points)
double noise_ratio; // Enhanced OHLC noise ratio [0,1]
double order_imbalance; // Volume-weighted directional pressure [-1,+1]
double adverse_selection; // quoted_spread minus roll_spread (points)
double roll_confidence; // |correlation| of adjacent returns [0,1]
};
//+------------------------------------------------------------------+
//| BidAskSpread: quoted spread in points. |
//| Live: SymbolInfoDouble ASK - BID, divided by point size. |
//| Historical proxy: mean bar range over the window (points). |
//| The historical proxy conflates spread widening with directional |
//| intrabar movement but is consistent as a relative indicator. |
//+------------------------------------------------------------------+
double BidAskSpread(const string symbol, const int tf,
const int window)
{
if(!ValidateSymbolV2(symbol) || window < 2)
return 0.0;
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
if(point <= DBL_MIN_POSITIVE)
return 0.0;
//--- Attempt live bid-ask first (works on current bar)
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
if(ask > bid && bid > 0)
{
double spread = (ask - bid) / point;
if(spread < 10000.0)
return spread;
}
//--- Fallback: mean bar range as historical proxy
double high[], low[];
ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true);
if(CopyHigh(symbol, (ENUM_TIMEFRAMES)tf, 0, window, high) < window)
return 0.0;
if(CopyLow (symbol, (ENUM_TIMEFRAMES)tf, 0, window, low) < window)
return 0.0;
double sum_range = 0.0;
int valid = 0;
for(int i = 0; i < window; i++)
{
double r = (high[i] - low[i]) / point;
if(r > 0 && r < 10000.0)
{
sum_range += r;
valid++;
}
}
if(valid == 0)
return 0.0;
return sum_range / valid;
}
//+------------------------------------------------------------------+
//| MicrostructureNoise: close-to-midpoint variance fraction. |
//| Returns noise_basic in [0,1]. Higher = more noise. |
//| Midpoint = (High + Low) / 2. Measures how far Close deviates |
//| from midpoint relative to total bar range variance. |
//+------------------------------------------------------------------+
double MicrostructureNoise(const string symbol, const int tf,
const int window)
{
if(!ValidateSymbolV2(symbol) || window < 3)
return 0.0;
double high[], low[], close[];
ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true);
ArraySetAsSeries(close, true);
if(CopyHigh (symbol,(ENUM_TIMEFRAMES)tf,0,window,high) < window) return 0.0;
if(CopyLow (symbol,(ENUM_TIMEFRAMES)tf,0,window,low) < window) return 0.0;
if(SafeCopyClose(symbol,tf,0,window,close) < window) return 0.0;
double diff_vals[], rng_vals[];
ArrayResize(diff_vals, window);
ArrayResize(rng_vals, window);
int valid = 0;
for(int i = 0; i < window; i++)
{
double mid = (high[i] + low[i]) / 2.0;
if(mid <= DBL_MIN_POSITIVE)
continue;
diff_vals[valid] = (close[i] - mid) / mid;
rng_vals [valid] = (high[i] - low[i]) / mid;
valid++;
}
if(valid < 3)
return 0.0;
//--- Two-pass variance for numerical stability
double mean_d = 0.0, mean_r = 0.0;
for(int i = 0; i < valid; i++) { mean_d += diff_vals[i]; mean_r += rng_vals[i]; }
mean_d /= valid;
mean_r /= valid;
double var_d = 0.0, var_r = 0.0;
for(int i = 0; i < valid; i++)
{
var_d += (diff_vals[i] - mean_d) * (diff_vals[i] - mean_d);
var_r += (rng_vals[i] - mean_r) * (rng_vals[i] - mean_r);
}
var_d /= valid;
var_r /= valid;
if(var_r <= DBL_MIN_POSITIVE)
return 0.0;
return MathMin(1.0, var_d / (var_r + DBL_MIN_POSITIVE));
}
//+------------------------------------------------------------------+
//| EnhancedMicrostructureNoise: three-component OHLC noise ratio. |
//| Component 1 (40%): close-to-midpoint variance fraction. |
//| Component 2 (40%): 1 - body_to_range (Garman-Klass efficiency). |
//| Component 3 (20%): OC variance as fraction of range variance. |
//| Returns noise in [0,1]. Writes to rfa.microstructure_noise. |
//+------------------------------------------------------------------+
double EnhancedMicrostructureNoise(const string symbol, const int tf,
const int window,
RobustFractalAnalysis &rfa)
{
if(!ValidateSymbolV2(symbol) || window < 3)
return 0.0;
double open[], high[], low[], close[];
ArraySetAsSeries(open, true); ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true); ArraySetAsSeries(close,true);
if(CopyOpen (symbol,(ENUM_TIMEFRAMES)tf,0,window,open) < window) return 0.0;
if(CopyHigh (symbol,(ENUM_TIMEFRAMES)tf,0,window,high) < window) return 0.0;
if(CopyLow (symbol,(ENUM_TIMEFRAMES)tf,0,window,low) < window) return 0.0;
if(SafeCopyClose(symbol,tf,0,window,close) < window) return 0.0;
double diff_v[], rng_v[], btr_v[], oc_v[];
ArrayResize(diff_v, window); ArrayResize(rng_v, window);
ArrayResize(btr_v, window); ArrayResize(oc_v, window);
int valid = 0;
for(int i = 0; i < window; i++)
{
double br = high[i] - low[i];
double mid = (high[i] + low[i]) / 2.0;
if(mid <= DBL_MIN_POSITIVE || br <= DBL_MIN_POSITIVE)
continue;
diff_v[valid] = (close[i] - mid) / mid;
rng_v [valid] = br / mid;
btr_v [valid] = MathAbs(close[i] - open[i]) / br;
oc_v [valid] = (close[i] - open[i]) / mid;
valid++;
}
if(valid < 3)
return 0.0;
//--- Two-pass variance
double mean_d=0,mean_r=0,mean_oc=0,mean_btr=0;
for(int i=0;i<valid;i++)
{ mean_d+=diff_v[i]; mean_r+=rng_v[i]; mean_oc+=oc_v[i]; mean_btr+=btr_v[i]; }
mean_d/=valid; mean_r/=valid; mean_oc/=valid; mean_btr/=valid;
double var_d=0, var_r=0, var_oc=0;
for(int i=0;i<valid;i++)
{
var_d += (diff_v[i]-mean_d) *(diff_v[i]-mean_d);
var_r += (rng_v[i] -mean_r) *(rng_v[i] -mean_r);
var_oc += (oc_v[i] -mean_oc)*(oc_v[i] -mean_oc);
}
var_d/=valid; var_r/=valid; var_oc/=valid;
//--- Component 1: close-to-midpoint fraction
double c1 = (var_r > DBL_MIN_POSITIVE)
? MathMin(1.0, var_d / (var_r + DBL_MIN_POSITIVE)) : 0.0;
//--- Component 2: inverted body-to-range (Garman-Klass efficiency)
double c2 = MathMax(0.0, 1.0 - mean_btr);
//--- Component 3: OC variance as fraction of range variance
double c3 = (var_r > DBL_MIN_POSITIVE)
? MathMin(1.0, var_oc / (var_r + DBL_MIN_POSITIVE)) : 0.0;
double noise = MathMax(0.0, MathMin(1.0, 0.40*c1 + 0.40*c2 + 0.20*c3));
//--- Write to shared struct field reserved in Part 1
rfa.microstructure_noise = noise;
if(!MathIsValidNumber(rfa.microstructure_noise))
rfa.microstructure_noise = 0.0;
return noise;
}
//+------------------------------------------------------------------+
//| BidAskBounceEffect: Roll (1984) implied spread. |
//| spread = 2 * sqrt(max(0, -Cov(Δp_t, Δp_{t-1}))) |
//| confidence = |correlation| of the two return series [0,1]. |
//| |
//| On NQ M1, this returns values near zero because intrabar price |
//| discovery absorbs the bid-ask bounce at 1-min aggregation. |
//| Retained for sub-minute timeframes and wider-spread instruments. |
//+------------------------------------------------------------------+
double BidAskBounceEffect(const string symbol, const int tf,
const int window, double &confidence)
{
confidence = 0.0;
if(!ValidateSymbolV2(symbol) || window < 5)
return 0.0;
double close[];
if(SafeCopyClose(symbol, tf, 0, window + 1, close) < window + 1)
return 0.0;
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
if(point <= DBL_MIN_POSITIVE)
return 0.0;
//--- Build log-return array; filter gross outliers
int n = ArraySize(close) - 1;
double ret[];
ArrayResize(ret, n);
int valid = 0;
for(int i = 0; i < n; i++)
{
if(close[i] <= 0 || close[i+1] <= 0)
continue;
double r = SafeLog(close[i+1]) - SafeLog(close[i]);
if(MathAbs(r) < 0.1)
ret[valid++] = r;
}
if(valid < 4)
return 0.0;
ArrayResize(ret, valid);
//--- Two-pass covariance of adjacent returns
double mean1 = 0.0, mean2 = 0.0;
int pairs = valid - 1;
for(int i = 0; i < pairs; i++) { mean1 += ret[i]; mean2 += ret[i+1]; }
mean1 /= pairs;
mean2 /= pairs;
double cov = 0.0, var1 = 0.0, var2 = 0.0;
for(int i = 0; i < pairs; i++)
{
cov += (ret[i]-mean1) * (ret[i+1]-mean2);
var1 += (ret[i]-mean1) * (ret[i] -mean1);
var2 += (ret[i+1]-mean2) * (ret[i+1]-mean2);
}
cov /= pairs; var1 /= pairs; var2 /= pairs;
//--- Confidence: absolute correlation
double denom_conf = MathSqrt(MathMax(0,var1) * MathMax(0,var2));
if(denom_conf > DBL_MIN_POSITIVE)
confidence = MathMin(1.0, MathAbs(cov / denom_conf));
//--- Roll spread: floor at zero when covariance is positive
if(cov >= 0)
return 0.0;
double spread_price = 2.0 * MathSqrt(-cov);
return MathMax(0.0, spread_price / point);
}
//+------------------------------------------------------------------+
//| OrderImbalance: volume-weighted directional pressure. |
//| Returns (Close-Low)/(High-Low) centered at zero, volume-weighted.|
//| +1 = all closes at high (buyer dominated). |
//| -1 = all closes at low (seller dominated). |
//| Bars with High == Low excluded (zero range = undefined signal). |
//+------------------------------------------------------------------+
double OrderImbalance(const string symbol, const int tf,
const int window)
{
if(!ValidateSymbolV2(symbol) || window < 3)
return 0.0;
double high[], low[], close[];
long vol[];
ArraySetAsSeries(high, true); ArraySetAsSeries(low, true);
ArraySetAsSeries(close,true); ArraySetAsSeries(vol, true);
if(CopyHigh (symbol,(ENUM_TIMEFRAMES)tf,0,window,high) < window) return 0.0;
if(CopyLow (symbol,(ENUM_TIMEFRAMES)tf,0,window,low) < window) return 0.0;
if(SafeCopyClose (symbol,tf,0,window,close) < window) return 0.0;
if(CopyTickVolume(symbol,(ENUM_TIMEFRAMES)tf,0,window,vol) < window) return 0.0;
double weighted_sum = 0.0, total_vol = 0.0;
for(int i = 0; i < window; i++)
{
double br = high[i] - low[i];
if(br <= DBL_MIN_POSITIVE)
continue;
double frac = (close[i] - low[i]) / br;
double imb = 2.0 * frac - 1.0;
double v = (vol[i] > 0) ? (double)vol[i] : 1.0;
weighted_sum += imb * v;
total_vol += v;
}
if(total_vol <= DBL_MIN_POSITIVE)
return 0.0;
return MathMax(-1.0, MathMin(1.0, weighted_sum / total_vol));
}
//+------------------------------------------------------------------+
//| PopulateMicrostructureAnalysis: fills MicrostructureAnalysis |
//| and writes microstructure_noise into RobustFractalAnalysis. |
//| adverse_selection = quoted_spread - roll_spread. |
//| On NQ M1, roll_spread ≈ 0 so adverse_selection ≈ quoted_spread. |
//+------------------------------------------------------------------+
void PopulateMicrostructureAnalysis(const string symbol, const int tf,
const int window,
MicrostructureAnalysis &msa,
RobustFractalAnalysis &rfa)
{
msa.quoted_spread = BidAskSpread(symbol, tf, window);
msa.noise_ratio = EnhancedMicrostructureNoise(symbol, tf, window, rfa);
msa.roll_spread = BidAskBounceEffect(symbol, tf, window,
msa.roll_confidence);
msa.order_imbalance = OrderImbalance(symbol, tf, window);
msa.adverse_selection = MathMax(0.0, msa.quoted_spread - msa.roll_spread);
//--- NaN guards
if(!MathIsValidNumber(msa.quoted_spread)) msa.quoted_spread = 0.0;
if(!MathIsValidNumber(msa.roll_spread)) msa.roll_spread = 0.0;
if(!MathIsValidNumber(msa.noise_ratio)) msa.noise_ratio = 0.0;
if(!MathIsValidNumber(msa.order_imbalance)) msa.order_imbalance = 0.0;
if(!MathIsValidNumber(msa.adverse_selection)) msa.adverse_selection = 0.0;
if(!MathIsValidNumber(msa.roll_confidence)) msa.roll_confidence = 0.0;
}
//+------------------------------------------------------------------+
//| OrderFlowAnalysis: order flow measurement results. |
//| Populated by PopulateOrderFlowAnalysis(). |
//| flow_confidence is gated on noise (Part 5) and jump intensity |
//| (Part 4). It is zero when the session is jump-contaminated. |
//+------------------------------------------------------------------+
struct OrderFlowAnalysis
{
double vpin; // VPIN_OHLC: volume imbalance proxy [0,1]
double flow_imbalance; // Signed volume-weighted directional flow [-1,+1]
double trade_intensity; // Session vol relative to 20-session baseline
double smart_money; // Late-session minus early-session return differential
double flow_momentum; // Short-window minus long-window flow differential
double flow_confidence; // Reliability weight [0,1]; 0 = jump-contaminated
};
//+------------------------------------------------------------------+
//| VPIN_OHLC: volume imbalance proxy over a rolling window. |
//| buy_vol = (Close-Low)/(High-Low) * Volume |
//| sell_vol = (1-(Close-Low)/(High-Low)) * Volume |
//| VPIN = mean(|buy-sell|) / mean(total vol) across the window. |
//| |
//| THIS IS NOT THE EASLEY-LOPEZ DE PRADO-O'HARA VPIN. |
//| The canonical VPIN uses fixed-volume buckets, not fixed time |
//| bars. On NQ M1, intrabar aggregation compresses the imbalance |
//| signal toward 0.5. Treat as a directional indicator only. |
//+------------------------------------------------------------------+
double VPIN_OHLC(const string symbol, const int tf,
const int window)
{
if(!ValidateSymbolV2(symbol) || window < 5)
return 0.5;
double high[], low[], close[];
long vol[];
ArraySetAsSeries(high, true); ArraySetAsSeries(low, true);
ArraySetAsSeries(close,true); ArraySetAsSeries(vol, true);
if(CopyHigh (symbol,(ENUM_TIMEFRAMES)tf,0,window,high) < window) return 0.5;
if(CopyLow (symbol,(ENUM_TIMEFRAMES)tf,0,window,low) < window) return 0.5;
if(SafeCopyClose (symbol,tf,0,window,close) < window) return 0.5;
if(CopyTickVolume(symbol,(ENUM_TIMEFRAMES)tf,0,window,vol) < window) return 0.5;
double sum_imb = 0.0, sum_vol = 0.0;
for(int i = 0; i < window; i++)
{
double br = high[i] - low[i];
if(br <= DBL_MIN_POSITIVE)
continue;
double v = (vol[i] > 0) ? (double)vol[i] : 1.0;
double frac = MathMax(0.0, MathMin(1.0, (close[i] - low[i]) / br));
double buy_v = frac * v;
double sell_v = (1.0 - frac) * v;
sum_imb += MathAbs(buy_v - sell_v);
sum_vol += v;
}
if(sum_vol <= DBL_MIN_POSITIVE)
return 0.5;
return MathMax(0.0, MathMin(1.0, sum_imb / sum_vol));
}
//+------------------------------------------------------------------+
//| OrderFlowImbalance: signed volume-weighted directional flow. |
//| Each bar: signed_imb = ((Close-Low)/(High-Low) - 0.5) * 2 * vol |
//| Returns sum(signed_imb) / sum(vol) in [-1,+1]. |
//| +1 = all closes at high (buyer dominated). |
//| -1 = all closes at low (seller dominated). |
//+------------------------------------------------------------------+
double OrderFlowImbalance(const string symbol, const int tf,
const int window)
{
if(!ValidateSymbolV2(symbol) || window < 3)
return 0.0;
double high[], low[], close[];
long vol[];
ArraySetAsSeries(high, true); ArraySetAsSeries(low, true);
ArraySetAsSeries(close,true); ArraySetAsSeries(vol, true);
if(CopyHigh (symbol,(ENUM_TIMEFRAMES)tf,0,window,high) < window) return 0.0;
if(CopyLow (symbol,(ENUM_TIMEFRAMES)tf,0,window,low) < window) return 0.0;
if(SafeCopyClose (symbol,tf,0,window,close) < window) return 0.0;
if(CopyTickVolume(symbol,(ENUM_TIMEFRAMES)tf,0,window,vol) < window) return 0.0;
double weighted_sum = 0.0, total_vol = 0.0;
for(int i = 0; i < window; i++)
{
double br = high[i] - low[i];
if(br <= DBL_MIN_POSITIVE)
continue;
double frac = MathMax(0.0, MathMin(1.0, (close[i] - low[i]) / br));
double v = (vol[i] > 0) ? (double)vol[i] : 1.0;
weighted_sum += (frac - 0.5) * 2.0 * v;
total_vol += v;
}
if(total_vol <= DBL_MIN_POSITIVE)
return 0.0;
return MathMax(-1.0, MathMin(1.0, weighted_sum / total_vol));
}
//+------------------------------------------------------------------+
//| TradeIntensity: current vol relative to historical baseline. |
//| Returns mean_volume(window) / baseline. |
//| baseline must be pre-computed from a longer lookback (caller). |
//| Values above 1.0 = above-average activity. |
//| NOTE: baseline requires at least 20 sessions to be meaningful. |
//| The first 20 sessions after data start will produce inflated |
//| values as the baseline warms up. Check baseline > 1 before use. |
//+------------------------------------------------------------------+
double TradeIntensity(const string symbol, const int tf,
const int window, double baseline)
{
if(!ValidateSymbolV2(symbol) || window < 2 || baseline <= DBL_MIN_POSITIVE)
return 1.0;
long vol[];
ArraySetAsSeries(vol, true);
if(CopyTickVolume(symbol,(ENUM_TIMEFRAMES)tf,0,window,vol) < window)
return 1.0;
double sum_v = 0.0;
int valid = 0;
for(int i = 0; i < window; i++)
if(vol[i] > 0) { sum_v += (double)vol[i]; valid++; }
if(valid == 0)
return 1.0;
return MathMax(0.0, (sum_v / valid) / baseline);
}
//+------------------------------------------------------------------+
//| SmartMoneyIndex: late-session minus early-session return. |
//| Positive: late buying after early selling = accumulation signal. |
//| Negative: late selling after early buying = distribution signal. |
//| n_ends: bars used for each window (default 15). |
//| Normalized by session range to be dimensionless. |
//+------------------------------------------------------------------+
double SmartMoneyIndex(const string symbol, const int tf,
const int window, int n_ends = 15)
{
if(!ValidateSymbolV2(symbol) || window < 2 * n_ends + 10)
return 0.0;
double open[], high[], low[], close[];
ArraySetAsSeries(open, true); ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true); ArraySetAsSeries(close,true);
if(CopyOpen (symbol,(ENUM_TIMEFRAMES)tf,0,window,open) < window) return 0.0;
if(CopyHigh (symbol,(ENUM_TIMEFRAMES)tf,0,window,high) < window) return 0.0;
if(CopyLow (symbol,(ENUM_TIMEFRAMES)tf,0,window,low) < window) return 0.0;
if(SafeCopyClose(symbol,tf,0,window,close) < window) return 0.0;
//--- Note: ArraySetAsSeries=true means index 0 = most recent bar
//--- Early bars = end of array (oldest); late bars = start (newest)
double early_ret = 0.0;
for(int i = window - 1; i >= window - n_ends; i--)
{
if(open[i] <= 0 || close[i] <= 0)
continue;
double r = SafeLog(close[i]) - SafeLog(open[i]);
if(MathAbs(r) < 0.1)
early_ret += r;
}
double late_ret = 0.0;
for(int i = 0; i < n_ends; i++)
{
if(open[i] <= 0 || close[i] <= 0)
continue;
double r = SafeLog(close[i]) - SafeLog(open[i]);
if(MathAbs(r) < 0.1)
late_ret += r;
}
//--- Normalize by session range
double h_max = high[0], l_min = low[0];
for(int i = 1; i < window; i++)
{
if(high[i] > h_max) h_max = high[i];
if(low[i] < l_min) l_min = low[i];
}
double mid = (h_max + l_min) / 2.0;
if(mid <= DBL_MIN_POSITIVE)
return 0.0;
double norm_range = (h_max - l_min) / mid;
if(norm_range <= DBL_MIN_POSITIVE)
return 0.0;
return MathMax(-1.0, MathMin(1.0, (late_ret - early_ret) / norm_range));
}
//+------------------------------------------------------------------+
//| OrderFlowMomentum: short-window minus long-window flow. |
//| Positive: directional pressure building. |
//| Negative: flow mean-reverting. |
//| Uses the same signed volume proxy as OrderFlowImbalance(). |
//+------------------------------------------------------------------+
double OrderFlowMomentum(const string symbol, const int tf,
int short_w = 10, int long_w = 30)
{
if(!ValidateSymbolV2(symbol) || short_w < 2 || long_w <= short_w)
return 0.0;
double short_flow = OrderFlowImbalance(symbol, tf, short_w);
double long_flow = OrderFlowImbalance(symbol, tf, long_w);
return MathMax(-2.0, MathMin(2.0, short_flow - long_flow));
}
//+------------------------------------------------------------------+
//| PopulateOrderFlowAnalysis: fills OrderFlowAnalysis struct. |
//| vol_baseline: 20-session rolling mean bar volume (caller). |
//| flow_confidence gated on: |
//| jump_intensity > 0.021 (Part 4 P90) → confidence = 0 |
//| noise_ratio > 0.632 (Part 5 P75) → confidence reduced |
//+------------------------------------------------------------------+
void PopulateOrderFlowAnalysis(const string symbol, const int tf,
const int window,
OrderFlowAnalysis &ofa,
const MicrostructureAnalysis &msa,
const VolatilityAnalysis &va,
double vol_baseline = 0.0)
{
ofa.vpin = VPIN_OHLC(symbol, tf, window);
ofa.flow_imbalance = OrderFlowImbalance(symbol, tf, window);
ofa.trade_intensity = TradeIntensity(symbol, tf, window,
(vol_baseline > DBL_MIN_POSITIVE)
? vol_baseline : 1.0);
ofa.smart_money = SmartMoneyIndex(symbol, tf, window);
ofa.flow_momentum = OrderFlowMomentum(symbol, tf, 10, 30);
//--- Flow confidence: gated on noise (Part 5) and jumps (Part 4)
if(va.jump_intensity > 0.021)
{
ofa.flow_confidence = 0.0; // jump-contaminated session
}
else if(msa.noise_ratio > 0.632)
{
//--- Elevated noise: reduce confidence proportionally
double excess = (msa.noise_ratio - 0.632) / (1.0 - 0.632);
ofa.flow_confidence = MathMax(0.0, 0.7 * (1.0 - excess));
}
else
{
//--- Normal noise: confidence scaled from noise quality
ofa.flow_confidence = MathMax(0.0, MathMin(1.0,
1.0 - (msa.noise_ratio / 0.632) * 0.3));
}
//--- NaN guards
if(!MathIsValidNumber(ofa.vpin)) ofa.vpin = 0.5;
if(!MathIsValidNumber(ofa.flow_imbalance)) ofa.flow_imbalance = 0.0;
if(!MathIsValidNumber(ofa.trade_intensity)) ofa.trade_intensity = 1.0;
if(!MathIsValidNumber(ofa.smart_money)) ofa.smart_money = 0.0;
if(!MathIsValidNumber(ofa.flow_momentum)) ofa.flow_momentum = 0.0;
if(!MathIsValidNumber(ofa.flow_confidence)) ofa.flow_confidence = 0.0;
}
//+------------------------------------------------------------------+
//| MARKET_REGIME: six-state regime classification. |
//| Used in RegimeAnalysis.regime field. |
//+------------------------------------------------------------------+
enum MARKET_REGIME
{
REGIME_NORMAL = 0, // Residual — no named regime applies
REGIME_STRESSED = 1, // Elevated vol/noise/jumps — reduce size
REGIME_NOISY = 2, // High noise + low flow confidence
REGIME_INFORMED = 3, // Elevated VPIN in clean environment
REGIME_TRENDING = 4, // High clustering + monofractal structure
REGIME_MEAN_REVERTING = 5, // Anti-persistent d + low clustering
};
//+------------------------------------------------------------------+
//| RegimeAnalysis: composite regime classification result. |
//| Populated by RegimeClassifier() or PopulateRegimeAnalysis(). |
//| composite_score: signed directional signal [-1,+1]. |
//| Trending/Informed: follow flow direction. |
//| Mean-Reverting: fade flow direction. |
//| Stressed/Noisy: zero — no directional signal offered. |
//+------------------------------------------------------------------+
struct RegimeAnalysis
{
MARKET_REGIME regime; // Current regime label
double confidence; // Classification confidence [0,1]
double composite_score; // Signed directional score [-1,+1]
};
//+------------------------------------------------------------------+
//| RegimeClassifier: priority-ordered rule-based regime classifier. |
//| |
//| Thresholds calibrated from 514 NQ M1 sessions (May 2024 – |
//| May 2026). Recalibrate on your own instrument and sample period. |
//| |
//| Priority (first match wins): |
//| 1. STRESSED — vol/noise/jump threshold exceeded |
//| 2. INFORMED — VPIN + clustering + low noise (all four) |
//| 3. TRENDING — clustering P75 + delta_alpha < median |
//| 4. NOISY — noise P75 + flow_confidence P25 |
//| 5. MEAN_REVERTING— GPH d P25 + clustering P25 |
//| 6. NORMAL — residual |
//| |
//| Confidence reliability: sqrt(mfdfa_conf * flow_conf). |
//| Roll confidence excluded — near-zero on NQ M1 (Part 5). |
//+------------------------------------------------------------------+
RegimeAnalysis RegimeClassifier(const RobustFractalAnalysis &rfa,
const VolatilityAnalysis &va,
const MicrostructureAnalysis &msa,
const OrderFlowAnalysis &ofa)
{
RegimeAnalysis result;
result.regime = REGIME_NORMAL;
result.confidence = 0.0;
result.composite_score = 0.0;
//--- Thresholds (NQ M1, May 2024 – May 2026 calibration)
const double RV_P75 = 0.000501; // realized_vol 75th pct
const double RV_P90 = 0.000630; // realized_vol 90th pct
const double NOISE_P75 = 0.6317; // noise_ratio 75th pct
const double VPIN_P75 = 0.5393; // vpin 75th pct
const double CL_P75 = 0.2026; // clustering_idx 75th pct
const double CL_P25 = 0.0756; // clustering_idx 25th pct
const double CL_MED = 0.1376; // clustering_idx median
const double DA_MED = 0.8747; // delta_alpha median
const double GPH_P25 = -0.0611; // gph_d 25th pct
const double FC_P25 = 0.6790; // flow_confidence 25th pct
//--- Input fields
double rv = va.realized_vol;
double noise = msa.noise_ratio;
double vpin = ofa.vpin;
double cl = va.clustering_index;
double da = rfa.multifractal_width;
double gph_d = rfa.arfima_d;
double fc = ofa.flow_confidence;
double flow_i = ofa.flow_imbalance;
double mfdfa_c= rfa.dimension_confidence;
//--- Reliability: geometric mean of MFDFA confidence and flow confidence
//--- Roll confidence excluded — near-zero on NQ M1 (Part 5)
double mfdfa_safe = MathMax(0.01, MathMin(1.0, mfdfa_c));
double fc_safe = MathMax(0.05, fc);
double reliability = MathSqrt(mfdfa_safe * fc_safe);
//--- 1. STRESSED
int s_count = 0;
if(fc <= 0.0) s_count++; // jump-contaminated
if(rv > RV_P90) s_count++; // extreme vol
if(rv > RV_P75 && noise > NOISE_P75) s_count++; // vol + noise spike
if(s_count > 0)
{
result.regime = REGIME_STRESSED;
result.confidence = MathMin(1.0, 0.55 + 0.15*s_count) * reliability;
return result; // composite_score = 0 for stressed
}
//--- 2. INFORMED: all four conditions required
if(vpin > VPIN_P75
&& noise < NOISE_P75
&& cl > CL_MED
&& fc > FC_P25)
{
double conf = MathMin(1.0,
0.55 + (vpin - VPIN_P75) * 5.0) * reliability;
result.regime = REGIME_INFORMED;
result.confidence = conf;
result.composite_score = MathSign(flow_i) * conf * 0.5;
return result;
}
//--- 3. TRENDING: clustering P75 + delta_alpha below median
if(cl > CL_P75
&& da < DA_MED
&& noise < NOISE_P75)
{
double conf = MathMin(1.0,
0.50 + (cl - CL_P75) / 0.40) * reliability;
result.regime = REGIME_TRENDING;
result.confidence = conf;
result.composite_score = MathSign(flow_i) * conf * 0.6;
return result;
}
//--- 4. NOISY: noise P75 + flow_confidence P25
if(noise > NOISE_P75 && fc < FC_P25)
{
double conf = MathMin(1.0,
0.50 + (noise - NOISE_P75) * 3.0) * reliability;
result.regime = REGIME_NOISY;
result.confidence = conf;
return result; // composite_score = 0 for noisy
}
//--- 5. MEAN-REVERTING: GPH d P25 + clustering P25
if(gph_d < GPH_P25 && cl < CL_P25)
{
double conf = MathMin(1.0,
0.45 + MathAbs(gph_d) * 1.5) * reliability;
result.regime = REGIME_MEAN_REVERTING;
result.confidence = conf;
result.composite_score = -MathSign(flow_i) * conf * 0.4;
return result;
}
//--- 6. NORMAL: residual
result.regime = REGIME_NORMAL;
result.confidence = MathMin(1.0, 0.30 + 0.40*fc) * reliability;
result.composite_score = 0.05 * MathSign(flow_i) * fc;
return result;
}
//+------------------------------------------------------------------+
//| PopulateRegimeAnalysis: full measurement chain + classifier. |
//| Calls Parts 2-6 Populate() functions in sequence then classifies.|
//| vol_baseline: 20-session rolling mean bar volume (caller). |
//+------------------------------------------------------------------+
void PopulateRegimeAnalysis(const string symbol, const int tf,
const int period,
RegimeAnalysis &regime_out,
RobustFractalAnalysis &rfa,
VolatilityAnalysis &va,
MicrostructureAnalysis &msa,
OrderFlowAnalysis &ofa,
double vol_baseline = 0.0)
{
PopulateHurstAnalysis (symbol, tf, period, rfa);
PopulateMultifractalAnalysis (symbol, tf, period, rfa);
PopulateVolatilityAnalysis (symbol, tf, period, va);
PopulateMicrostructureAnalysis(symbol, tf, period, msa, rfa);
PopulateOrderFlowAnalysis (symbol, tf, period, ofa, msa, va,
vol_baseline);
regime_out = RegimeClassifier (rfa, va, msa, ofa);
}
//+------------------------------------------------------------------+
//| Overload: classifier only (pre-populated structs supplied). |
//| Use when individual Populate() functions are called separately. |
//+------------------------------------------------------------------+
void PopulateRegimeAnalysis(const RobustFractalAnalysis &rfa,
const VolatilityAnalysis &va,
const MicrostructureAnalysis &msa,
const OrderFlowAnalysis &ofa,
RegimeAnalysis &regime_out)
{
regime_out = RegimeClassifier(rfa, va, msa, ofa);
}
//+------------------------------------------------------------------+
//| PART 8 — MICRO-TREND STRENGTH |
//+------------------------------------------------------------------+
//| ENGINEERING HEURISTIC — NOT A PUBLISHED MODEL. |
//| GetMicroTrendStrength() combines four EMA-derived sub-scores |
//| (alignment, ATR-normalized price position, slope consistency, |
//| volume confirmation) with a contradiction penalty. It is a |
//| pragmatic approximation — same category as FIGARCHVolatility() |
//| in Part 4 and VPIN_OHLC() in Part 6. |
//| |
//| IMPLEMENTATION NOTE: EMA is computed as a recursive exponential |
//| moving average from CopyClose() data. ATR is computed from |
//| CopyHigh/CopyLow/CopyClose. This matches the pattern used |
//| throughout Parts 1-7 — raw price arrays, no indicator handles. |
//+------------------------------------------------------------------+
#define MT_EMA_MIN_BARS 30 // Minimum bars before slope calc is trusted
#define MT_DEFAULT_LOOKBACK 5 // Bars used for EMA slope (5-bar window)
#define MT_THRESH_HIGH_BASE 0.7 // Strong-signal threshold (fixed overload)
#define MT_THRESH_LOW_BASE 0.3 // Weak-signal threshold (fixed overload)
//+------------------------------------------------------------------+
//| TREND_LABEL: seven-state classification of micro-trend strength. |
//| Used in MicroTrendAnalysis.label field. |
//+------------------------------------------------------------------+
enum TREND_LABEL
{
TREND_STRONG_DOWN = -3, // strength < -threshold_high
TREND_DOWN = -2, // strength < -threshold_low
TREND_WEAK_DOWN = -1, // strength < -threshold_low/2 (informational)
TREND_FLAT = 0, // |strength| <= threshold_low/2
TREND_WEAK_UP = 1, // strength > threshold_low/2 (informational)
TREND_UP = 2, // strength > threshold_low
TREND_STRONG_UP = 3 // strength > threshold_high
};
//+------------------------------------------------------------------+
//| MicroTrendAnalysis: composite micro-trend scoring result. |
//| Populated by PopulateMicroTrendAnalysis(). |
//+------------------------------------------------------------------+
struct MicroTrendAnalysis
{
double strength; // Composite score [-1,+1]
TREND_LABEL label; // Seven-state classification
int binary_signal; // -1 / 0 / +1
int persistent_dir; // -1 / 0 / +1 sustained over N bars
double threshold_high; // Adaptive or fixed strong-signal cutoff
double threshold_low; // Adaptive or fixed weak-signal cutoff
};
//+------------------------------------------------------------------+
//| ComputeEMA: single recursive EMA from a close array. |
//| arr[0] = oldest bar, arr[n-1] = most recent bar. |
//| Returns the EMA value at index (n-1) — the most recent bar. |
//+------------------------------------------------------------------+
double ComputeEMA(const double &arr[], int n, int period)
{
if(n < period || period < 1) return 0.0;
double k = 2.0 / (period + 1.0);
//--- Seed with SMA of the first 'period' values
double ema = 0.0;
for(int i = 0; i < period; i++) ema += arr[i];
ema /= period;
//--- Recurse through the rest
for(int i = period; i < n; i++)
ema = arr[i] * k + ema * (1.0 - k);
return ema;
}
//+------------------------------------------------------------------+
//| ComputeEMAAt: EMA value at a specific index within arr[]. |
//| arr[0]=oldest, arr[n-1]=most recent. Returns EMA at index idx. |
//+------------------------------------------------------------------+
double ComputeEMAAt(const double &arr[], int n, int period, int idx)
{
if(idx < period - 1 || period < 1 || idx >= n) return 0.0;
double k = 2.0 / (period + 1.0);
double ema = 0.0;
for(int i = 0; i < period; i++) ema += arr[i];
ema /= period;
for(int i = period; i <= idx; i++)
ema = arr[i] * k + ema * (1.0 - k);
return ema;
}
//+------------------------------------------------------------------+
//| ComputeATR: Wilder ATR from high/low/close arrays. |
//| arr indices: [0]=oldest, [n-1]=most recent. |
//+------------------------------------------------------------------+
double ComputeATR(const double &hi[], const double &lo[],
const double &cl[], int n, int period)
{
if(n < period + 1 || period < 1) return 0.0;
//--- Seed: simple mean of first 'period' true ranges
double atr = 0.0;
for(int i = 1; i <= period; i++)
{
double tr = MathMax(hi[i] - lo[i],
MathMax(MathAbs(hi[i] - cl[i-1]),
MathAbs(lo[i] - cl[i-1])));
atr += tr;
}
atr /= period;
//--- Wilder smoothing
for(int i = period + 1; i < n; i++)
{
double tr = MathMax(hi[i] - lo[i],
MathMax(MathAbs(hi[i] - cl[i-1]),
MathAbs(lo[i] - cl[i-1])));
atr = (atr * (period - 1) + tr) / period;
}
return atr;
}
//+------------------------------------------------------------------+
//| GetMicroTrendStrength: composite EMA-based trend score [-1,+1]. |
//| |
//| Requires shift >= 1 to avoid lookahead on the forming bar. |
//| All indicator values are computed from completed bars only. |
//+------------------------------------------------------------------+
double GetMicroTrendStrength(const string symbol, const int tf,
const int ema_fast, const int ema_med,
const int ema_slow, const int atr_period,
int shift = 1)
{
if(!ValidateSymbolV2(symbol)) return 0.0;
if(ema_fast >= ema_med || ema_med >= ema_slow) return 0.0;
if(shift < 1) shift = 1;
//--- Need enough bars: slow EMA warmup + lookback + shift + ATR + 1
int need = ema_slow + MT_DEFAULT_LOOKBACK + atr_period + shift + 2;
double cl[];
if(SafeCopyClose(symbol, tf, 0, need, cl) < need) return 0.0;
//--- Reverse to chronological order (oldest first) for EMA computation
//--- SafeCopyClose returns newest-first (cl[0]=most recent)
//--- Reverse so cl_chron[0]=oldest
int sz = ArraySize(cl);
double cl_chron[];
ArrayResize(cl_chron, sz);
for(int i = 0; i < sz; i++) cl_chron[i] = cl[sz - 1 - i];
//--- Target index within chronological array (shift bars from the end)
int tgt = sz - 1 - shift; // index of the bar at 'shift'
int tgt0 = sz - 1 - (shift + MT_DEFAULT_LOOKBACK); // lookback bar
if(tgt < ema_slow || tgt0 < ema_slow) return 0.0;
//--- Compute EMAs at target bar
double ef = ComputeEMAAt(cl_chron, sz, ema_fast, tgt);
double em = ComputeEMAAt(cl_chron, sz, ema_med, tgt);
double es = ComputeEMAAt(cl_chron, sz, ema_slow, tgt);
//--- Compute EMAs at lookback bar for slope
double ef0 = ComputeEMAAt(cl_chron, sz, ema_fast, tgt0);
double em0 = ComputeEMAAt(cl_chron, sz, ema_med, tgt0);
double es0 = ComputeEMAAt(cl_chron, sz, ema_slow, tgt0);
//--- Price at target bar
double price = cl_chron[tgt];
if(price <= 0) return 0.0;
//--- ATR at target bar
double hi[], lo[];
if(CopyHigh(symbol, (ENUM_TIMEFRAMES)tf, 0, need, hi) < need) return 0.0;
if(CopyLow (symbol, (ENUM_TIMEFRAMES)tf, 0, need, lo) < need) return 0.0;
//--- Reverse to chronological
double hi_chron[], lo_chron[];
ArrayResize(hi_chron, sz); ArrayResize(lo_chron, sz);
for(int i = 0; i < sz; i++)
{ hi_chron[i] = hi[sz-1-i]; lo_chron[i] = lo[sz-1-i]; }
//--- Use a sub-array ending at tgt for ATR computation
int atr_sz = tgt + 1;
double hi_sub[], lo_sub[], cl_sub[];
ArrayResize(hi_sub, atr_sz); ArrayResize(lo_sub, atr_sz);
ArrayResize(cl_sub, atr_sz);
for(int i = 0; i < atr_sz; i++)
{ hi_sub[i]=hi_chron[i]; lo_sub[i]=lo_chron[i]; cl_sub[i]=cl_chron[i]; }
double atr = ComputeATR(hi_sub, lo_sub, cl_sub, atr_sz, atr_period);
if(atr <= 0) atr = 0.1;
//--- (1) Alignment: +-0.33/0.34 per pairwise EMA ordering
double align = (ef > em ? 0.33 : -0.33)
+ (em > es ? 0.33 : -0.33)
+ (ef > es ? 0.34 : -0.34);
//--- (2) Price position: tanh-compressed, ATR-normalised (40/30/30)
double price_pos = SafeTanh((price - ef) / atr) * 0.40
+ SafeTanh((price - em) / atr) * 0.30
+ SafeTanh((price - es) / atr) * 0.30;
//--- (3) Slope consistency over MT_DEFAULT_LOOKBACK bars
double sf = ef - ef0, sm = em - em0, ss = es - es0;
double slope = 0.0;
if(sf > 0 && sm > 0 && ss > 0)
slope = MathMin( 1.0, (sf + sm + ss) / (3.0 * atr));
else if(sf < 0 && sm < 0 && ss < 0)
slope = MathMax(-1.0, (sf + sm + ss) / (3.0 * atr));
//--- (4) Volume confirmation: current bar vs 20-bar average, [0.5, 1.5]
long vol[];
double vol_boost = 1.0;
int vol_need = shift + 21;
if(CopyTickVolume(symbol, (ENUM_TIMEFRAMES)tf, 0, vol_need, vol) >= vol_need)
{
double avg_vol = 0.0;
for(int v = shift; v < shift + 20; v++) avg_vol += (double)vol[v];
avg_vol /= 20.0;
if(avg_vol > 0)
{
double ratio = (double)vol[shift] / avg_vol;
vol_boost = MathMin(1.5, MathMax(0.5, 0.5 + ratio));
}
}
//--- Combine: align 40%, price_pos 40%, slope 20%, then volume-scale
double base = (align * 0.4 + price_pos * 0.4 + slope * 0.2) * vol_boost;
//--- Contradiction penalty
if(align > 0 && price < ef) base *= 0.3;
else if(align < 0 && price > ef) base *= 0.3;
return MathMax(-1.0, MathMin(1.0, base));
}
//+------------------------------------------------------------------+
//| GetTrendLabel: maps strength to a seven-state TREND_LABEL. |
//+------------------------------------------------------------------+
TREND_LABEL GetTrendLabel(const double strength,
double threshold_high = MT_THRESH_HIGH_BASE,
double threshold_low = MT_THRESH_LOW_BASE)
{
double half_low = threshold_low / 2.0;
if(strength > threshold_high) return TREND_STRONG_UP;
if(strength > threshold_low) return TREND_UP;
if(strength > half_low) return TREND_WEAK_UP;
if(strength < -threshold_high) return TREND_STRONG_DOWN;
if(strength < -threshold_low) return TREND_DOWN;
if(strength < -half_low) return TREND_WEAK_DOWN;
return TREND_FLAT;
}
//+------------------------------------------------------------------+
//| GetBinarySignal: returns -1, 0, or +1. |
//+------------------------------------------------------------------+
int GetBinarySignal(const double strength,
double threshold_high = MT_THRESH_HIGH_BASE)
{
if(strength > threshold_high) return 1;
if(strength < -threshold_high) return -1;
return 0;
}
//+------------------------------------------------------------------+
//| GetPersistentTrendDirection: direction sustained over N bars. |
//| Returns 0 if binary signal is not identical across all N bars. |
//+------------------------------------------------------------------+
int GetPersistentTrendDirection(const string symbol, const int tf,
const int ema_fast, const int ema_med,
const int ema_slow, const int atr_period,
int n_bars = 3,
double threshold_high = MT_THRESH_HIGH_BASE)
{
if(n_bars < 1) return 0;
int dir = 0;
for(int i = 1; i <= n_bars; i++)
{
double s = GetMicroTrendStrength(symbol, tf, ema_fast, ema_med,
ema_slow, atr_period, i);
int b = GetBinarySignal(s, threshold_high);
if(b == 0) return 0;
if(dir == 0) dir = b;
else if(b != dir) return 0;
}
return dir;
}
//+------------------------------------------------------------------+
//| PopulateMicroTrendAnalysis: fixed-threshold overload. |
//+------------------------------------------------------------------+
void PopulateMicroTrendAnalysis(const string symbol, const int tf,
const int ema_fast, const int ema_med,
const int ema_slow, const int atr_period,
MicroTrendAnalysis &mta,
int persistent_n_bars = 3)
{
mta.threshold_high = MT_THRESH_HIGH_BASE;
mta.threshold_low = MT_THRESH_LOW_BASE;
mta.strength = GetMicroTrendStrength(symbol, tf, ema_fast, ema_med,
ema_slow, atr_period, 1);
mta.label = GetTrendLabel(mta.strength, mta.threshold_high,
mta.threshold_low);
mta.binary_signal = GetBinarySignal(mta.strength, mta.threshold_high);
mta.persistent_dir = GetPersistentTrendDirection(symbol, tf, ema_fast,
ema_med, ema_slow, atr_period,
persistent_n_bars, mta.threshold_high);
if(!MathIsValidNumber(mta.strength)) mta.strength = 0.0;
}
//+------------------------------------------------------------------+
//| PopulateMicroTrendAnalysis: session-adaptive threshold overload. |
//| Requires RegimeAnalysis from Part 7. |
//| threshold_high = 0.70 - 0.15 * confidence [clamped 0.10, 0.90] |
//| threshold_low = 0.30 - 0.10 * confidence [clamped 0.10, 0.90] |
//+------------------------------------------------------------------+
void PopulateMicroTrendAnalysis(const string symbol, const int tf,
const int ema_fast, const int ema_med,
const int ema_slow, const int atr_period,
MicroTrendAnalysis &mta,
const RegimeAnalysis &reg,
int persistent_n_bars = 3)
{
double conf = MathMax(0.0, MathMin(1.0, reg.confidence));
mta.threshold_high = MathMax(0.10, MathMin(0.90,
MT_THRESH_HIGH_BASE - 0.15 * conf));
mta.threshold_low = MathMax(0.10, MathMin(0.90,
MT_THRESH_LOW_BASE - 0.10 * conf));
mta.strength = GetMicroTrendStrength(symbol, tf, ema_fast, ema_med,
ema_slow, atr_period, 1);
mta.label = GetTrendLabel(mta.strength, mta.threshold_high,
mta.threshold_low);
mta.binary_signal = GetBinarySignal(mta.strength, mta.threshold_high);
mta.persistent_dir = GetPersistentTrendDirection(symbol, tf, ema_fast,
ema_med, ema_slow, atr_period,
persistent_n_bars, mta.threshold_high);
if(!MathIsValidNumber(mta.strength)) mta.strength = 0.0;
}
//+------------------------------------------------------------------+
//| ██████████████████████████████████████████████████████████████ |
//| PART 9 — PULLBACK QUALITY |
//| Appended to MicroStructure_Foundation.mqh (v8.00 → v9.00) |
//| Requires: MicroTrendAnalysis from Part 8 |
//| ██████████████████████████████████████████████████████████████ |
//+------------------------------------------------------------------+
//--- Fibonacci retracement constants (inline documentation)
#define PB_FIBO_236 0.236 // Fibonacci 23.6% retracement level
#define PB_FIBO_382 0.382 // Fibonacci 38.2% retracement level
#define PB_FIBO_618 0.618 // Fibonacci 61.8% retracement level
//--- Pullback computation parameters
#define PB_SWING_BARS 20 // Bars to establish swing high/low anchor
#define PB_AUTOCORR_WIN 20 // Lag-1 autocorrelation rolling window
#define PB_H1_PROXY_BARS 60 // 60 M1 bars ≈ 1 H1 bar (proxy for H1 range)
#define PB_ALIGN_MIN 0.05 // Minimum |EMA5-EMA13|/ATR to assert a trend
//--- Composite score weights (must sum to 1.0)
#define PB_W_FIB 0.50 // Fibonacci quality weight
#define PB_W_H1 0.30 // H1 range context weight
#define PB_W_AUTOCORR 0.20 // Momentum autocorrelation weight
//+------------------------------------------------------------------+
//| PULLBACK_QUALITY: Fibonacci-mapped retracement quality label. |
//| Integers reflect ordinal depth: higher = deeper retracement. |
//+------------------------------------------------------------------+
enum PULLBACK_QUALITY
{
PBQ_NO_TREND = 0, // No trend signal — EMA alignment below threshold
PBQ_STRONG = 1, // Depth < 23.6% — price near extension, trend intact
PBQ_HEALTHY = 2, // Depth 23.6–38.2% — shallow retracement, valid entry
PBQ_WARNING = 3, // Depth 38.2–61.8% — retracement approaching midpoint
PBQ_DEEP = 4, // Depth > 61.8% — approaching trend origin
PBQ_BROKEN = 5, // Depth > 100% — price beyond swing origin
};
//+------------------------------------------------------------------+
//| PullbackAnalysis: pullback quality measurement result. |
//| Populated by PopulatePullbackAnalysis(). |
//| depth: Fibonacci retracement fraction [0,∞). |
//| 0.0 = price at full extension; 1.0 = price at swing origin. |
//| > 1.0 = structure broken. |
//| h1_position: price location in 60-bar rolling range [0,1]. |
//| composite_score: weighted entry quality [0,1] (higher = better). |
//| momentum_autocorr: lag-1 return autocorrelation [-1,+1]. |
//| Positive = momentum persistence; negative = mean-reversion. |
//| persistent_dir: dominant direction from MicroTrendAnalysis (+1, |
//| -1, or 0). |
//+------------------------------------------------------------------+
struct PullbackAnalysis
{
double depth; // Fibonacci retracement depth [0,∞)
PULLBACK_QUALITY quality; // PBQ label mapped from depth
double h1_position; // Price in 60-bar rolling range [0,1]
double composite_score; // Weighted entry quality [0,1]
double momentum_autocorr;// Lag-1 return autocorrelation [-1,+1]
int persistent_dir; // Trend direction: +1, -1, or 0
};
//+------------------------------------------------------------------+
//| GetPullbackDepth: Fibonacci retracement depth from swing high/ |
//| low anchor. |
//| |
//| Returns retracement fraction [0,∞) relative to the current bar: |
//| Uptrend: (swing_high - close) / (swing_high - swing_low) |
//| Downtrend: (close - swing_low) / (swing_high - swing_low) |
//| |
//| Trend direction determined by EMA5 vs EMA13 alignment, |
//| normalized by ATR. If alignment < PB_ALIGN_MIN, returns -1.0 |
//| (no-trend sentinel). |
//| |
//| ComputeATR() and ComputeEMAAt() (Part 8) require chronological |
//| arrays (index 0 = oldest bar). CopyHigh/CopyLow/SafeCopyClose |
//| return newest-first, so the working arrays are reversed before |
//| being passed to the Part 8 helpers. |
//| |
//| is_uptrend_out: set to true if EMA alignment is bullish. |
//+------------------------------------------------------------------+
double GetPullbackDepth(const string symbol, const int tf,
const int period, bool &is_uptrend_out)
{
is_uptrend_out = false;
if(!ValidateSymbolV2(symbol) || period < PB_SWING_BARS + 13 + 14)
return -1.0;
//--- Copy price arrays, newest-first (index 0 = current bar)
double high[], low[], close[];
ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true);
int copy_n = period;
if(CopyHigh(symbol, (ENUM_TIMEFRAMES)tf, 0, copy_n, high) < copy_n) return -1.0;
if(CopyLow (symbol, (ENUM_TIMEFRAMES)tf, 0, copy_n, low) < copy_n) return -1.0;
if(SafeCopyClose(symbol, tf, 0, copy_n, close) < copy_n) return -1.0;
//--- Build chronological arrays (index 0 = oldest) for ComputeATR/ComputeEMAAt
double hi_chron[], lo_chron[], cl_chron[];
ArrayResize(hi_chron, copy_n);
ArrayResize(lo_chron, copy_n);
ArrayResize(cl_chron, copy_n);
for(int i = 0; i < copy_n; i++)
{
hi_chron[i] = high [copy_n - 1 - i];
lo_chron[i] = low [copy_n - 1 - i];
cl_chron[i] = close[copy_n - 1 - i];
}
int last = copy_n - 1; // current bar's index in chronological order
//--- ATR at the current bar (Part 8 helper: hi[], lo[], cl[], n, period)
double cur_atr = ComputeATR(hi_chron, lo_chron, cl_chron, copy_n, 14);
if(cur_atr < DBL_EPSILON) return -1.0;
//--- EMA5 and EMA13 at the current bar (Part 8 helper: arr[], n, period, idx)
double ema_fast = ComputeEMAAt(cl_chron, copy_n, 5, last);
double ema_slow = ComputeEMAAt(cl_chron, copy_n, 13, last);
if(ema_fast <= 0.0 || ema_slow <= 0.0) return -1.0;
//--- Trend direction: normalized alignment
double align_norm = (ema_fast - ema_slow) / (cur_atr + DBL_EPSILON);
if(MathAbs(align_norm) < PB_ALIGN_MIN) return -1.0; // no trend sentinel
is_uptrend_out = (align_norm > 0.0);
//--- Swing high/low over PB_SWING_BARS bars ending at current bar
//--- (uses newest-first arrays — unaffected by the ordering fix above)
double sw_high = high[0];
double sw_low = low[0];
for(int i = 1; i < PB_SWING_BARS && i < copy_n; i++)
{
if(high[i] > sw_high) sw_high = high[i];
if(low[i] < sw_low ) sw_low = low[i];
}
double sw_range = sw_high - sw_low;
if(sw_range < DBL_EPSILON) return -1.0;
//--- Retracement depth
double depth;
if(is_uptrend_out)
depth = (sw_high - close[0]) / sw_range;
else
depth = (close[0] - sw_low) / sw_range;
return MathMax(0.0, depth); // negative depth (above swing high) floors at 0
}
//+------------------------------------------------------------------+
//| GetPullbackQuality: maps retracement depth to PULLBACK_QUALITY. |
//| depth < 0 (no-trend sentinel) → PBQ_NO_TREND. |
//+------------------------------------------------------------------+
PULLBACK_QUALITY GetPullbackQuality(double depth)
{
if(depth < 0.0) return PBQ_NO_TREND;
if(depth < PB_FIBO_236) return PBQ_STRONG;
if(depth < PB_FIBO_382) return PBQ_HEALTHY;
if(depth < PB_FIBO_618) return PBQ_WARNING;
if(depth <= 1.0) return PBQ_DEEP;
return PBQ_BROKEN;
}
//+------------------------------------------------------------------+
//| GetH1RangeContext: price position in 60-bar rolling range. |
//| |
//| Uses the 60 most recent M1 bars as a proxy for the H1 candle |
//| range. This avoids AddDataSeries() and multi-timeframe access. |
//| The approximation overstates H1 range when sub-ranges do not |
//| overlap cleanly across the hour boundary. See Limitations. |
//| |
//| Returns h1_position in [0,1]: |
//| 0.0 = close at rolling low (bearish context) |
//| 1.0 = close at rolling high (bullish context) |
//+------------------------------------------------------------------+
double GetH1RangeContext(const string symbol, const int tf)
{
if(!ValidateSymbolV2(symbol)) return 0.5;
double high[], low[], close[];
ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true);
int n = PB_H1_PROXY_BARS;
if(CopyHigh(symbol, (ENUM_TIMEFRAMES)tf, 0, n, high) < n) return 0.5;
if(CopyLow (symbol, (ENUM_TIMEFRAMES)tf, 0, n, low) < n) return 0.5;
if(SafeCopyClose(symbol, tf, 0, 1, close) < 1) return 0.5;
//--- Rolling maximum high and minimum low
double roll_high = high[0];
double roll_low = low[0];
for(int i = 1; i < n; i++)
{
if(high[i] > roll_high) roll_high = high[i];
if(low[i] < roll_low ) roll_low = low[i];
}
double roll_range = roll_high - roll_low;
if(roll_range < DBL_EPSILON) return 0.5;
return MathMax(0.0, MathMin(1.0, (close[0] - roll_low) / roll_range));
}
//+------------------------------------------------------------------+
//| GetMomentumAutocorrelation: lag-1 autocorrelation of M1 returns. |
//| |
//| Computes Pearson correlation between r[t] and r[t-1] over a |
//| PB_AUTOCORR_WIN bar rolling window. |
//| +1 = perfect momentum (consecutive same-direction moves) |
//| -1 = perfect mean-reversion (alternating direction) |
//| 0 = no serial correlation |
//| |
//| At M1 resolution, NQ returns are mildly mean-reverting |
//| (negative autocorrelation) due to bid-ask bounce and microstruc- |
//| ture noise. Positive autocorrelation identifies momentum windows.|
//+------------------------------------------------------------------+
double GetMomentumAutocorrelation(const string symbol, const int tf,
const int window)
{
if(!ValidateSymbolV2(symbol) || window < 4) return 0.0;
double close[];
ArraySetAsSeries(close, true);
int need = window + 1;
if(SafeCopyClose(symbol, tf, 0, need, close) < need) return 0.0;
//--- Build return array (index 0 = most recent)
double ret[];
ArrayResize(ret, window);
for(int i = 0; i < window; i++)
{
if(close[i+1] <= DBL_EPSILON) { ret[i] = 0.0; continue; }
ret[i] = (close[i] - close[i+1]) / close[i+1];
//--- Discard gross outliers (> 5% per bar — data error guard)
if(MathAbs(ret[i]) > 0.05) ret[i] = 0.0;
}
//--- Two-pass Pearson correlation of lag-1 pairs
int pairs = window - 1;
if(pairs < 3) return 0.0;
double mean1 = 0.0, mean2 = 0.0;
for(int i = 0; i < pairs; i++) { mean1 += ret[i]; mean2 += ret[i+1]; }
mean1 /= pairs; mean2 /= pairs;
double cov = 0.0, var1 = 0.0, var2 = 0.0;
for(int i = 0; i < pairs; i++)
{
double d1 = ret[i] - mean1;
double d2 = ret[i+1] - mean2;
cov += d1 * d2;
var1 += d1 * d1;
var2 += d2 * d2;
}
double denom = MathSqrt(var1 * var2);
if(denom < DBL_EPSILON) return 0.0;
return MathMax(-1.0, MathMin(1.0, cov / denom));
}
//+------------------------------------------------------------------+
//| GetPositiveAutocorrelation: momentum persistence component. |
//| Returns max(0, lag-1 autocorrelation) — clips mean-reversion to |
//| zero. Used as the autocorrelation input to the composite score |
//| because only positive (momentum) autocorrelation signals a |
//| favorable pullback entry environment. |
//+------------------------------------------------------------------+
double GetPositiveAutocorrelation(const string symbol, const int tf,
const int window)
{
return MathMax(0.0, GetMomentumAutocorrelation(symbol, tf, window));
}
//+------------------------------------------------------------------+
//| GetCompositePullbackScore: weighted entry quality [0,1]. |
//| |
//| composite = 0.50 * fib_quality |
//| + 0.30 * h1_position |
//| + 0.20 * momentum_autocorr_positive |
//| |
//| fib_quality = clip(1 - depth, 0, 1) for valid depth; |
//| = 0.0 for PBQ_NO_TREND or PBQ_BROKEN. |
//| |
//| Higher score indicates a structurally stronger entry setup: |
//| shallow retracement + price in favorable H1 position + |
//| momentum-persistent environment. |
//| |
//| Engineering heuristic. Weights are not derived from a regression.|
//| Recalibrate on your own instrument and strategy before use. |
//+------------------------------------------------------------------+
double GetCompositePullbackScore(double depth, double h1_position,
double momentum_autocorr_positive)
{
double fib_quality;
if(depth < 0.0 || depth > 1.0)
fib_quality = 0.0; // no-trend or broken structure
else
fib_quality = MathMax(0.0, MathMin(1.0, 1.0 - depth));
double score = PB_W_FIB * fib_quality
+ PB_W_H1 * h1_position
+ PB_W_AUTOCORR * momentum_autocorr_positive;
return MathMax(0.0, MathMin(1.0, score));
}
//+------------------------------------------------------------------+
//| PopulatePullbackAnalysis: single-call wrapper. |
//| Fills all fields of PullbackAnalysis for the current bar. |
//| Uses MicroTrendAnalysis.persistent_dir for directional context. |
//| |
//| period: number of bars available (must be >= PB_SWING_BARS + 27).|
//| mta: populated MicroTrendAnalysis from Part 8 (read only). |
//| |
//| NaN guard: sets composite_score = 0 and quality = PBQ_NO_TREND |
//| if any upstream input returns an invalid sentinel. |
//+------------------------------------------------------------------+
void PopulatePullbackAnalysis(const string symbol, const int tf,
const int period,
PullbackAnalysis &pba,
const MicroTrendAnalysis &mta)
{
//--- Initialize to safe defaults
pba.depth = -1.0;
pba.quality = PBQ_NO_TREND;
pba.h1_position = 0.5;
pba.composite_score = 0.0;
pba.momentum_autocorr = 0.0;
pba.persistent_dir = mta.persistent_dir;
//--- 1. Fibonacci retracement depth
bool is_up = false;
pba.depth = GetPullbackDepth(symbol, tf, period, is_up);
pba.quality = GetPullbackQuality(pba.depth);
//--- 2. H1 range context (60-bar rolling proxy)
pba.h1_position = GetH1RangeContext(symbol, tf);
//--- 3. Momentum autocorrelation
pba.momentum_autocorr = GetMomentumAutocorrelation(symbol, tf,
PB_AUTOCORR_WIN);
double ac_pos = MathMax(0.0, pba.momentum_autocorr);
//--- 4. Composite score
pba.composite_score = GetCompositePullbackScore(pba.depth,
pba.h1_position,
ac_pos);
//--- NaN guards
if(!MathIsValidNumber(pba.depth)) pba.depth = -1.0;
if(!MathIsValidNumber(pba.h1_position)) pba.h1_position = 0.5;
if(!MathIsValidNumber(pba.momentum_autocorr)) pba.momentum_autocorr = 0.0;
if(!MathIsValidNumber(pba.composite_score)) pba.composite_score = 0.0;
if(!MathIsValidNumber(pba.depth) || pba.depth < 0.0)
pba.quality = PBQ_NO_TREND;
}
#endif // MICROSTRUCTURE_FOUNDATION_V9_MQH
//+------------------------------------------------------------------+