A robust MetaTrader 5 Expert Advisor implementing a bi-directional ATR-based grid trading strategy with dynamic lot sizing, drawdown protection, and broker-aware stop management.
β‘ ATR-Adaptive Β· π‘οΈ Drawdown Protected Β· π Bi-directional Β· π€ Fully Automated
GridMaster Pro is a quantitative trading EA that exploits market volatility in ranging markets. Unlike trend-following systems that rely on prediction, it uses a grid execution model to capture profit from mean-reversion movements.
- Bi-directional β Places BUY orders below AND SELL orders above the current price simultaneously (Neutral mode), or can run one-sided in trending markets.
- ATR-Adaptive β Grid spacing dynamically adjusts to market volatility using ATR, preventing over-trading in low-volatility and under-trading in high-volatility conditions.
- Broker-Aware β Reads
SYMBOL_TRADE_STOPS_LEVELand enforces proper minimum stop distances, preventing the "Invalid stops" error common on crypto and exotic pairs. - Risk-Managed β Built-in drawdown circuit breaker auto-pauses and closes all positions when equity drops beyond a configurable threshold.
| Parameter | Default | Description |
|---|---|---|
GridMode |
NEUTRAL | NEUTRAL (both), BULLISH (buy only), BEARISH (sell only) |
MaxOrders |
5 | Max open positions per side |
ATRPeriod |
14 | ATR lookback period |
ATRMultiplier |
1.5 | Grid spacing = ATR Γ multiplier |
| Parameter | Default | Description |
|---|---|---|
LotMode |
FIXED | FIXED or DYNAMIC (risk % per order) |
LotSize |
0.1 | Fixed lot (ignored in dynamic mode) |
RiskPercent |
1.0 | % of balance risked per order (dynamic mode) |
DefaultTP |
200 | Minimum TP in points (auto-raised to broker minimum) |
DefaultSL |
1000 | Minimum SL in points (auto-raised to broker minimum) |
UseTrailingStop |
true | Enable trailing stop |
TrailingPoints |
100 | Trailing activation distance in points |
TrailingStep |
20 | Trailing step (minimum move before update) |
| Parameter | Default | Description |
|---|---|---|
MaxDrawdownPct |
5.0 | Max equity drawdown % before pause |
CloseOnDrawdown |
true | Close all positions on drawdown breach |
- Bi-directional Grid β BUY + SELL simultaneously in NEUTRAL mode
- Dynamic Grid Distance β ATR-based spacing adapts to volatility
- Broker-Aware Stops β Reads broker minimum stop level, auto-adjusts TP/SL
- Dynamic Lot Sizing β Risk-based lot calculation (% of balance)
- Drawdown Protection β Circuit breaker pauses grid on equity loss
- Trailing Stop β Proper directional trailing with configurable step
- Live Position Count β Uses
PositionSelectByTicket()+ magic filter (no stale counters) - Collision-Safe Magic Number β Symbol + timeframe based, prevents EA cross-interference
- Append Logging β Log file appends properly (no data loss on each tick)
- OnDeinit Cleanup β Graceful deinitialization with position count report
| Instrument | LotSize | MaxOrders | ATRMult | DefaultTP | DefaultSL | MaxDrawdown |
|---|---|---|---|---|---|---|
| BTCUSD | 0.01 | 5 | 2.0 | 1000 | 5000 | 5% |
| EURUSD | 0.1 | 8 | 1.5 | 200 | 1000 | 3% |
| XAUUSD | 0.05 | 6 | 1.8 | 500 | 3000 | 4% |
| GBPUSD | 0.1 | 6 | 1.6 | 200 | 1200 | 3% |
- Download β Get
GridMaster Pro.mq5from this repository - Deploy β Copy to
MetaTrader 5 / MQL5 / Experts / - Compile β Open MetaEditor (F4), compile (F7), check for 0 errors
- Attach β Drag onto chart (EURUSD H1 recommended for testing)
- Enable β Turn on "Algo Trading" in the toolbar
Grid strategies can sustain large drawdowns during strong trending markets when orders stack against the trend. Always:
- Set
MaxDrawdownPctto limit losses (recommended: 3-5%)- Test on demo account for at least 2 weeks before going live
- Never risk more than you can afford to lose
- Fixed: "Position doesn't exist" error β
PositionSelect(_Symbol)replaced withPositionSelectByTicket()+ magic number filter. Old code was attempting to modify positions with ticket#0(invalid). - Fixed: "Invalid stops" on BTCUSD/crypto β
DefaultTP = 100points was below broker minimum stop distance for BTC. Now readsSYMBOL_TRADE_STOPS_LEVELand enforcesMathMax(userTP, brokerMin Γ 1.5)on every order. - Fixed:
ordersCountstale counter β Old code incremented but never decremented, permanently stopping order placement after MaxOrders. Replaced with liveCountOurPositions()calculated on each tick. - Fixed:
SymbolInfoIntegerwrong usage β Was passingtradeAllowedas reference (compile error on some compilers). Fixed to properlong x = SymbolInfoInteger(...)usage. - Fixed: Log file overwrites β
FILE_WRITEwas truncating the log on every write. Fixed withFILE_READ | FILE_WRITE+FileSeek(SEEK_END)to append.
- Bi-directional grid β Three modes: NEUTRAL (BUY+SELL), BULLISH (BUY only), BEARISH (SELL only)
- Dynamic lot sizing β Risk-based mode:
lot = (balance Γ riskPct) / (SL Γ tickValue) - Drawdown circuit breaker β Auto-closes all positions and pauses grid when equity falls below threshold
- Improved trailing stop β Separate BUY/SELL logic with
TrailingStepminimum move - Collision-safe magic number β
MagicBase + symbolLenΓ1000 + timeframe, prevents interference with other EAs - OnDeinit handler β Logs position count on EA removal
- Replaced manual
OrderSendwithCTradelibrary for cleaner, more reliable execution - Removed
GenerateMagicNumber()string-parsing hack CalculateLot()now handles both FIXED and DYNAMIC modesOrderExistsNearPrice()prevents duplicate orders at the same grid level
- Initial release with BUY-only grid
- ATR-based dynamic grid distance
- Basic retry mechanism for order placement
- File logging (overwrites β bug)
ordersCountcounter (stale β bug)
- Basket close β Close all BUY + SELL positions when combined floating profit β₯ target
- Partial close β Close oldest/worst position when new grid level is hit
- Break-even stop β Move SL to open price after first TP hit
- Moving average trend filter β Only place BUY orders when price > MA200, SELL when below
- RSI filter β Only place orders when RSI is not overbought/oversold
- Session filter β Restrict trading to London/NY sessions for forex pairs
- Martingale mode β Optional lot multiplier per grid level (configurable, off by default)
- Equity lock β Don't open new orders when floating loss exceeds threshold
- Correlation guard β Prevent opening grid on correlated pairs simultaneously
- WhatsApp/Telegram alerts β Notify on order placed, TP hit, drawdown breach
- Dashboard panel β On-chart display of grid levels, P&L, position count
- Backtesting reports β 5-year reports on EURUSD, BTCUSD, XAUUSD
- ML regime detection β Classify market as trending/ranging, auto-select grid mode
- GPT-based parameter optimizer β Suggest ATR multiplier based on recent volatility history
- Integration with MarketSync-EA β AI decides WHEN to deploy the grid
| Project | Description |
|---|---|
| MarketSync-EA | AI-powered evolution β uses ML to decide when/where to place the grid |
| Slippage Tracker | Monitor broker execution quality for your grid orders |
| WhatsApp Bot | Trade alerts via WhatsApp |
Distributed under the MIT License. See LICENSE for more information.
MQL5 Developer Β· Quantitative Researcher Β· AI Trading Systems