New Candles Close
Every time the configured number of bars (default 24) close, the EA wakes up for retraining. This happens automatically — no scheduler, no external trigger.
A fully self-contained Expert Advisor that trains 4 Random Forests directly inside MetaTrader 4 and MetaTrader 5 — no DLLs, no Python, no dependencies. 120 features, real-time regime adaptation, and pure MQL horsepower. 🔥 Works on ANY symbol — Forex, Gold, Indices, Crypto — ANY timeframe
Features
Forests
Trees Each
Both Platforms
4 Random Forests that retrain automatically — adapts as markets change
Forex, Gold, Indices, Crypto — M30 to D1 — MT4 and MT5
Model retrains every N bars in real-time, no manual intervention needed
Auto-detects range vs trend — adjusts grid, lot size, and risk instantly
Drawdown limits, daily loss cap, strong trend auto-exit — no blowouts
Most grid EAs fail because they use fixed rules that break when market conditions change. This EA uses online Random Forest learning to continuously adapt — and the math proves why it works across any market and timeframe.
A single decision tree overfits easily — high variance, low bias. A Random Forest averages 20+ decorrelated trees, each trained on a bootstrap sample with random feature subsets (√m ≈ 11 of 120). The Central Limit Theorem guarantees that the ensemble's prediction error converges to the Bayes optimal as trees increase. σ²_ensemble ≈ σ² / T · (1 + ρ(T−1)) where ρ is tree correlation (minimized by random feature selection).
Price-action is non-linear and regime-dependent. Using only 5-10 indicators misses the complex interactions between momentum, volatility, and mean reversion. With 60 price-relative ratios + 60 technical indicators, the model can learn non-linear decision boundaries that no single indicator can capture. The Gini impurity criterion automatically selects the most informative features at each split.
Markets evolve — what worked last month may fail today. The EA retrains all 4 forests every N bars (default 24) on the latest data. This is online learning without the overhead: each retrain discards stale patterns and learns new ones. The training window slides forward, so the model always sees the most recent market regime. No manual retraining.
A single binary classifier produces ~50% false signals in noisy data. This EA uses 4 independent forests (Buy, Sell, Trend/W, Hedge/H) that must agree before a trade is taken. The probability of all 4 models being wrong simultaneously drops exponentially: P(all 4 wrong) = ∏ P(eᵢ) where eᵢ = misclassification rate With each model at 70% accuracy, the joint error rate ≈ 0.3⁴ ≈ 0.8%.
A model trained on trending data fails in range markets, and vice versa. The EA's regime detector classifies the market as Range / Weak Trend / Strong Trend using ADX + Bollinger Width + Momentum consistency. Parameters adjust: wider grids and fewer levels in trends, tighter grids with BB mean-reversion in ranges. This is a meta-learning layer that prevents the strategy from being overfit to any single market condition.
Every trade is governed by hard statistical limits. Max drawdown from balance, daily loss limit in account currency, and an ADX-based strong trend exit that closes all positions when the market becomes directional beyond a threshold. This isn't arbitrary — it's a stop-loss on the strategy itself, preventing the grid from being destroyed by a runaway trend.
This isn't a static EA that was trained once and sold. FxMath Elite Pro retrains itself continuously — every time N new candles close, it fetches fresh data, computes features, and rebuilds all 4 forests. The model is never stale.
Every time the configured number of bars (default 24) close, the EA wakes up for retraining. This happens automatically — no scheduler, no external trigger.
The EA pulls the latest InpTrainBars (default 1000) candles and computes all 120 features per candle — price-relative ratios, SMA, RSI, MACD, ATR, Bollinger, ADX, momentum, candle anatomy.
Each candle is labeled for Buy (B), Sell (S), Trend (W), and Hedge (H) using the TP/SL window method. Then 4 independent Random Forests are trained with bootstrap, Gini impurity, and class weighting.
The fresh models predict on every new tick until the next retrain cycle. If market conditions shift, the models may be less accurate — but that's fine, because they'll retrain again soon.
This cycle runs forever. Old data is discarded, new patterns are learned. The EA is always up to date with the latest market microstructure.
Zero dependencies. Zero external libraries. Every algorithm — from the Random Forest training loop to the technical indicators — is hand-coded in pure MQL4/MQL5.
Bootstrap sampling, Gini impurity with class weights, random feature subset (√m ≈ 11), recursive binary tree building, OOB error estimation, and feature importance counting — all in native MQL.
Core ML60 price-relative features (open/high/low/close % changes over 15 bars) + 60 indicators: SMA, RSI, MACD, ATR, Bollinger %B, ADX, Momentum ROC, candle anatomy ratios, and volatility spreads.
EngineeringTrains on latest InpTrainBars (default 1000), retrains every InpRetrainBars (default 24). Model automatically adapts to changing volatility, trends, and market microstructure.
Auto-AdaptReal-time detection using ADX (50%), Bollinger Band width (30%), momentum consistency (20%). Three regimes: Range, Weak Trend, Strong Trend — each with tailored grid/risk parameters.
Meta-LearningGrid distance = ATR × multiplier (self-adjusting to volatility). Levels = base × regime multiplier. Lot size = base × regime multiplier. In range mode: BB mean-reversion entries added.
Execution4-indicator consensus: HTF SMA 200 slope, ADX +DI/-DI on trading TF, MACD histogram slope, RSI 14 regime. Blocks counter-trend trades with configurable threshold.
ProtectionMax drawdown % from balance, max daily loss in account currency, strong trend auto-close (ADX ≥ threshold), optional trade halt after protection trigger. No DD can wipe the account.
SafetyLive HUD on the chart showing balance, equity, floating P&L, drawdown %, position counts, all 4 model predictions, current regime/direction/score, ATR, grid config, protection status, and retrain progress.
UXNo DLLs, no external imports, no Python scripts. A single self-contained .ex5/.ex4 file. Compiles cleanly on any MetaTrader 5 or 4 terminal. Easy deployment to any broker.
Zero DepsMost grid EAs on the market are static rule-based systems. See what makes this one different.
| Feature | ❌ Traditional Grid EA | ✅ FxMath Elite Pro |
|---|---|---|
| Entry Logic | Fixed distance from price — enters at X pips regardless of market state | Random Forest predicts probability using 120 features — enters only when ML model sees a high-confidence opportunity |
| Market Adaptation | ✗ None — same behavior in range and trend | ✓ Regime detector — ADX + BB + momentum score → switches between range, weak trend, and strong trend modes |
| Model Updates | ✗ Static — trained once (if at all), never changes | ✓ Online retraining — retrains automatically every N bars, model evolves with the market |
| Feature Set | 3–10 basic indicators — typically just SMA, RSI, or Bollinger | 120 features — 60 price-relative + 60 technical: SMA, RSI, MACD, ATR, Bollinger %B, ADX, Momentum, candle anatomy, volatility ratios |
| False Signal Filtering | ✗ Single signal source — high false positive rate in noisy markets | ✓ 4-model consensus — Buy + Sell + Trend + Hedge forests must agree. Joint error rate ≈ 0.8% |
| Risk Management | Basic SL/TP, sometimes trailing. No account-level protection. | 3-layer protection — max drawdown % from balance, daily loss limit, strong trend auto-close (ADX ≥ threshold) |
| Grid Distances | Fixed pips — too tight in volatility, too wide in quiet markets | ATR-adaptive — grid distance = ATR × multiplier, self-adjusts to current volatility. Regime-adjusted (×0.8 range, ×1.5 trend). Hard-minimum clamp — never drops below InpGridDistance, even after multipliers. |
| Position Sizing | Fixed lot or simple martingale — no market awareness | Fixed or Adaptive — InpFixedLot=true (default) uses exact base lot for ALL levels — no scaling, no regime multipliers. When disabled: lot = base × regime multiplier × InpLotRatioⁿ. Full lots in range, reduced (×0.3) in strong trend. |
| Mean Reversion | ✗ None — only trades on grid distance | ✓ BB Reversion — in range mode, enters buy at lower Bollinger Band and sell at upper band, even without ML signal |
| Trend Filter | ✗ None — takes counter-trend trades and gets crushed | ✓ Multi-TF consensus — HTF SMA 200 + ADX + MACD + RSI → blocks counter-trend trades above configurable threshold |
| Platform Support | Usually MT4 or MT5 only — not both | ✓ MT4 + MT5 — same EA, same logic, both platforms. Ship .ex5 and .ex4 with every license |
| Dependencies | Often needs DLLs, API keys, or external data feeds | ✓ Zero dependencies — pure MQL, no DLLs, no Python, no external data. Drop on chart and go |
| Transparency | Black box — you have no idea why trades are taken | ✓ Full chart HUD — live panel shows all 4 predictions, regime, score, grid, protection, and retrain status in real-time |
Every tick runs through a deterministic pipeline — from feature computation to trade execution — all within milliseconds.
Every piece of information the EA uses to make decisions is displayed on your chart in a sleek HUD panel:
⚡ All values update in real-time on every tick — zero lag, zero external tools.
The feature engineering is purely price-based with zero symbol-specific parameters. The model self-adapts to the volatility, trend behavior, and microstructure of whatever instrument you trade. Supports both MetaTrader 4 and MetaTrader 5 — a single license works seamlessly on both platforms.
XAUUSD, XAGUSD — strong mean reversion and range behavior make grid strategies highly effective on H1-H4.
EURUSD, GBPUSD, USDJPY — lower spreads, good volatility for grid capture. Works on M30 to D1.
US30, NASDAQ, FTSE, DAX — trending indices benefit from the ADX-based trend exit and reduced lot sizing.
BTCUSD, ETHUSD — high volatility means wider ATR-based grids. The regime detector handles crypto's explosive breakouts.
All 120 features use percentage changes relative to the current price, not absolute values.
This normalises the feature space across any instrument and any timeframe. The Random Forest learns
relative patterns — like "when RSI is below 30 and price is above SMA 200, buy signals
have 70% probability" — which generalise across markets. The online retraining then fine-tunes the
thresholds to the current instrument's specific dynamics. You don't need to change anything
when switching from XAUUSD H1 to BTCUSD H4.
MT4 & MT5: The core engine is written in the common MQL4/MQL5 subset, with platform-specific
abstractions for order management. Both versions ship together — you get .ex5 and .ex4
with every license.
Every tick is processed through the same deterministic pipeline. Here's exactly what happens:
The EA runs max once per second. First it checks account safety — if drawdown exceeds max % or daily loss limit is breached, all positions close and trading stops. Safety always comes first.
If N new bars have closed since last retrain, the EA enters training mode: fetch latest 1000 bars, compute 120 features per bar, generate 4 label sets (B/S/W/H), train 20 trees per forest. Until training completes, no new trades — existing positions keep running with their SL/TP/trails.
ADX + Bollinger width + momentum consistency → weighted score (0.0–1.0). Score < 0.35 = Range, 0.35–0.65 = Weak Trend, > 0.65 = Strong Trend. Direction determined by MACD histogram + ADX +DI/-DI.
Compute 120 features from latest 15 candles. Run all 4 forests (80 trees total) to get pB, pS, pW, pH. Apply consensus logic: Buy = pB≥0.5 AND pW≥0.5 AND pH≥0.5. Also apply the multi-TF trend filter to block counter-trend signals.
If signal is valid: open first position or add a grid level. Grid distance adapts to regime (tighter in range, wider in trend). In range mode, also enter on BB touches. Lot size scales with grid step (×InpLotRatio) and regime multiplier.
Recalculate TP = avgPrice ± totalTP / count. Set SL behind the last grid entry. Trail all positions as price moves favorably — locking profit without interfering with grid stacking.
Run FxMath Gold AI Elite on up to 3 MT5 accounts simultaneously
and switch anytime. All payments in Cryptocurrency.
🎉 50% DISCOUNT - Limited Time Offer! 🎉
Half-year plan for committed traders.
Buy Now — CryptoThe sweet spot. Maximum savings, full year of AI trading.
Buy Now — CryptoTwo years of hands-free automated trading.
Buy Now — CryptoForever access. All future updates included.
Buy Now — Crypto💳 All transactions processed through Cryptocurrency — BTC, ETH, USDT, BNB, SOL, LTC, DOGE, and more. Secure and private.
⚡ After purchase you will receive the compiled .ex5 (MT5) and .ex4 (MT4) files instantly.
Everything you need to know about the EA.
.ex5 for MetaTrader 5 and .ex4 for MetaTrader 4. Both versions have identical logic, features, and performance. A single license gives you access to both files. Run on MT4, MT5, or both simultaneously on up to 3 accounts..ex5 (MT5) and .ex4 (MT4) files instantly. No personal information required — your privacy is protected.If you want to execute these trades 100% automated and hands-free, purchase a license for FxMath Gold AI Elite. Run it on 3 MT5 accounts simultaneously and switch anytime.
📡 Get free realtime signals — join our Telegram Group:
✈️ t.me/FxMathAI