Live Trading — Version 1.0

Random Forest
Grid Trading
Reimagined

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

120

Features

4

Forests

20

Trees Each

MT4+MT5

Both Platforms

Σ G π θ α RF CORE buy sell trend hedge gini impurity · bootstrap · oob
🧠

Self-Learning AI

4 Random Forests that retrain automatically — adapts as markets change

🌍

Any Market, Any TF

Forex, Gold, Indices, Crypto — M30 to D1 — MT4 and MT5

🔄

Online Updates

Model retrains every N bars in real-time, no manual intervention needed

🌊

Regime-Aware

Auto-detects range vs trend — adjusts grid, lot size, and risk instantly

🛡️

Bank-Grade Safety

Drawdown limits, daily loss cap, strong trend auto-exit — no blowouts

Why This Strategy Works

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.

🌲

Ensemble Learning Reduces Variance

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

📊

120 Features Capture Market Microstructure

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.

🔄

Online Learning = Constant Adaptation

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.

🎯

4-Model Consensus Eliminates Noise

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

🌊

Regime Detection Prevents Curve-Fitting

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.

🛡️

Mathematical Risk Controls

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.

The Model Updates Every N Bars

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.

🕯️ NEW BARS 📐 120 FEATURES 🌲🌲 TRAIN 4 FORESTS 🎯 PREDICT RETRAIN EVERY N BARS CopyClose/CopyHigh/... Gini impurity 4 predictions Candles closed default: 24 bars
1

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.

2

Fetch & Compute 120 Features

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.

3

Generate Labels & Train 4 Forests

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.

4

Predict & Trade Until Next Retrain

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.

♾️

Continuous Loop — Never Stale

This cycle runs forever. Old data is discarded, new patterns are learned. The EA is always up to date with the latest market microstructure.

60
Price-Relative Features
60
Technical Indicators
80
Total Trees (4×20)
8
Max Tree Depth

Everything Built From Scratch

Zero dependencies. Zero external libraries. Every algorithm — from the Random Forest training loop to the technical indicators — is hand-coded in pure MQL4/MQL5.

🌲

Random Forest Engine

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 ML
📐

120-D Feature Space

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

Engineering
🔄

Online Retraining

Trains on latest InpTrainBars (default 1000), retrains every InpRetrainBars (default 24). Model automatically adapts to changing volatility, trends, and market microstructure.

Auto-Adapt
🌊

Regime Adaptation

Real-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-Learning
🔲

Adaptive Grid Trading

Grid distance = ATR × multiplier (self-adjusting to volatility). Levels = base × regime multiplier. Lot size = base × regime multiplier. In range mode: BB mean-reversion entries added.

Execution
📊

Multi-TF Trend Filter

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

Protection
🛡️

Account Protection Suite

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

Safety
📈

Chart Info Panel

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

UX

100% Pure MQL

No 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 Deps

Traditional Grid vs FxMath Elite Pro

Most 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 AdaptiveInpFixedLot=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

Tick Processing Pipeline

Every tick runs through a deterministic pipeline — from feature computation to trade execution — all within milliseconds.

⚡ OnTick() — 1s throttle 🛡️ CheckProtection() 🔄 CheckRetrain() 🌊 DetectRegime() GetLiveFeatures() 120 features GetSignal() 4 Forest Predicts RETRAIN Boostrap 1000 samples Gini + class weights 20 trees × 4 forests OOB error estimation 📈 ManageGrid() ✏️ ModifyPositions() 🎯 Trailing() grid distance = ATR × mult · levels = max × regime · lot = base × regime range: tight grid · weak trend: normal · strong trend: wide + reduced risk 📊 LIVE PANEL REGIME: RANGE SCORE: 0.22 Bal: 10000.00 FlP: +50.00 DD: 0.5% pB:0.72 pS:0.31 pW:0.85 pH:0.68
📊 FxMath Elite Pro — Live Bal: 10,000.00  |  Equ: 10,050.00 FlP: +50.00  |  DD: 0.5% Buy: 3  |  Sell: 2 Model Predictions B: 0.72   S: 0.31 W: 0.85   H: 0.68 80 trees active REGIME RANGE score: 0.22 Grid Settings Distance: 20.0  |  ATR: 12.5 MaxG: 10  |  Mode: Adaptive Protection 🛡️ Status: ACTIVE DD Limit: 30%  |  Daily: Off Learning Cycle Retrain: 12/24 bars Model: READY

See Everything at a Glance

Every piece of information the EA uses to make decisions is displayed on your chart in a sleek HUD panel:

  • Account Health — Balance, Equity, Floating P&L (color-coded), Drawdown %
  • Model Predictions — Live pB, pS, pW, pH values from all 4 forests (80 trees)
  • Regime Status — Current regime (Range/Weak Trend/Strong Trend), direction (Bullish/Bearish), and score
  • Grid Configuration — Current grid distance (ATR-adjusted), ATR value, max levels, regime mode
  • Protection Status — Green = Active, Red = Triggered, Gray = Disabled
  • Retrain Progress — How many bars since last retrain, current retrain schedule

