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

double Erf(double x)

Computes the Gauss error function using Abramowitz & Stegun 7.1.26 approximation (Hastings polynomial).

The error function is defined as:

erf(x) = (2 / √π) · ∫₀ˣ e^(-t²) dt

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.

ParameterTypeDescription
xdoubleInput value (any real number)
→ Returnsdoubleerf(x) in range (−1, 1)

ErfInv — Inverse Error Function

double ErfInv(double x)

Computes the inverse error function, used to construct confidence intervals and convert probabilities to z-scores. Uses a piecewise rational approximation:

ParameterTypeDescription
xdoubleInput in range [−1, 1]
→ Returnsdoubleerf⁻¹(x) — will return ±1e10 for |x| ≥ 1 (leak indicator)

GaussPDF — Probability Density Function

double GaussPDF(double x, double mu, double sigma)

Computes the standard Gaussian PDF:

f(x) = (1 / (σ · √(2π))) · exp(−(x−μ)² / (2·σ²))

If sigma ≤ 0, returns 0.0 to prevent division-by-zero.

ParameterTypeDescription
xdoubleInput value
mudoubleMean of the distribution
sigmadoubleStandard deviation (must be > 0)
→ ReturnsdoubleProbability density at x

GaussCDF — Cumulative Distribution Function

double GaussCDF(double x, double mu, double sigma)

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.

ParameterTypeDescription
xdoubleQuantile
mudoubleMean
sigmadoubleStandard deviation
→ ReturnsdoubleP(X ≤ x) — probability in [0, 1]

GaussZScore — Z-Score Calculation

double GaussZScore(double x, double mu, double sigma)

Computes the z-score: z = (x − μ) / σ. A measure of how many standard deviations the observation x is from the mean.

ParameterTypeDescription
xdoubleObserved value
mudoublePopulation mean
sigmadoublePopulation standard deviation
→ Returnsdoublez-score (standardized deviation)

GaussEntropy — Differential Entropy

double GaussEntropy(double sigma)

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.

ParameterTypeDescription
sigmadoubleStandard deviation
→ ReturnsdoubleDifferential 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

bool CholeskyDecompFlat(const double &K[], double &L[], int n)

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.

Note: The matrix K is passed as a 1D array of length n×n. L is also 1D of length n×n, but only the lower triangle is populated. The upper triangle elements are left unchanged.
ParameterTypeDescription
Kdouble[]Input covariance matrix (n×n, row-major)
Ldouble[] (out)Output lower-triangular factor
nintMatrix dimension
→ Returnsbooltrue on success, false if matrix is not positive-definite

SolveCholeskyFlat

bool SolveCholeskyFlat(const double &L[], const double &b[], double &x[], int n)

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).

ParameterTypeDescription
Ldouble[]Lower-triangular Cholesky factor (n×n)
bdouble[]Right-hand side vector (length n)
xdouble[] (out)Solution vector (length n)
nintMatrix dimension
→ Returnsbooltrue on success

SolveForwardFlat — Forward Substitution

bool SolveForwardFlat(const double &L[], const double &b[], double &x[], int n)

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]

ParameterTypeDescription
Ldouble[]Lower triangular matrix (n×n)
bdouble[]Right-hand side (length n)
xdouble[] (out)Solution (length n)
nintMatrix dimension
→ Returnsbooltrue on success

SolveBackwardFlat — Backward Substitution

bool SolveBackwardFlat(const double &L[], const double &b[], double &x[], int n)

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]

col1col2Description
Ldouble[]Lower triangular matrix (n×n; reads L[j][i] = transpose access)
bdouble[]Right-hand side (length n)
xdouble[] (out)Solution (length n)
nintMatrix dimension
→ Returnsbooltrue on success

Data & Filtering

PriceBuffer

class 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.

MethodReturnsDescription
Update()voidFetch latest bar data from the chart (iClose, iHigh, iLow, iVolume)
Size()intNumber of bars currently stored
Close(i)doubleClose price at index i (0 = current bar)
High(i)doubleHigh price at index i
Low(i)doubleLow price at index i
Volume(i)doubleVolume at index i
Median(i)double(High(i) + Low(i)) / 2
Typical(i)double(High(i) + Low(i) + Close(i)) / 3

CalcATR / GetATR

bool CalcATR(double &atr[], int period)

Computes the Average True Range (ATR) for the given period using:

double GetATR(int period)

Convenience wrapper: allocates the array, calls CalcATR, returns the current ATR value (index 0).

GaussFilter

class GaussFilter

Static utility class for one-dimensional Gaussian filtering. Used by Strategy 1 (Filter Trend) and Strategy 5 (Volatility Bands).

