Back to Trending
RepositoryMQL5
sajidmahamud835

sajidmahamud835/grid-master-pro-mt5-ea

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

137stars
42forks
1issues
4views

Featured achievements

The project's latest awards

1
TINIX TRENDING·Topic: mql5

#1 Repository of the week

1
TINIX TRENDING·Topic: ea

#1 Repository of the week

1
TINIX TRENDING·Topic: mt5

#1 Repository of the week

🤖 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

ParameterDefaultDescription
GridModeNEUTRALNEUTRAL (both), BULLISH (buy only), BEARISH (sell only)
MaxOrders5Max open positions per side
ATRPeriod14ATR lookback period
ATRMultiplier1.5Grid spacing = ATR × multiplier

Order Settings

ParameterDefaultDescription
LotModeFIXEDFIXED or DYNAMIC (risk % per order)
LotSize0.1Fixed lot (ignored in dynamic mode)
RiskPercent1.0% of balance risked per order (dynamic mode)
DefaultTP200Minimum TP in points (auto-raised to broker minimum)
DefaultSL1000Minimum SL in points (auto-raised to broker minimum)
UseTrailingStoptrueEnable trailing stop
TrailingPoints100Trailing activation distance in points
TrailingStep20Trailing step (minimum move before update)

Risk Management

ParameterDefaultDescription
MaxDrawdownPct5.0Max equity drawdown % before pause
CloseOnDrawdowntrueClose 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
InstrumentLotSizeMaxOrdersATRMultDefaultTPDefaultSLMaxDrawdown
BTCUSD0.0152.0100050005%
EURUSD0.181.520010003%
XAUUSD0.0561.850030004%
GBPUSD0.161.620012003%

📥 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

ProjectDescription
MarketSync-EAAI-powered evolution — uses ML to decide when/where to place the grid
Slippage TrackerMonitor broker execution quality for your grid orders
WhatsApp BotTrade 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

Similar Projects

Discover other similar projects and AI models.

RepositoryMQL5
nkanven/MT4-MT5-Trading-EA-Collections

This repository is about some of my various MT4/MT5 EA you everyone can use for free. I implemented various strategies and scripts you can customize for your projects.

146
Dec 11, 2024
RepositoryMQL5
MT5-Automation-Labs/mt5-gold-scalper-ea

MT5 gold (XAUUSD) M1 scalper EAs: Z-score mean reversion plus trend breakout, with dynamic equity risk tiers, session window, spread filter and cost-aware broker-side take-profit.

135
Oct 15, 2026
RepositoryMQL5
EarnForex/Account-Protector

Automate emergency position closing and autotrading termination using a multi-setting expert advisor.

126
Feb 19, 2026
RepositoryMQL5
xxvw/ICT_Library_MQ5

ICT Concept OSS Library for MQ5/MT5

111
Oct 13, 2026
RepositoryMQL5
EarnForex/AutoTrading-Scheduler

Create simple weekly schedule for your autotrading needs in MT4 and MT5.

57
Mar 2, 2026
RepositoryC#
vdemydiuk/mtapi

MetaTrader API (terminal bridge)

711
Nov 24, 2026
RepositoryHTML
Dream-XR/MT5-Post-Trade-Insight-Reporter

AutoTrade Forex Signals: Telegram to MT5 EA 2026 Strategy

121
Nov 27, 2026
RepositoryHTML
7skooooo/mql5-systems-mirror

MQL5 Algorithmic Trading Scripts 2026 – Automated MT5 Strategies

116
Dec 2, 2026
RepositoryHTML
tharindu2028/Trade-Terminator-Closer

Best MT4 MT5 Close All Orders Script 2026 Automated Position Management

115
Nov 25, 2026