⚡ All values update in real-time on every tick — zero lag, zero external tools.

Works on Any Market, Any Timeframe, Both Platforms

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.

🪙

Gold & Metals

XAUUSD, XAGUSD — strong mean reversion and range behavior make grid strategies highly effective on H1-H4.

H1H4D1
💶

Forex Majors

EURUSD, GBPUSD, USDJPY — lower spreads, good volatility for grid capture. Works on M30 to D1.

M30H1H4D1
📊

Indices

US30, NASDAQ, FTSE, DAX — trending indices benefit from the ADX-based trend exit and reduced lot sizing.

H1H4D1

Crypto

BTCUSD, ETHUSD — high volatility means wider ATR-based grids. The regime detector handles crypto's explosive breakouts.

H1H4D1

🔬 Why Any Pair, Any TF, Both MT4 & MT5?

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.

From Tick to Trade — The Full Cycle

Every tick is processed through the same deterministic pipeline. Here's exactly what happens:

1. Throttle & Protection Check

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.

2. Check Retrain Schedule

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.

3. Detect Market Regime

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.

4. Compute Features & Get Signal

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.

5. Manage Grid

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.

6. Modify Positions & Trailing

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.

Purchase a License — 50% OFF

Run FxMath Gold AI Elite on up to 3 MT5 accounts simultaneously and switch anytime. All payments in Cryptocurrency.
🎉 50% DISCOUNT - Limited Time Offer! 🎉

1 Month
$69
per month

Perfect for testing. Full access, all features, 3 accounts.

Buy Now — Crypto
6 Months
$199
Save $215
$33/mo — best short-term value

Half-year plan for committed traders.

Buy Now — Crypto
24 Months
$399
Save $1,257
$16.6/mo — long-term power

Two years of hands-free automated trading.

Buy Now — Crypto
Lifetime
$799
one-time payment
Unlimited — never pay again

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

Frequently Asked Questions

Everything you need to know about the EA.

How is this different from other grid EAs?
Most grid EAs use fixed rules — enter at X pips, add every Y pips, close at Z profit. They fail when market conditions change. This EA uses a Random Forest trained on 120 features that adapts online. It also has regime detection that changes grid behavior based on whether the market is ranging or trending. It's not a grid EA with ML bolted on — it's an ML model that uses a grid as its execution mechanism.
Does it work on both MT4 and MT5?
Yes — both platforms are fully supported. The EA is compiled as .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.
Does it need any special setup?
No. It's a single .ex5 or .ex4 file. Drop it in your Experts folder, drag onto a chart, and it works. No DLLs, no Python, no external data, no API keys. The model trains itself on the first tick using the chart's own price history.
Can I use it on multiple symbols simultaneously?
Absolutely. Each chart runs its own independent instance with its own 4 Random Forests. You can run XAUUSD on one chart, EURUSD on another, and BTCUSD on a third — each will train its own models specific to that instrument's behavior. Just make sure each instance has a unique magic number.
How much drawdown should I expect?
This depends on your settings and market conditions. With default parameters on XAUUSD H1, typical drawdown ranges 10-25% during normal conditions. The account protection system (max drawdown % and daily loss limit) gives you hard safety guarantees. The strong trend exit also prevents catastrophic drawdown during runaway trends.
Which markets and timeframes work best?
Any symbol, any timeframe. The EA uses percentage-change features that normalize across instruments. It has been tested on Forex (EURUSD, GBPUSD, USDJPY), Gold (XAUUSD), Silver (XAGUSD), Indices (US30, NASDAQ, FTSE), and Crypto (BTCUSD, ETHUSD). Recommended timeframes range from M30 to D1 — H1 is the sweet spot. The regime detector automatically adjusts grid behavior for each market's unique volatility and trending characteristics.
Does the Random Forest overfit?
The architecture is specifically designed to prevent overfitting: (1) Bootstrap sampling adds randomness, (2) Random feature subsets (√m ≈ 11/120) decorrelate trees, (3) Max depth limits tree complexity, (4) Min samples per split prevents leaf nodes from fitting noise, (5) OOB error estimation gives unbiased accuracy metrics without a separate validation set, (6) Online retraining prevents the model from being stale.
How do I pay with cryptocurrency?
All payments are processed through secure crypto checkout. Click any "Buy Now — Crypto" button, choose your license plan, and complete the payment with BTC, ETH, USDT, BNB, SOL, LTC, DOGE, and many more. After payment confirmation, you will receive download links for both the .ex5 (MT5) and .ex4 (MT4) files instantly. No personal information required — your privacy is protected.
What's the recommended starting configuration?
Start with defaults on XAUUSD H1 or EURUSD H1 with a demo account. Run for 2-4 weeks to let the models train through different market conditions. If drawdown is too high: increase InpTrendStrength (0.6→0.8), lower InpRangeADXMax (22→18), or decrease InpMaxGrid (10→7). If too few trades: lower InpTrendStrength or increase InpRetrainBars to keep models fresher.

Ready to Transform Your Trading?

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