This Expert Advisor implements a regime-aware, restartable grid-trading system grounded in the Bi-Directional Grid Constrained (BGC) stochastic process research by Aldo Taranto at the University of Southern Queensland (2020–2022). The research formally proves that naive grids converge toward ruin, but that finite cycles with regime-aware gating transform grid trading into a viable strategy with positive expected value under the right conditions.
Unlike conventional grid EAs that run a single open-ended grid until the account blows, this system operates in short, restartable cycles. Each cycle picks an anchor price, builds a grid, trades under active supervision, and closes when a profit target, drawdown threshold, age limit, or weekend rule triggers. The cycle then restarts fresh at current market conditions, resetting both variance accumulation and grid-level exposure back to zero.
The EA features three distinct grid algorithms that activate automatically based on detected market regime:
Mode selection happens automatically at each cycle restart based on the VolatilityGate (ATR/drift ratio with cooldown) and CPDEngine (frozen-baseline CUSUM structural break detector).
| Setting | Recommended value | Notes |
|---|---|---|
| Symbol | XAUUSD (Gold) | Primary development and testing instrument. The EA works on any symbol — ATR-dynamic spacing adapts automatically. |
| Chart timeframe | M1 (1-minute) | The chart timeframe is for tick-level execution and sync. Regime detection and ATR spacing use configurable higher timeframes (default H4 and D1). |
| Account type | Hedged | Required. The EA places simultaneous long and short positions and uses CloseBy for efficient shutdown. |
Important: Always test on a demo account first. Grid trading involves significant financial risk. The mathematical research demonstrates both the potential and the structural limitations of constrained grid systems. Past backtest performance does not guarantee future results.
Regime Detection and Mode Switching
Adaptive Grid Infrastructure
Cycle Management
Diagnostics Pipeline


The EA consists of one main file, nine header modules, and two companion Python scripts:
MQL5 Source Files
| File | Role | Description |
|---|---|---|
| GridEA.mq5 | Orchestrator | Main EA file — all inputs, OnInit/OnTick/OnDeinit, cycle start/restart policy, weekend rules, block flags, and glue code between modules. |
| Defines.mqh | Shared types | Enums (ENUM_GRID_STATE, ENUM_GRID_MODE, ENUM_LOT_MODE), structs (GridLevel, GridSession), and constants. |
| GridCore.mqh | Execution engine | Order placement for all three modes (PlaceLevelBGT/TGT/MGT), sync and re-arm, CloseAllPositions with CloseBy hedging, position recovery. |
| LotEngine.mqh | Lot sizing | Per-level lot calculation with mild multiplier mode and dynamic shrink-under-stress mode. |
| LtMonitor.mqh | Risk diagnostics | Theoretical L_t, weighted dollar loss, snapshot RPR, path-aware L_t, Theorem 52/53 ruin probability, expected absorption steps. |
| ProfitMonitor.mqh | Profit logic | Cycle profit calculation (equity minus cycleStartEquity), target check (percent or dollar), position counting. |
| VolatilityGate.mqh | Regime filter | ATR and drift computation on regime timeframe, sigma_t/mu_t ratio, cooldown-based favorable/unfavorable state, signed drift for trend direction. |
| CPDEngine.mqh | Break detector | Frozen-baseline CUSUM — collects baseline window, freezes it, accumulates S_high/S_low, fires on threshold breach, resets accumulators. |
| StateManager.mqh | Persistence | Saves and loads cycle state via MQL5 global variables. Supports spacing mismatch tolerance for ATR-dynamic mode. |
| DiagnosticLog.mqh | CSV logging | Buffers BarSnapshot, DiagCycleSummary, and DiagEventRecord rows in memory. Flushes to FILE_COMMON on OnDeinit or OnTester. |
Python Companion Scripts
| File | Purpose | Description |
|---|---|---|
| analyze_backtest.py | Post-run analysis | Loads latest CSVs from MetaTrader common files. Prints 13 text-analysis sections, runs 10 automated bug checks, generates 8 chart PNGs. Supports --date and --no-charts flags. |
| calibrate_parameters.py | Cross-run calibration | Loads all CSVs across all dates. Runs 6 calibration passes: variance age curve, Theorem 53 sanity check, sigma/mu threshold derivation, profitability zone analysis, expected-steps validation, and multi-timeframe regime detection. Supports --no-mt5 flag. |
The EA exposes 12 input groups. Key parameters are listed below with their defaults. All parameters are documented in the source code and explained in the accompanying article series.
| Group | Key parameters | Defaults |
|---|---|---|
| Grid structure | InpGridSpacing, InpGridLevels, InpBaseLot | 500 pts, 8 levels/side, 0.01 lot |
| Dynamic spacing | InpUseATRSpacing, InpATRSpacingTF, InpATRSpacingMultiplier | true, D1, 0.12 |
| Dynamic lot sizing | InpUseDynamicBaseLot, InpLotFraction | true, 0.000003 |
| Exit conditions | InpRuinThreshold, InpProfitTargetPercent, InpMaxCycleHours | 0.25 (25%), 3.0%, 72 hours |
| Regime detection | InpRegimeTF, InpMinSigmaMuRatio, InpATRPeriod, InpMAPeriod | H4, 5.0, 14, 20 |
| Mode switching | InpEnableTGT, InpEnableMGT, InpTGTSigmaMuThreshold | true, true, 5.0 |
| CPD | InpUseCPD, InpCPDWindow, InpCPDDelta, InpCPDThreshold | true, 50, 2.0, 15.0 |
| Weekend | InpEnableWeekendClose, InpFridayCloseHour, InpMondayResumeHour | true, 22, 1 |
Note: Disable free-margin closures if need not be.
The EA is based on the following academic work by Aldo Taranto and Manzur Khan at the University of Southern Queensland:
A detailed companion article series explains the mathematical foundations and walks through the implementation of each module. It's Now Available
ExMachina Heikin Ashi
Heikin Ashi overlay (color candles or line) with 5 smoothing methods, step filter, MTF, signal arrows, strength meter, dashboard, and 4-channel alerts (popup/sound/push/email). Free.
ExMachina Smart Money Concepts
Complete SMC toolkit: BOS/CHoCH detection, Order Blocks (internal + swing), Fair Value Gaps, Equal Highs/Lows, Premium/Discount zones, Strong/Weak H/L, trend candles, dashboard, 4-channel alerts. Free.
MACD Tradingview version
The standard MACD on MT5 platform seem to be not enough so I code this version by copying from the pinescript.
SMC Fair Value Gap (FVG) Auto-Detector
A clean, lightweight, and non-repainting indicator that automatically detects and draws Smart Money Concepts (SMC) Fair Value Gaps (FVG) directly on your chart across any timeframe.