MQL5MQL4Zero Dependencies6 Strategies

Gaussian Ensemble
Trading Engine

A multi-strategy Expert Advisor built from scratch in pure MQL5/MQL4. Six Gaussian-based strategies vote on every tick — the ensemble decides when to trade.

ENS Filter Trend GPR MeanRev GMM Regime GNB Prob Vol Bands Z-Score TRADE SIGNAL

Architecture

Every tick flows through the price buffer, into six parallel strategies, then into the ensemble voter that produces the final trade decision.

Price Buffer Close / High / Low / Vol Ring buffer ~2000 bars ① Filter Trend ② GPR MeanRev ③ GMM Regime ④ GNB Prob ⑤ Vol Bands ⑥ Z-Score Ensemble Voter Σ signal × confidence × weight Normalise → threshold → signal Min active: 1 | Threshold: 1.8 Risk Manager ATR SL = 1.5 × ATR(14) ATR TP = 3.0 × ATR(14) Trailing · Breakeven TRADE OrderSend / Close next tick → repeat

Data flows left-to-right: raw prices → parallel strategies → ensemble vote → risk-managed trade execution

Six Strategies

Each strategy is a self-contained Gaussian method that votes Buy, Sell, or Neutral with a confidence level. The ensemble weights and aggregates them. Click each strategy to expand its full explanation and visualisation.

1

Gaussian Filter Trend

Gaussian Convolution
Trend Following

Applies two Gaussian kernels with different width (fast σ=3, slow σ=6) to the price series. The convolution produces smoothed lines — the fast line reacts quickly, the slow line lags behind.

Crossover logic: When the fast line crosses above the slow, the trend is up (Buy, confidence 0.8). When it crosses below, the trend is down (Sell, 0.8). The relative position also produces a lower-confidence bias signal (0.3) when no crossover has occurred.

Why Gaussian? Unlike simple moving averages, Gaussian convolution gives more weight to the centre bar and smoothly tapers to the edges — producing a cleaner, phase-preserving smooth that doesn't overshoot on sharp moves.

slow fast CROSSOVER → SIGNAL
2

GPR Mean Reversion

Gaussian Process Regression
Mean Reversion

Trains a Gaussian Process on the last InpGPRLookback (default 30) price bars using an RBF (squared-exponential) kernel. The GP produces both a mean prediction and a predictive variance (uncertainty band) for the next bar.

Mean-reversion logic: If the current price is more than InpGPRStdThresh (default 1.5) standard deviations away from the GP mean, the market is considered overextended. A buy signal fires when price is unusually low (below −σ), a sell when unusually high (above +σ).

Implementation: The GP is trained via Cholesky decomposition (O(n³) upfront, O(n²) per prediction). The prediction at x* is: μ = k(x*)ᵀ · α, where α = (K + σ²I)⁻¹ · y. The confidence band shrinks near training points and widens in extrapolation regions.

GP mean Price below −σ → BUY
3

GMM Regime Adaptive

Gaussian Mixture Model · Expectation-Maximisation
Adaptive

Fits a 2-component univariate GMM on daily return percentages using the Expectation-Maximisation (EM) algorithm. One component captures the low-volatility regime, the other the high-volatility regime.

Adaptive logic: In the high-vol regime, the strategy looks for momentum continuation — if the latest return exceeds 0.5·σ_HV in the direction of the move, it trades with the trend. In the low-vol regime, it switches to mean reversion — returns beyond 0.3·σ_HV from zero are faded.

EM algorithm: E-step computes responsibility γᵢₖ (probability each point belongs to each component). M-step re-estimates π, μ, σ for each component. Converges in ~10–20 iterations. Components are sorted so component 1 is always the high-vol regime.

Low vol High vol Mean-revert Momentum
4

GNB Probability

Gaussian Naive Bayes
Classification

Trains a binary Gaussian Naive Bayes classifier on three independent features to predict whether the next bar closes up or down:

  • f₀ — Return: (Close[i] − Close[i+1]) / Close[i+1] — captures short-term price change
  • f₁ — Volume ratio: log(Volume[i] / Volume[i+1]) — increasing volume often confirms moves
  • f₂ — HL spread: (High[i] − Low[i]) / Close[i] — wider ranges indicate uncertainty / volatility

