API Documentation
Complete reference for every function, class, and strategy in FxMath GaussEnsemble. Both MQL5 and MQL4 versions share the same API — differences are noted inline.
Core Math
All Gaussian math is implemented from scratch — zero external dependencies. The approximations use Abramowitz & Stegun formulas for the error function and its inverse, which are accurate to ~1.5e-7 absolute error.
Erf — Error Function
Computes the Gauss error function using Abramowitz & Stegun 7.1.26 approximation (Hastings polynomial).
The error function is defined as:
The implementation uses a rational approximation with 5 coefficients. The sign is preserved, so the function works correctly for negative x. The maximum absolute error is ~1.5e-7 across the entire domain.
| Parameter | Type | Description |
|---|---|---|
| x | double | Input value (any real number) |
| → Returns | double | erf(x) in range (−1, 1) |
ErfInv — Inverse Error Function
Computes the inverse error function, used to construct confidence intervals and convert probabilities to z-scores. Uses a piecewise rational approximation:
- For x near 0 (p < 5): uses a 19-coefficient rational polynomial in transformed variable p = 2·x − 2
- For x near 1 (p ≥ 5): uses a 20-coefficient rational polynomial in transformed variable p = sqrt(p − 5)
| Parameter | Type | Description |
|---|---|---|
| x | double | Input in range [−1, 1] |
| → Returns | double | erf⁻¹(x) — will return ±1e10 for |x| ≥ 1 (leak indicator) |
GaussPDF — Probability Density Function
Computes the standard Gaussian PDF:
If sigma ≤ 0, returns 0.0 to prevent division-by-zero.
| Parameter | Type | Description |
|---|---|---|
| x | double | Input value |
| mu | double | Mean of the distribution |
| sigma | double | Standard deviation (must be > 0) |
| → Returns | double | Probability density at x |
GaussCDF — Cumulative Distribution Function
Computes the Gaussian CDF using the relationship CDF(x) = 0.5 · (1 + erf((x−μ) / (σ·√2))). The result is the probability that a random sample from N(μ, σ²) is ≤ x.
| Parameter | Type | Description |
|---|---|---|
| x | double | Quantile |
| mu | double | Mean |
| sigma | double | Standard deviation |
| → Returns | double | P(X ≤ x) — probability in [0, 1] |
GaussZScore — Z-Score Calculation
Computes the z-score: z = (x − μ) / σ. A measure of how many standard deviations the observation x is from the mean.
| Parameter | Type | Description |
|---|---|---|
| x | double | Observed value |
| mu | double | Population mean |
| sigma | double | Population standard deviation |
| → Returns | double | z-score (standardized deviation) |
GaussEntropy — Differential Entropy
Computes the differential entropy of a univariate Gaussian: H = 0.5 · ln(2π·e·σ²). Used internally by GMM for regime detection — higher entropy implies higher uncertainty / volatility.
| Parameter | Type | Description |
|---|---|---|
| sigma | double | Standard deviation |
| → Returns | double | Differential entropy in nats |
Linear Algebra
Matrix operations use flat 1D arrays stored in row-major order: element A[i][j] is at index i·n+j. The Cholesky decomposition is the workhorse for GPR training. MQL5 uses native matrix/vector types; MQL4 uses the flat array pattern.
CholeskyDecompFlat
Computes the Cholesky decomposition of a symmetric positive-definite matrix K: K = L · Lᵀ, where L is lower triangular. Uses the standard Cholesky-Crout algorithm with O(n³/3) operations.
| Parameter | Type | Description |
|---|---|---|
| K | double[] | Input covariance matrix (n×n, row-major) |
| L | double[] (out) | Output lower-triangular factor |
| n | int | Matrix dimension |
| → Returns | bool | true on success, false if matrix is not positive-definite |
SolveCholeskyFlat
Solves the linear system L·Lᵀ·x = b for x, given the Cholesky factor L. Uses forward substitution (L·y = b) followed by backward substitution (Lᵀ·x = y).
| Parameter | Type | Description |
|---|---|---|
| L | double[] | Lower-triangular Cholesky factor (n×n) |
| b | double[] | Right-hand side vector (length n) |
| x | double[] (out) | Solution vector (length n) |
| n | int | Matrix dimension |
| → Returns | bool | true on success |
SolveForwardFlat — Forward Substitution
Solves L·x = b where L is lower triangular. For i = 0..n−1: x[i] = (b[i] − Σⱼ₌₀ⁱ⁻¹ L[i][j]·x[j]) / L[i][i]
| Parameter | Type | Description |
|---|---|---|
| L | double[] | Lower triangular matrix (n×n) |
| b | double[] | Right-hand side (length n) |
| x | double[] (out) | Solution (length n) |
| n | int | Matrix dimension |
| → Returns | bool | true on success |
SolveBackwardFlat — Backward Substitution
Solves Lᵀ·x = b where L is lower triangular. For i = n−1..0: x[i] = (b[i] − Σⱼ₌ᵢ₊₁ⁿ⁻¹ L[j][i]·x[j]) / L[i][i]
| col1 | col2 | Description |
|---|---|---|
| L | double[] | Lower triangular matrix (n×n; reads L[j][i] = transpose access) |
| b | double[] | Right-hand side (length n) |
| x | double[] (out) | Solution (length n) |
| n | int | Matrix dimension |
| → Returns | bool | true on success |
Data & Filtering
PriceBuffer
Thread-safe OHLCV ring buffer that stores the most recent maxBars (default 200) bars. Updated on every tick from OnTick(). Provides indexed access to price components and common derived values.
| Method | Returns | Description |
|---|---|---|
| Update() | void | Fetch latest bar data from the chart (iClose, iHigh, iLow, iVolume) |
| Size() | int | Number of bars currently stored |
| Close(i) | double | Close price at index i (0 = current bar) |
| High(i) | double | High price at index i |
| Low(i) | double | Low price at index i |
| Volume(i) | double | Volume at index i |
| Median(i) | double | (High(i) + Low(i)) / 2 |
| Typical(i) | double | (High(i) + Low(i) + Close(i)) / 3 |
CalcATR / GetATR
Computes the Average True Range (ATR) for the given period using:
- TR = max(High − Low, |High − Closeₚᵣₑᵥ|, |Low − Closeₚᵣₑᵥ|)
- ATR is computed via a modified Wilder's smoothing with EMA
Convenience wrapper: allocates the array, calls CalcATR, returns the current ATR value (index 0).
GaussFilter
Static utility class for one-dimensional Gaussian filtering. Used by Strategy 1 (Filter Trend) and Strategy 5 (Volatility Bands).
GaussFilter::Kernel
Generates a 1D Gaussian kernel: k[i] = exp(−x² / (2·σ²)) where x = i − length/2. The kernel is normalized so its elements sum to 1.
| Parameter | Type | Description |
|---|---|---|
| length | int | Kernel size (should be odd for symmetry) |
| sigma | double | Standard deviation of the Gaussian |
| k | double[] (out) | Output kernel array |
GaussFilter::Filter
Combines Kernel + Convolve in one call: generates a Gaussian kernel of length kLen with the given sigma, then convolves it with src, producing the smoothed output in dst.
GaussFilter::Convolve
Performs discrete 1D convolution with boundary clamping. For each output position i, the weighted average of valid kernel-overlapping src samples is computed. Edge positions automatically use fewer kernel taps (weight renormalized).
Machine Learning Models
GPR — Gaussian Process Regression
Implements Gaussian Process Regression for time-series prediction. Uses a squared-exponential (RBF) kernel: K(xᵢ, xⱼ) = σ² · exp(−(xᵢ−xⱼ)² / (2·ℓ²)). The implementation follows the standard GPR formulation (Rasmussen & Williams).
GPR::Train
Trains the GP on n training points. The algorithm:
- Build covariance matrix K: K[i][j] = kernel(x[i], x[j]) + δᵢⱼ · noise² where noise = 0.01 · σ_y
- Cholesky decomposition: L = chol(K) — factorizes K into L·Lᵀ
- Compute α: Solve L·Lᵀ·α = y via forward/backward substitution
- Store L and α for efficient prediction
| Parameter | Type | Description |
|---|---|---|
| x | double[] | Training inputs (indices 0..n−1) |
| y | double[] | Training targets (price values) |
| n | int | Number of training points |
| → Returns | bool | true if Cholesky succeeded |
GPR::Predict
Predicts at a test point x* using the stored GP posterior:
- Mean: k(x*)ᵀ · α — where k(x*) is the kernel vector between x* and all training points
- Variance: k(x*, x*) − k(x*)ᵀ · (Lᵀ \ (L \ k(x*))) — the posterior uncertainty
| Parameter | Type | Description |
|---|---|---|
| xStar | double | Test input (typically lookback index) |
| yMean | double& (out) | Predicted mean |
| yStd | double& (out) | Predicted standard deviation (uncertainty) |
| → Returns | bool | true if model is trained |
GMM — Gaussian Mixture Model
Fits a 2-component univariate Gaussian Mixture Model using Expectation-Maximization (EM). Designed to detect high-volatility vs low-volatility regimes in return series.
GMM::Fit
Runs the EM algorithm for up to 100 iterations (or until convergence):
- E-Step: Compute responsibility γᵢₖ = πₖ · N(xᵢ | μₖ, σₖ²) / Σⱼ πⱼ · N(xᵢ | μⱼ, σⱼ²) for each component k and data point i
- M-Step: Update parameters — Nₖ = Σᵢ γᵢₖ, πₖ = Nₖ / n, μₖ = Σᵢ γᵢₖ·xᵢ / Nₖ, σₖ² = Σᵢ γᵢₖ·(xᵢ−μₖ)² / Nₖ
- Check: if max parameter change < 1e-6, stop early
Initialization: k-means with 2 iterations. Component 0 is initialized with the lower-variance cluster (sorted by sigma after fitting).
| Parameter | Type | Description |
|---|---|---|
| data | double[] | Training data (return series as %) |
| n | int | Number of data points |
GMM::Predict
Assigns a data point to the most likely component (maximum posterior responsibility). Returns the component index (0 or 1).
GMM::GetHighVolRegime
Returns the component index with the higher standard deviation — i.e., the high-volatility regime. The model internally sorts components so that component 1 is always the high-vol regime after fitting.
GMM::Accessors
Retrieve the fitted parameters. Returns safe defaults (0.0, 1.0, 0.0 respectively) if the model hasn't been fitted or the index is out of range.
GNB — Gaussian Naive Bayes
Implements a binary Gaussian Naive Bayes classifier using three features: return, log-volume-ratio, and high-low spread. Used to predict whether the next bar closes up vs down.
GNB::Fit
Fits the model on n training samples. For each class (up/down):
- Prior: P(up) = n_up / n, P(down) = n_down / n
- For each feature j: μⱼ = mean of feature in class, σⱼ = std of feature in class (clamped to a minimum of 1.0 to prevent zero-variance)
- Requires at least 3 samples per class
GNB::PredictProbUp
Computes P(up | features) using Bayes' rule under the Naive assumption (conditional independence):
evidence = P(up)·Πⱼ PDF(fⱼ|μ_up) + P(down)·Πⱼ PDF(fⱼ|μ_down)
Returns 0.5 if the model hasn't been fitted.
Strategies
IStrategy Interface (Abstract Class)
Base class that all six strategies implement. In MQL5 this is an interface; in MQL4 it's an abstract class with pure virtual methods.
| Method | Description |
|---|---|
| Update(PriceBuffer &pbuf) | Called once per tick to let the strategy update internal state |
| GetSignal() → SignalVote | Returns the current (signal, confidence) pair |
| Name() → string | Returns a human-readable strategy name for the panel display |
Strategy 1 — Gaussian Filter Trend
Applies two Gaussian convolutions with different kernel sizes (fast period, slow period). Compares the smoothed lines:
- Bullish crossover: fast just crossed above slow → Buy (confidence 0.8)
- Bearish crossover: fast just crossed below slow → Sell (confidence 0.8)
- Level bias: fast above slow = Buy (0.3), fast below slow = Sell (0.3)
- All signals are weighted by
InpWeightFilter
Strategy 2 — GPR Mean Reversion
Trains a Gaussian Process on InpGPRLookback bars. Computes the z-score of current price vs the GP's predictive distribution:
- If z >
InpGPRStdThresh→ Sell (price is unusually high, expect reversion) - If z < −
InpGPRStdThresh→ Buy (price is unusually low) - Confidence scales as min(|z| / 5.0, 1.0)
- The GP is retrained every tick (stored as α and L for O(n) prediction)
Strategy 3 — GMM Regime Adaptive
Fits a 2-component GMM on return series (updated every 10 bars). Dynamically switches behavior based on detected regime:
- High-vol regime: looks for momentum continuation (returns beyond 0.5·σ_HV)
- Low-vol regime: looks for mean reversion (returns beyond 0.3·σ_HV)
- The high-vol component's sigma is used as the reference scale in both modes
- Signal confidence is fixed at 0.5 − 0.6 to keep the strategy as a moderate contributor
Strategy 4 — GNB Probability
Trains a Gaussian Naive Bayes classifier on three features:
- f0: return = (Close[i] − Close[i+1]) / Close[i+1]
- f1: log-volume-ratio = log(Volume[i] / Volume[i+1])
- f2: high-low spread = (High[i] − Low[i]) / Close[i]
If P(up) > InpGNBProbThresh → Buy. If P(up) < 1 − InpGNBProbThresh → Sell. Confidence = |P(up) − 0.5| × 2 (maps [0.5, 1.0] → [0, 1.0]).
Strategy 5 — Volatility Bands
Computes a Gaussian-weighted rolling mean and standard deviation over the last 30 bars. The kernel (length 15, σ=4.0) gives higher weight to recent prices. If current price is beyond InpVolBandMultiplier × σ from the mean, the market is considered overextended:
- Price above upper band → Sell
- Price below lower band → Buy
- Confidence = min((z − multiplier) / 3.0, 1.0) — scales with distance from the band edge
Strategy 6 — Z-Score Channel
Calculates the rolling z-score of current price relative to the mean of the last period bars (default 20). Pure statistical mean reversion:
- If z >
InpZScoreEntry→ Sell (overbought, fade) - If z < −
InpZScoreEntry→ Buy (oversold, fade) - The exit threshold
InpZScoreExitis reserved for future position-exit logic - Confidence = min(|z| / 5.0, 1.0)
Ensemble Voting
The core voting engine. Maintains an array of up to 6 strategy pointers and their associated weights.
Ensemble::AddStrategy
Registers a strategy with the given weight. Maximum 6 strategies (no-op beyond that).
Ensemble::Vote
Iterates all registered strategies, calls Update() then GetSignal(), and aggregates votes:
normalised = totalVote / Σ(weight of active strategies)
final = normalised × number_of_active_strategies
if final ≥ +InpVoteThreshold → SIG_BUY
if final ≤ −InpVoteThreshold → SIG_SELL
else → SIG_NONE
The normalization ensures that having more strategies agree amplifies the signal, while a single dissenting strategy has limited impact.
TradeSignal Struct
| Field | Type | Description |
|---|---|---|
| signal | ENUM_SIGNAL | −1 (Sell), 0 (Neutral), +1 (Buy) |
| totalVote | double | Raw weighted vote sum before thresholding |
| numActive | int | How many strategies had a non-neutral signal |
| numBuy | int | Count of buy votes |
| numSell | int | Count of sell votes |
SignalVote Struct
| Field | Type | Description |
|---|---|---|
| signal | ENUM_SIGNAL | Strategy's vote direction |
| confidence | double | How confident [0, 1] |
| weight | double | Global weight assigned to this strategy |
Risk Management
ATR-Based SL/TP
At order creation:
- SL = entry_price − sign × InpATRSLMultiplier × ATR(14)
- TP = entry_price + sign × InpATRTPMultiplier × ATR(14)
- Where sign = +1 for Buy, −1 for Sell
Because ATR adapts to volatility, SL/TP automatically widen in high-volatility markets and tighten in calm markets.
Breakeven
Once price reaches InpBEActivatePct% of the TP distance, SL is moved to entry price + buffer (0.1 × ATR). Fires only once per position (tracked via the TrackedPos array).
Trailing Stop
Once price reaches InpTrailActivatePct% of TP distance, the EA tracks the peak price. When price retraces by InpTrailStepPct% of the TP distance from the peak, SL is tightened to the new level. Continues until exit or stop-out.
TrackedPos Structure
| Field | Type | Description |
|---|---|---|
| ticket | int | Order ticket number |
| beDone | bool | Whether breakeven has been applied |
| trailingActive | bool | Whether trailing has been activated |
| peakPrice | double | Best price reached (for trailing calc) |
ModifySL
Helper that selects an order by ticket, verifies it belongs to this EA (magic number + symbol check), then calls OrderModify (MQL4) / PositionModify (MQL5) with the new SL. The return value is checked and errors are logged.
Chart Panel
When InpShowPanel = true, an info panel draws on the chart using OBJ_LABEL and OBJ_RECTANGLE_LABEL. The panel displays:
- EA name and version
- Current ensemble signal, vote sum, and breakdown (buy/sell counts)
- ATR(14) value in price terms
- Current bid price and spread
- Position info (if open): type, profit, entry, pips, SL, TP, trailing/BE status
Labels use the "Consolas" monospace font with color-coded signal (green = Buy, red = Sell, gray = Neutral). Extra labels from previous frames are cleaned up each tick.
Input Parameters
| Input | Type | Default | Description |
|---|---|---|---|
| InpMagicNumber | int | 202406 | Unique EA identifier for order management |
| InpLotSize | double | 0.1 | Fixed lot size per trade |
| InpATRPeriod | int | 14 | ATR computation period |
| InpATRSLMultiplier | double | 1.5 | SL = ATR × this multiplier |
| InpATRTPMultiplier | double | 3.0 | TP = ATR × this multiplier |
| InpVoteThreshold | double | 1.8 | Minimum weighted vote to trigger a trade |
| InpMaxSpread | int | 30 | Max spread in points (entered as integer, multiplied by 10 internally) |
| InpTradeOnNewBarOnly | bool | true | Only evaluate on the first tick of a new bar |
| InpUseFilterTrend | bool | true | Enable Strategy 1 |
| InpUseGPRMeanRev | bool | true | Enable Strategy 2 |
| InpUseGMMRegime | bool | true | Enable Strategy 3 |
| InpUseGNBProb | bool | true | Enable Strategy 4 |
| InpUseVolBands | bool | true | Enable Strategy 5 |
| InpUseZScore | bool | true | Enable Strategy 6 |
| InpWeightFilter | double | 1.0 | Strategy 1 voting weight |
| InpWeightGPR | double | 1.0 | Strategy 2 voting weight |
| InpWeightGMM | double | 1.0 | Strategy 3 voting weight |
| InpWeightGNB | double | 1.0 | Strategy 4 voting weight |
| InpWeightVol | double | 1.0 | Strategy 5 voting weight |
| InpWeightZScore | double | 1.0 | Strategy 6 voting weight |
| InpFilterFastPeriod | int | 12 | Fast Gaussian kernel size (Strategy 1) |
| InpFilterSlowPeriod | int | 26 | Slow Gaussian kernel size (Strategy 1) |
| InpGPRLookback | int | 30 | GP training window (Strategy 2) |
| InpGPRStdThresh | double | 1.5 | GP std deviation threshold (Strategy 2) |
| InpGMMTrainBars | int | 100 | GMM training window (Strategy 3) |
| InpGNBTrainBars | int | 80 | GNB training window (Strategy 4) |
| InpGNBProbThresh | double | 0.60 | GNB probability threshold (Strategy 4) |
| InpVolBandMultiplier | double | 2.0 | Std multiplier for vol bands (Strategy 5) |
| InpZScoreEntry | double | 2.0 | Z-score entry threshold (Strategy 6) |
| InpZScoreExit | double | 0.3 | Z-score exit threshold (Strategy 6, reserved) |
| InpUseTrailing | bool | true | Enable trailing stop |
| InpTrailActivatePct | double | 50.0 | Trailing activates at % of TP distance |
| InpTrailStepPct | double | 25.0 | Trailing step size as % of TP distance |
| InpUseBE | bool | true | Enable breakeven |
| InpBEActivatePct | double | 30.0 | BE activates at % of TP distance |
| InpShowPanel | bool | true | Show info panel on chart |
MQL4 vs MQL5 Differences
| Feature | MQL5 | MQL4 |
|---|---|---|
| Matrix types | Native matrix/vector | Flat 1D double[] (i·n+j indexing) |
| Interfaces | interface keyword | Abstract class with pure virtual methods |
| Bar data | CopyClose()/CopyHigh() etc. | iClose()/iHigh()/iLow()/iVolume() |
| Position model | Position-centric (PositionGet*, PositionSelect) | Order-centric (OrderSelect, OrderSend, OrderClose) |
| Order tickets | ulong | int |
| Object API | ObjectCreate(0, ...), ObjectSetInteger() | ObjectCreate(...), ObjectSet(), ObjectSetText() |
| Variable scoping | Block-scoped | Function-scoped (no for local scope) |
| Struct init | Allows = {inputVar, ...} | Compile-time constants only; uses Set() method pattern |
| Trade functions | PositionOpen/PositionModify | OrderSend/OrderModify/OrderClose |
| Market info | SymbolInfoDouble()/SymbolInfoInteger() | MarketInfo() |
| Bars count | Bars() | iBars() |