GaussFilter::Kernel

static void Kernel(int length, double sigma, double &k[])

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.

ParameterTypeDescription
lengthintKernel size (should be odd for symmetry)
sigmadoubleStandard deviation of the Gaussian
kdouble[] (out)Output kernel array

GaussFilter::Filter

static void Filter(const double &src[], int kLen, double sigma, double &dst[])

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

static bool Convolve(const double &src[], const double &kernel[], double &dst[])

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

class GPR

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

bool Train(const double &x[], const double &y[], int n)

Trains the GP on n training points. The algorithm:

  1. Build covariance matrix K: K[i][j] = kernel(x[i], x[j]) + δᵢⱼ · noise² where noise = 0.01 · σ_y
  2. Cholesky decomposition: L = chol(K) — factorizes K into L·Lᵀ
  3. Compute α: Solve L·Lᵀ·α = y via forward/backward substitution
  4. Store L and α for efficient prediction
ParameterTypeDescription
xdouble[]Training inputs (indices 0..n−1)
ydouble[]Training targets (price values)
nintNumber of training points
→ Returnsbooltrue if Cholesky succeeded

GPR::Predict

bool Predict(double xStar, double &yMean, double &yStd)

Predicts at a test point x* using the stored GP posterior:

ParameterTypeDescription
xStardoubleTest input (typically lookback index)
yMeandouble& (out)Predicted mean
yStddouble& (out)Predicted standard deviation (uncertainty)
→ Returnsbooltrue if model is trained

GMM — Gaussian Mixture Model

class GMM

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

void Fit(const double &data[], int n)

Runs the EM algorithm for up to 100 iterations (or until convergence):

  1. E-Step: Compute responsibility γᵢₖ = πₖ · N(xᵢ | μₖ, σₖ²) / Σⱼ πⱼ · N(xᵢ | μⱼ, σⱼ²) for each component k and data point i
  2. M-Step: Update parameters — Nₖ = Σᵢ γᵢₖ, πₖ = Nₖ / n, μₖ = Σᵢ γᵢₖ·xᵢ / Nₖ, σₖ² = Σᵢ γᵢₖ·(xᵢ−μₖ)² / Nₖ
  3. 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).

ParameterTypeDescription
datadouble[]Training data (return series as %)
nintNumber of data points

GMM::Predict

int Predict(double x)

Assigns a data point to the most likely component (maximum posterior responsibility). Returns the component index (0 or 1).

GMM::GetHighVolRegime

int 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

double GetMu(int i), double GetSigma(int i), double GetWeight(int i)

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

class GNB

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

bool Fit(const double &f0[], const double &f1[], const double &f2[], const double &target[], int n)

Fits the model on n training samples. For each class (up/down):

GNB::PredictProbUp

double PredictProbUp(double f0, double f1, double f2)

Computes P(up | features) using Bayes' rule under the Naive assumption (conditional independence):

P(up|f) = P(up) · Πⱼ PDF(fⱼ | μ_upⱼ, σ_upⱼ) / evidence
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)

class IStrategy

Base class that all six strategies implement. In MQL5 this is an interface; in MQL4 it's an abstract class with pure virtual methods.

MethodDescription
Update(PriceBuffer &pbuf)Called once per tick to let the strategy update internal state
GetSignal() → SignalVoteReturns the current (signal, confidence) pair
Name() → stringReturns a human-readable strategy name for the panel display

Strategy 1 — Gaussian Filter Trend

class StratFilterTrend : public IStrategy

Applies two Gaussian convolutions with different kernel sizes (fast period, slow period). Compares the smoothed lines:

Strategy 2 — GPR Mean Reversion

class StratGPRMeanRev : public IStrategy

Trains a Gaussian Process on InpGPRLookback bars. Computes the z-score of current price vs the GP's predictive distribution:

Strategy 3 — GMM Regime Adaptive

class StratGMMRegime : public IStrategy

Fits a 2-component GMM on return series (updated every 10 bars). Dynamically switches behavior based on detected regime:

Strategy 4 — GNB Probability

class StratGNBProb : public IStrategy

Trains a Gaussian Naive Bayes classifier on three features:

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

class StratVolBands : public IStrategy

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:

Strategy 6 — Z-Score Channel

class StratZScore : public IStrategy

Calculates the rolling z-score of current price relative to the mean of the last period bars (default 20). Pure statistical mean reversion:

Ensemble Voting

class Ensemble

The core voting engine. Maintains an array of up to 6 strategy pointers and their associated weights.

Ensemble::AddStrategy

void AddStrategy(IStrategy* s, double w)

Registers a strategy with the given weight. Maximum 6 strategies (no-op beyond that).