The Naive Bayes assumption (conditional independence of features given the class) allows the joint likelihood to be computed as a product of univariate Gaussians: P(f₀,f₁,f₂ | class) = Πⱼ PDF(fⱼ | μ_class_j, σ_class_j).

Trade logic: If P(up | features) > InpGNBProbThresh (0.60) → Buy. If P(up) < 1 − threshold → Sell. Confidence = |P(up) − 0.5| × 2, mapping the range [0.5, 1.0] → [0, 1.0].

f₀ ret f₁ vol f₂ spread P(up) = Π PDF(f₀)·PDF(f₁)·PDF(f₂) Green = up class · Red = down class Naive assumption: features independent
5

Volatility Bands

Gaussian-Weighted Rolling Statistics
Overextended

Computes a Gaussian-weighted rolling mean and standard deviation over the last 30 bars. The Gaussian kernel (length 15, σ=4.0) assigns higher weight to recent prices — making the band adaptive to recent market conditions while still retaining statistical stability.

Band logic: When price moves beyond InpVolBandMultiplier (default 2.0) standard deviations from the weighted mean, the market is statistically overextended. A sell signal fires above the upper band, a buy below the lower band. The confidence scales linearly with the distance from the band edge, capped at 1.0.

Why Gaussian-weighted? Unlike a simple rolling window (equal weights), the Gaussian weighting smoothly transitions from recent to older data — avoiding the "cliff edge" effect where a bar suddenly drops out of the window, causing a discontinuous jump in the mean and std.

+2σ μ −2σ Price above +2σ → SELL
6

Z-Score Channel

Rolling Z-Score Statistics
Statistical

Calculates the z-score of the current close price relative to the mean and standard deviation of the last period (default 20) bars: z = (Price − μ) / σ. The z-score is a unitless measure of how many standard deviations the current price is from its recent average.

Fade-the-move logic: When |z| > InpZScoreEntry (default 2.0), the price is statistically extreme — large deviations from the mean tend to revert. A buy signal fires at z = −2.0 (oversold), a sell at z = +2.0 (overbought). The confidence scales linearly with |z|, capped at 1.0 at z = 5.0.

Why z-score? The z-score normalises price by recent volatility — it works across different instruments and timeframes without parameter changes. A z-score of 2.0 means the same thing (95th percentile) whether on EUR/USD H1 or XAU/USD D1, making this strategy the most portable of the six.

0 +2 −2 z = 3.2 → SELL Rolling z-score: (price − μ) / σ

Ensemble Voting

Each strategy returns a (signal, confidence) pair. The ensemble computes a weighted sum and compares it to a threshold.

            6
    totalVote =  Σ  signal_s × confidence_s × weight_s
            s=1

    if totalVote ≥ +threshold → BUY
    if totalVote ≤ −threshold → SELL
    else                      → NEUTRAL
VariableDescriptionRange
signalDirection vote from each strategy−1, 0, +1
confidenceHow strongly the strategy believes its signal[0.0, 1.0]
weightUser-configurable influence per strategyany positive
thresholdMinimum ensemble conviction to enterdefault 1.8

Risk Management

ATR-adaptive SL/TP, trailing stop, and breakeven — all configurable as percentages of TP distance rather than fixed point values.

ATR SL

1.5×
ATR multiplier for stop loss

ATR TP

3.0×
ATR multiplier for take profit

Trailing

50%
Activates at % of TP distance

Breakeven

30%
Move SL to entry at % of TP
FeatureHow It Works
ATR SL/TPAt order open, SL = price − 1.5 × ATR(14) and TP = price + 3.0 × ATR(14). Adapts to volatility automatically.
Trailing StopOnce price reaches 50% of the TP distance, the EA tracks the peak. SL is tightened in 25% increments of the TP distance.
BreakevenWhen price reaches 30% of TP distance, SL is moved to entry + small buffer (0.1 × ATR). Fires once per position.

Recommended Markets

The ensemble was designed for liquid markets with balanced trending and mean-reversion behaviour. Below are the best pairs and timeframes based on backtesting.

Best Pairs

PairWhy
EUR/USDTightest spread, balanced trending/ranging, GMM regime detection works well
GBP/USDMore volatility than EUR/USD, trends clearly, good for Filter + GPR combo
USD/JPYClean trends, lower noise, Z-score channels perform well
EUR/JPYHigher volatility, good for GMM high-vol regime momentum trades
XAU/USDStrong trending + sharp reversals — plays to both Filter and mean-rev strategies
Avoid exotics — wide spreads trigger InpMaxSpread rejection and ATR-based SL becomes erratic.

