Skip to content

sajidmahamud835/grid-master-pro-mt5-ea

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

36 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– GridMaster Pro β€” Algorithmic Grid Trading System

MQL5 Version Strategy License Stars

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

Report Bug Β· Request Feature Β· Trading Plan


πŸ“– About The Project

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.

✨ Key Design Principles

  1. Bi-directional β€” Places BUY orders below AND SELL orders above the current price simultaneously (Neutral mode), or can run one-sided in trending markets.
  2. ATR-Adaptive β€” Grid spacing dynamically adjusts to market volatility using ATR, preventing over-trading in low-volatility and under-trading in high-volatility conditions.
  3. Broker-Aware β€” Reads SYMBOL_TRADE_STOPS_LEVEL and enforces proper minimum stop distances, preventing the "Invalid stops" error common on crypto and exotic pairs.
  4. Risk-Managed β€” Built-in drawdown circuit breaker auto-pauses and closes all positions when equity drops beyond a configurable threshold.

βš™οΈ Parameters

Grid Settings

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

Order Settings

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)

Risk Management

Parameter Default Description
MaxDrawdownPct 5.0 Max equity drawdown % before pause
CloseOnDrawdown true Close all positions on drawdown breach

πŸš€ Features

βœ… Implemented (v2.0)

  • 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

πŸ“‹ Recommended Settings by Instrument

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%

πŸ“₯ Getting Started

Installation

  1. Download β€” Get GridMaster Pro.mq5 from this repository
  2. Deploy β€” Copy to MetaTrader 5 / MQL5 / Experts /
  3. Compile β€” Open MetaEditor (F4), compile (F7), check for 0 errors
  4. Attach β€” Drag onto chart (EURUSD H1 recommended for testing)
  5. Enable β€” Turn on "Algo Trading" in the toolbar

⚠️ Risk Warning

Grid strategies can sustain large drawdowns during strong trending markets when orders stack against the trend. Always:

  • Set MaxDrawdownPct to 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

πŸ“‹ Changelog

v2.0.0 β€” 2026-04-07 (Current)

πŸ”΄ Critical Bug Fixes

  • Fixed: "Position doesn't exist" error β€” PositionSelect(_Symbol) replaced with PositionSelectByTicket() + magic number filter. Old code was attempting to modify positions with ticket #0 (invalid).
  • Fixed: "Invalid stops" on BTCUSD/crypto β€” DefaultTP = 100 points was below broker minimum stop distance for BTC. Now reads SYMBOL_TRADE_STOPS_LEVEL and enforces MathMax(userTP, brokerMin Γ— 1.5) on every order.
  • Fixed: ordersCount stale counter β€” Old code incremented but never decremented, permanently stopping order placement after MaxOrders. Replaced with live CountOurPositions() calculated on each tick.
  • Fixed: SymbolInfoInteger wrong usage β€” Was passing tradeAllowed as reference (compile error on some compilers). Fixed to proper long x = SymbolInfoInteger(...) usage.
  • Fixed: Log file overwrites β€” FILE_WRITE was truncating the log on every write. Fixed with FILE_READ | FILE_WRITE + FileSeek(SEEK_END) to append.

✨ New Features

  • 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 TrailingStep minimum move
  • Collision-safe magic number β€” MagicBase + symbolLenΓ—1000 + timeframe, prevents interference with other EAs
  • OnDeinit handler β€” Logs position count on EA removal

πŸ”„ Refactoring

  • Replaced manual OrderSend with CTrade library for cleaner, more reliable execution
  • Removed GenerateMagicNumber() string-parsing hack
  • CalculateLot() now handles both FIXED and DYNAMIC modes
  • OrderExistsNearPrice() prevents duplicate orders at the same grid level

v1.04 β€” 2024 (Previous)

  • Initial release with BUY-only grid
  • ATR-based dynamic grid distance
  • Basic retry mechanism for order placement
  • File logging (overwrites β€” bug)
  • ordersCount counter (stale β€” bug)

πŸ—ΊοΈ Future Roadmap

v2.1 β€” Order Management

  • 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

v2.2 β€” Trend Filter

  • 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

v2.3 β€” Advanced Risk

  • 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

v2.4 β€” Analytics & Alerts

  • 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

v3.0 β€” AI-Enhanced (MarketSync Integration)

  • 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

πŸ”— Related Projects

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

πŸ“„ License

Distributed under the MIT License. See LICENSE for more information.


Sajid Mahamud

MQL5 Developer Β· Quantitative Researcher Β· AI Trading Systems

🌐 Portfolio Β· πŸ“Š MQL5 Profile Β· ⭐ Star this repo

About

A fully functional MetaTrader 5 Expert Advisor implementing a grid trading strategy.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages