Nexus Quant Matrix
- Libraries
-
Syarief Azman Bin Rosli
Hello and welcome to my official MQL5 profile!
I am Syarief Azman Bin Rosli, an algorithmic trading systems developer and quantitative software engineer with over a decade of specialized experience creating robust automated trading solutions for MetaTrader 5 and MetaTrader 4. - Version: 1.0
- Activations: 5
Nexus Quant Matrix is a high-performance quantitative library built natively in MQL5. It delivers institutional-grade Kalman filtering, Cornish-Fisher VaR, Expected Shortfall (CVaR), Kelly Criterion sizing, margin-protected lot calculation, and Pearson correlation directly into your Expert Advisors — zero DLLs, zero external dependencies.
Distributed as a compiled binary (Nexus_Quant_Matrix.ex5). This description is your complete API reference.
Installation
- Download Nexus_Quant_Matrix.ex5 from MQL5 Market.
- Place it in: MQL5/Libraries/
- Add the #import block below into your .mq5 source file.
- Compile your EA or Indicator. All 6 functions are now available.
Import Declaration (Copy-Paste Ready)
#import "Nexus_Quant_Matrix.ex5" double NQM_KalmanFilter(double measurement, double q_process, double r_measure, double ¤t_state, double ¤t_covariance, double &kalman_gain); double NQM_CornishFisherVaR(double confidence_level, double mean_return, double std_dev_return, double skewness, double excess_kurtosis); double NQM_ExpectedShortfall(double confidence_level, double mean_return, double std_dev_return); double NQM_KellyFraction(double win_rate, double payoff_ratio, int kelly_mode, double max_fraction_cap); double NQM_CalculateLotSize(string symbol, double risk_percent, double stop_loss_points, double max_margin_utilization); double NQM_PearsonCorrelation(const double &series_x[], const double &series_y[], int length); #import
API Reference
NQM_KalmanFilter
Single-step 1D discrete Kalman filter. Filters market noise from raw price data without fixed lag.
Parameters:
- measurement: Raw price observation (Bid, Ask, or Close).
- q_process: Process noise covariance. Controls adaptation speed. Default: 0.001. Auto-corrected if zero or negative.
- r_measure: Measurement noise covariance. Controls smoothing strength. Default: 0.05. Auto-corrected if zero or negative.
- current_state (by ref): Previous filtered estimate. Updated in-place. Initialize to first price on first call.
- current_covariance (by ref): Previous error covariance. Updated in-place. Initialize to 1.0.
- kalman_gain (by ref): Output Kalman gain (0.0 to 1.0). Higher values mean more trust in measurement.
Returns: New filtered price estimate. Division-by-zero guarded internally.
NQM_CornishFisherVaR
Modified Value-at-Risk using Cornish-Fisher expansion. Adjusts for skewness (crash risk) and excess kurtosis (fat tails) that standard Gaussian VaR ignores.
Parameters:
- confidence_level: 0.90, 0.95, 0.99, or above 0.99 (99.5%). Other values default to 0.95.
- mean_return: Expected mean return. Use 0.0 for zero-drift assumption.
- std_dev_return: Return volatility. Returns 0.0 if near-zero.
- skewness: Fisher-Pearson skewness. Negative values increase VaR (left-tail risk).
- excess_kurtosis: Kurtosis minus 3. Positive values increase VaR (heavy tails).
Returns: Non-negative VaR loss value. Returns 0.0 if volatility is zero.
NQM_ExpectedShortfall
Parametric Expected Shortfall (Conditional VaR / CVaR). Average loss in worst-case tail scenarios — more conservative than VaR, required by Basel III.
Parameters:
- confidence_level: Values >= 0.99 use 99% tail, <= 0.90 use 90% tail, others default to 95%.
- mean_return: Expected mean return.
- std_dev_return: Return volatility. Returns 0.0 if near-zero.
Returns: Average tail loss as positive value. Returns 0.0 if volatility is zero.
NQM_KellyFraction
Optimal capital allocation using the Kelly Criterion. Maximizes long-term geometric growth while controlling ruin probability.
Parameters:
- win_rate: Historical win rate (0.0 to 1.0). Example: 0.55 = 55%. Clamped to 0.99 if >= 1.0. Returns 0.0 if <= 0.
- payoff_ratio: Average win / average loss ratio. Example: 1.5. Returns 0.0 if <= 0.
- kelly_mode: 0 = Full Kelly (1.0x), 1 = Half Kelly (0.5x, recommended), 2 = Quarter Kelly (0.25x). Other values default to Half.
- max_fraction_cap: Hard cap on fraction. Example: 0.25 = never risk more than 25%.
Returns: Optimal risk fraction (0.0 to max_fraction_cap). Returns 0.0 if strategy has negative expectancy.
NQM_CalculateLotSize
Risk-based lot calculator with broker spec compliance and Article 2555 margin safety. Reads symbol properties, normalizes to broker lot steps, and verifies margin via OrderCalcMargin before returning.
Parameters:
- symbol: Trading symbol (e.g. Symbol() or "EURUSD").
- risk_percent: Percentage of balance to risk. Example: 1.0 = 1%.
- stop_loss_points: Stop loss distance in points (not pips). Example: 300 = 30 pips on 5-digit broker.
- max_margin_utilization: Max percentage of free margin for required margin. Example: 30.0 = 30%.
Returns: Normalized lot volume for OrderSend. Returns 0.0 if capital insufficient or margin exceeds limit. Rounded down to broker lot step. Clamped to SYMBOL_VOLUME_MIN / MAX.
NQM_PearsonCorrelation
Sample Pearson correlation coefficient between two time-series arrays. Measures linear relationship strength.
Parameters:
- series_x[]: Primary data array (e.g. close prices of instrument A).
- series_y[]: Benchmark data array (e.g. close prices of instrument B).
- length: Number of data points from index 0. Minimum 3 required. Must not exceed array sizes.
Returns: Correlation coefficient (-1.0 to 1.0). Returns 0.0 if length < 3, arrays too short, or either series has zero variance. Clamped to [-1.0, 1.0].
Working Integration Example
#property copyright "Your Name" #property version "1.00" #import "Nexus_Quant_Matrix.ex5" double NQM_KalmanFilter(double measurement, double q_process, double r_measure, double ¤t_state, double ¤t_covariance, double &kalman_gain); double NQM_CornishFisherVaR(double confidence_level, double mean_return, double std_dev_return, double skewness, double excess_kurtosis); double NQM_ExpectedShortfall(double confidence_level, double mean_return, double std_dev_return); double NQM_KellyFraction(double win_rate, double payoff_ratio, int kelly_mode, double max_fraction_cap); double NQM_CalculateLotSize(string symbol, double risk_percent, double stop_loss_points, double max_margin_utilization); double NQM_PearsonCorrelation(const double &series_x[], const double &series_y[], int length); #import double g_state, g_cov, g_gain; int OnInit() { g_state = iClose(_Symbol, PERIOD_M1, 1); g_cov = 1.0; g_gain = 0.0; return INIT_SUCCEEDED; } void OnTick() { double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); double filtered = NQM_KalmanFilter(bid, 0.001, 0.05, g_state, g_cov, g_gain); Print("Kalman: ", filtered, " Gain: ", g_gain); double var99 = NQM_CornishFisherVaR(0.99, 0.0, 0.015, -0.5, 2.0); Print("99% CF-VaR: ", var99); double es95 = NQM_ExpectedShortfall(0.95, 0.0, 0.012); Print("95% CVaR: ", es95); double kelly = NQM_KellyFraction(0.55, 1.5, 1, 0.25); Print("Half Kelly: ", kelly); double lots = NQM_CalculateLotSize(_Symbol, 1.0, 300.0, 30.0); Print("Lot Size: ", lots); }
Architecture
All 6 functions are stateless and independent. The Kalman filter uses pass-by-reference state variables you manage externally, so multiple filters can run simultaneously with separate state sets. All functions perform pure math with no side effects — no chart objects, no timers, no trade execution, no network access. Exception: NQM_CalculateLotSize reads account/symbol properties for margin checks.
Compatibility
- Platform: MetaTrader 5 only
- Strategy Tester: Fully compatible (backtesting and optimization)
- MQL5 Cloud Network: Fully compatible (zero DLLs)
- External Dependencies: None
- Minimum Data Points: NQM_PearsonCorrelation requires at least 3 data points
- No chart objects, no timers, no visual output — pure computation engine