Ensemble::Vote

TradeSignal Vote(PriceBuffer &pbuf)

Iterates all registered strategies, calls Update() then GetSignal(), and aggregates votes:

totalVote = Σ s.signal · s.confidence · s.weight (over all "active" strategies with confidence > 0.1)
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

FieldTypeDescription
signalENUM_SIGNAL−1 (Sell), 0 (Neutral), +1 (Buy)
totalVotedoubleRaw weighted vote sum before thresholding
numActiveintHow many strategies had a non-neutral signal
numBuyintCount of buy votes
numSellintCount of sell votes

SignalVote Struct

FieldTypeDescription
signalENUM_SIGNALStrategy's vote direction
confidencedoubleHow confident [0, 1]
weightdoubleGlobal weight assigned to this strategy

Risk Management

ATR-Based SL/TP

At order creation:

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

FieldTypeDescription
ticketintOrder ticket number
beDoneboolWhether breakeven has been applied
trailingActiveboolWhether trailing has been activated
peakPricedoubleBest price reached (for trailing calc)

ModifySL

void ModifySL(int ticket, double newSL)

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:

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

InputTypeDefaultDescription
InpMagicNumberint202406Unique EA identifier for order management
InpLotSizedouble0.1Fixed lot size per trade
InpATRPeriodint14ATR computation period
InpATRSLMultiplierdouble1.5SL = ATR × this multiplier
InpATRTPMultiplierdouble3.0TP = ATR × this multiplier
InpVoteThresholddouble1.8Minimum weighted vote to trigger a trade
InpMaxSpreadint30Max spread in points (entered as integer, multiplied by 10 internally)
InpTradeOnNewBarOnlybooltrueOnly evaluate on the first tick of a new bar
InpUseFilterTrendbooltrueEnable Strategy 1
InpUseGPRMeanRevbooltrueEnable Strategy 2
InpUseGMMRegimebooltrueEnable Strategy 3
InpUseGNBProbbooltrueEnable Strategy 4
InpUseVolBandsbooltrueEnable Strategy 5
InpUseZScorebooltrueEnable Strategy 6
InpWeightFilterdouble1.0Strategy 1 voting weight
InpWeightGPRdouble1.0Strategy 2 voting weight
InpWeightGMMdouble1.0Strategy 3 voting weight
InpWeightGNBdouble1.0Strategy 4 voting weight
InpWeightVoldouble1.0Strategy 5 voting weight
InpWeightZScoredouble1.0Strategy 6 voting weight
InpFilterFastPeriodint12Fast Gaussian kernel size (Strategy 1)
InpFilterSlowPeriodint26Slow Gaussian kernel size (Strategy 1)
InpGPRLookbackint30GP training window (Strategy 2)
InpGPRStdThreshdouble1.5GP std deviation threshold (Strategy 2)
InpGMMTrainBarsint100GMM training window (Strategy 3)
InpGNBTrainBarsint80GNB training window (Strategy 4)
InpGNBProbThreshdouble0.60GNB probability threshold (Strategy 4)
InpVolBandMultiplierdouble2.0Std multiplier for vol bands (Strategy 5)
InpZScoreEntrydouble2.0Z-score entry threshold (Strategy 6)
InpZScoreExitdouble0.3Z-score exit threshold (Strategy 6, reserved)
InpUseTrailingbooltrueEnable trailing stop
InpTrailActivatePctdouble50.0Trailing activates at % of TP distance
InpTrailStepPctdouble25.0Trailing step size as % of TP distance
InpUseBEbooltrueEnable breakeven
InpBEActivatePctdouble30.0BE activates at % of TP distance
InpShowPanelbooltrueShow info panel on chart

MQL4 vs MQL5 Differences

FeatureMQL5MQL4
Matrix typesNative matrix/vectorFlat 1D double[] (i·n+j indexing)
Interfacesinterface keywordAbstract class with pure virtual methods
Bar dataCopyClose()/CopyHigh() etc.iClose()/iHigh()/iLow()/iVolume()
Position modelPosition-centric (PositionGet*, PositionSelect)Order-centric (OrderSelect, OrderSend, OrderClose)
Order ticketsulongint
Object APIObjectCreate(0, ...), ObjectSetInteger()ObjectCreate(...), ObjectSet(), ObjectSetText()
Variable scopingBlock-scopedFunction-scoped (no for local scope)
Struct initAllows = {inputVar, ...}Compile-time constants only; uses Set() method pattern
Trade functionsPositionOpen/PositionModifyOrderSend/OrderModify/OrderClose
Market infoSymbolInfoDouble()/SymbolInfoInteger()MarketInfo()
Bars countBars()iBars()
↑ Back to top