Best Timeframes

TFWhyTrades/week
H4 ★Sweet spot: enough bars for GPR/GMM training, low noise1–3
H1Good balance, more signals, noise filtered by ensemble3–6
D1Cleanest signals, but fewer trades; GPR lookback = 6 weeks0–1
Start here: EUR/USD H4 — the 6-strategy ensemble filters H4 noise well, ATR-based SL adapts to its volatility, and the GMM regime detector has clear high/low regimes to exploit.

Advanced Paid EAs

Need more power? FxMath offers professional-grade EAs with gradient boosting, reinforcement learning, and AI strategy generation — built for traders who demand more.

Feature GaussEnsemble
FREE
RFConsensus
$99
Lumina
$299
AI Engine Gaussian Ensemble (6 strategies) RF + LGBM + Q-Learning RL LightGBM Strategy Generator
Features 6 models — math from scratch 28 technical features 500+ ML features
Timeframes Any (best on H1–H4) 3 (multi-TF voting) Any (M1–MN)
Reinforcement Learning No Yes — Q-Learning Yes — Adaptive
Strategy 6 Gaussian strategies + voting AI ensemble consensus Custom-generated by RR target
Walk-Forward Validation Manual Yes Yes
Simultaneous Instances 1 per chart 1 per chart Unlimited
Platform MT4 + MT5 MT4 + MT5 MT5 (Python bridge)
DLL Required No — pure MQL RF: No / LGBM: Yes Yes (static)
$99 Lifetime

FxMath RFConsensus

Two AI Engines in One Package

RFConsensus is the first EA to offer two AI engines in one package: a pure-MQL Random Forest (no DLLs) and a LightGBM + Q-Learning version with reinforcement learning that adapts trading thresholds based on every trade outcome.

✓ RF (Pure MQL) + LGBM+RL ✓ 28 Technical Features ✓ Multi-TF Voting (3 TFs) ✓ Q-Learning RL Agent ✓ MT4 + MT5 Included ✓ Volatility-Adaptive Labels ✓ Q-Table Persistence ✓ Any Symbol & TF
Learn More →
Why more advanced: Uses 3 independent ML models across 3 timeframes with confidence-weighted voting. 28 features including skew, kurtosis, Elder-Ray, CMO. Q-Learning RL adapts thresholds in real time.
$299 Lifetime

FxMath Lumina

AI Strategy Generator

Lumina is an autonomous ML trading terminal. You don't code strategy rules — you set your ideal Risk/Reward ratio and profit target, and Lumina generates a complete machine-learned strategy around your preferences.

✓ AI Strategy Generator ✓ RR-Adaptive Learning ✓ Pair & TF Validator ✓ Walk-Forward Backtester ✓ Unlimited Instances ✓ Any TF (M1–MN) ✓ LightGBM Engine ✓ MT5 Python Bridge
Learn More →
Why more advanced: Generates a completely custom strategy from your RR target — it learns the market patterns, not just filters signals. Uses LightGBM gradient boosting (not simple models) — significantly higher predictive accuracy. Walk-Forward validation eliminates curve-fitting.

Get the EA — Free

Both MQL5 (.ex5) and MQL4 (.ex4) compiled files are ready to use. No registration, no license — deploy on any chart, any broker.

↓ Download EX5 (MT5) ↓ Download EX4 (MT4)
72 KB — compiled for MT5 build 1930+ 106 KB — compiled for MT4 build 600+

Get In Touch

Need a custom or more advanced EA? Explore FxMath Lumina (AI Strategy Generator, $299) or FxMath RFConsensus (Dual AI Engines + RL, $99). Or just ask us anything!

💬

Telegram

Join the community for updates & support

t.me/FxMath

Email

Click to copy to clipboard

[email protected]
💻

Custom Development

Need a tailored solution? Advanced EAs, indicators, or ML-based strategies?

Contact us for custom projects

🔮

Advanced EAs

Upgrade to Lumina (AI strategy generator) or RFConsensus (dual AI engines + RL)

lumina.fxmath.com rfconsensus.fxmath.com