Pipsgrowth EX03011 Grid
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX03011 GoldGridMartingale_EA — grid with martingale lot multiplier and basket management, full 12-layer stack.
Overview
Pipsgrowth EX03011 is a Gold grid martingale built around a single principle: once a fresh cycle begins, the EA queues 1-6 pending stops at fixed 50-pip spacing in the chosen direction, then lets price walk the ladder. There is no per-trade stop loss on individual orders. The risk envelope is the basket itself, and the EA manages that envelope through weighted-average price targets, basket-profit percentage, a drawdown kill switch, and a margin-level emergency. If any of those trip, the entire grid is force-closed and the cycle resets to CYCLE_INACTIVE.
The cycle starts from scratch on every tick where CountOpenPositions and CountPendingOrders both return zero. OnInit enforces the symbol whitelist at startup — XAUUSD, XAUUSDm, GOLD, XAU, XAUUSD.raw, XAUUSD., or XAUUSD.i — and refuses any other symbol with an Alert and INIT_FAILED. It also warns if AccountInfoInteger(ACCOUNT_LEVERAGE) is below 1:500, since a 6-level grid with martingale scaling punishes low leverage.
Three entry modes sit behind the ENUM_ENTRY_TYPE input. ENTRY_RANDOM sets direction from tick.time parity: it reads SymbolInfoTick and computes lastRandom = (int)(tick.time % 2), then routes to the buy side if UseBuyGrid is true (and falls back to sell only if buy is disabled). The effect is buy-biased randomisation, not 50/50. ENTRY_RSI is the cleaner mode: it creates g_rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, RSI_Period=14, PRICE_CLOSE) at init, and on each cycle-check tick it reads CopyBuffer(0, 0, 2). RSI > 50 fires a buy; RSI < 50 fires a sell, with UseBuyGrid and UseSellGrid as the only filters. ENTRY_BREAKOUT calls CopyHigh and CopyLow over the last BreakoutBars=48 five-minute bars (4 hours) and fires when SymbolInfoDouble(SYMBOL_LAST) clears the highest high (buy) or breaks the lowest low (sell).
When CheckEntrySignal returns true, PlaceGridOrders walks MaxGridLevels iterations. Level 1 sits at currentPrice ± gridStepPrice (50 pips) as a BUY_STOP or SELL_STOP, level 2 at ± 2 × gridStepPrice, and so on up to MaxGridLevels=6. Lot sizing is martingale: lot = InitialLot × LotMultiplier^(level-1). With LotMultiplier=1.0 (default) the lots are flat at InitialLot=0.01. Bumping it to 1.4 turns the ladder into 0.01, 0.014, 0.0196, 0.0274, 0.0384, 0.0538 — that escalation is what the 80% drawdown ceiling is designed to absorb. CalculateLotSize also enforces a MaxTotalLots=1.0 cap, so the final lot is reduced if the running total plus the new level would exceed that ceiling. Each order goes through a 3-retry OrderOpen loop with 100ms sleeps between failures, and OrderCalcMargin is called first; if required margin > 50% of free margin, the loop breaks early.
When a stop fills, the next tick detects openPositions > 0 and sets g_cycleState = CYCLE_BUY or CYCLE_SELL. DeleteOppositePendingOrders(ORDER_TYPE_BUY) cleans up any straggling sell-side pending orders, leaving the live basket to work the average. GetBasketProfit, CalculateAveragePrice, and UpdateTrailingProfit run on every tick while the cycle is active.
The basket take-profit is dual-mode. Method 1 watches CalculateAveragePrice (a volume-weighted average of all position open prices) and closes the basket when price has moved TakeProfit=20 pips in the cycle's favor — bid for buy cycles, ask for sell cycles. Method 2 closes when basket profit as a percentage of account balance reaches BasketProfitPercent=20%. The first to fire wins, and the cycle resets.
Trailing kicks in once basket profit reaches 50% of the basket target. g_trailingActive flips true, g_maxBasketProfit is set to the current basket profit, and on every subsequent tick the EA compares the current profit to the trailing threshold (max profit minus TrailingDistance=10 pips, converted to a percentage). When profit falls back through that level, takeProfitHit is set and CloseAllPositions + DeleteAllPendingOrders runs. The trailing is in pips-of-percentage territory rather than price-pips; the 0.1 multiplier on TrailingDistance is an approximate scaling from pips to percent, intentional in the code as a rough conversion rather than a precise trailing band.
The risk stack above the basket has three independent cutoffs. The first is the margin-level emergency in OnTick: if AccountInfoDouble(ACCOUNT_MARGIN_LEVEL) is non-zero and below 100%, the EA calls CloseAllPositions + DeleteAllPendingOrders and returns immediately. The second is CheckMaxDrawdown: drawdown = (balance - equity) / balance, and if it reaches MaxDrawdownPercent=80% the same shutdown runs. The third is the MinFreeMarginPercent=20% gate inside CheckMarginLevel — when there are no positions, it blocks new cycles if free margin dips below 20% of balance; when there are positions, it blocks new cycles if margin level falls below 150%.
Daily and intraday risk are split. CheckDailyLimits compares current balance to g_dailyStartBalance; if the day's profit reaches DailyProfitTarget=100% the EA blocks new cycles, and if it hits -DailyLossLimit=-50% the same. The OnTradeTransaction handler is the bookkeeping layer: it parses HistoryDealGetInteger(DEAL_ENTRY), increments g_dailyTrades on DEAL_ENTRY_IN, accumulates g_realizedToday and g_realizedWeek on DEAL_ENTRY_OUT, and increments g_consecLossesHD on each loss. After 3 consecutive losses, g_cooldownUntil = TimeCurrent() + InpCooldownMinutes * 60 (30 minutes by default) — this is a fixed threshold in the code, not the InpHrdMaxConsecLoss input (which gates the IsSafeToTrade check at a separate, larger value). The hardening block also exposes InpEquityFloor, InpHrdDailyLoss, InpHrdWeeklyLoss, and InpCapitalCap, all of which default to 0/disabled. When InpUseGMTSessions=true (default) the EA adds a London 7-16 ∪ New York 12-21 GMT gate via InActiveSession_EX03011; outside those hours — and on Saturday/Sunday — no new cycles fire regardless of the basic StartHour=7 / EndHour=16 input.
The news filter is intentionally minimal. IsNewsTime() blocks new cycles only on the first Friday of the month between 13:00 and 15:00 (NFP window), and only when UseNewsFilter=true (default false). There is no FOMC detection, no calendar feed — a trader who wants CPI or FOMC blocking has to layer it on top. The trade comment is hard-coded to 'Psgrowth.com Expert_03011' for identification, and the magic number 22203011 isolates this EA from any others running on the same account.
OnTester ranks candidates by (profit / maxDD) × max(0, profitFactor - 1), with hard gates of trades >= 10 and maxDD > 0. This favors strategies that produce meaningful trades with low relative drawdown and a profit factor above 1.0 — the right shape for a grid EA that runs a long cycle and closes cleanly. Trade-execution retries are 3 attempts at 100-200ms on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED return codes via TryOrderDelete_EX03011 and TryClose_EX03011; everything else (insufficient margin, invalid stops, market closed) breaks out of the retry loop immediately so the EA does not hammer the broker.
Operationally, the realistic minimum is not the listed $100. A 6-level gold grid with 50-pip spacing that needs room for the basket TP to develop is going to draw down before it cycles out; $1,000-$5,000 with leverage at 1:500 or higher is the working range, and any account that cannot absorb the full 6-level martingale escalation should reduce MaxGridLevels first, then reconsider LotMultiplier. The two are independent knobs but both feed the same drawdown ceiling.
Strategy Deep Dive
On every tick OnTick first runs the safety stack: UpdateDailyCounters_EX03011 rotates daily/weekly P&L totals, then a margin-level <100% emergency calls CloseAllPositions+DeleteAllPendingOrders and returns immediately, and the same shutdown runs when CheckMaxDrawdown sees drawdown >= MaxDrawdownPercent=80%. CountOpenPositions and CountPendingOrders then classify the state — if both are zero, g_cycleState becomes CYCLE_INACTIVE and the EA evaluates IsNewCycleAllowed and IsSafeToTrade_EX03011 (London 7-16 ∪ New York 12-21 GMT sessions, weekend guard, equity floor, daily/weekly loss caps, capital cap, trades-per-day cap, and the cooldown gate from g_cooldownUntil). The CheckEntrySignal switch picks a direction based on EntryType, and PlaceGridOrders queues 1-6 BUY_STOP or SELL_STOP pending orders at PipsToPrice(GridStep=50) intervals with lot = InitialLot × LotMultiplier^(level-1) capped at MaxTotalLots=1.0, each going through a 3-retry OrderOpen loop with 100ms sleeps on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED. When a stop fills, the next tick detects openPositions > 0, sets g_cycleState, and DeleteOppositePendingOrders cleans up stragglers on the other side; GetBasketProfit, CalculateAveragePrice, and UpdateTrailingProfit then monitor the cycle until one of the dual TP conditions or the trailing-stop logic fires. OnTradeTransaction updates g_realizedToday, g_realizedWeek, g_dailyTrades, and g_consecLossesHD, and at 3 consecutive losses sets g_cooldownUntil to TimeCurrent() + 30 minutes by default. OnTester ranks candidates by (profit/maxDD) × max(0, profitFactor-1) with hard gates of trades >= 10 and maxDD > 0.
Entries are dispatched by ENUM_ENTRY_TYPE: ENTRY_RANDOM uses tick-time parity (lastRandom = (int)(tick.time % 2)) and routes to buy if UseBuyGrid is enabled, else sell — buy-biased, not 50/50. ENTRY_RSI reads g_rsiHandle (RSI_Period=14 on PRICE_CLOSE) and buys when RSI > 50, sells when RSI < 50, gated by UseBuyGrid/UseSellGrid. ENTRY_BREAKOUT compares SYMBOL_LAST to the BreakoutBars=48-bar (4-hour) high and low and fires when price clears either side. Whichever mode picks a direction, PlaceGridOrders then places 1-6 pending stops at PipsToPrice(GridStep=50) intervals above or below current price, with lot = InitialLot × LotMultiplier^(level-1) capped at MaxTotalLots=1.0.
Basket-level dual-exit. Method 1 closes when the volume-weighted average price moves TakeProfit=20 pips in the cycle's favor (bid for buy cycles, ask for sell cycles). Method 2 closes when basket profit as a percent of account balance reaches BasketProfitPercent=20%. Trailing activates once basket profit reaches 50% of the basket target, locking in via g_maxBasketProfit and TrailingDistance=10 pips. The OnTradeTransaction handler tracks g_consecLossesHD; after 3 consecutive losses, g_cooldownUntil = TimeCurrent() + InpCooldownMinutes*60 (30 min by default) blocks new cycles even after the basket closes.
No per-trade stop loss. Risk control is the basket: MaxDrawdownPercent=80% (drawdown = (balance-equity)/balance) triggers full shutdown via CloseAllPositions+DeleteAllPendingOrders, and an emergency margin-level cutoff fires if ACCOUNT_MARGIN_LEVEL < 100%. MinFreeMarginPercent=20% blocks new cycles when free margin drops too low, and the per-cycle MaxTotalLots=1.0 cap prevents single-cycle lot escalation from breaching the broker's exposure limits.
Dual-mode basket TP. Method 1 closes when weighted-average price moves TakeProfit=20 pips in the cycle's favor (bid for buy, ask for sell). Method 2 closes when basket profit as % of balance reaches BasketProfitPercent=20%. Trailing activates at 50% of basket target via UpdateTrailingProfit, then ratchets via g_maxBasketProfit minus TrailingDistance=10 pips. Whichever fires first wins, and the cycle resets to CYCLE_INACTIVE with all positions and pending orders cleared.
Gold/XAUUSD only — the OnInit symbol whitelist refuses any other symbol. M5 timeframe; the 50-pip grid spacing on 5-minute bars means cycles develop over 4-12 hours. Recommended balance $1,000-$5,000 with leverage >= 1:500, even though the listing shows $100 — a 6-level martingale grid needs capital to absorb the 80% drawdown ceiling. London 7-16 GMT and New York 12-21 GMT overlap (InpUseGMTSessions=true, no Sat/Sun); outside that window no new cycles fire regardless of the basic 7-16 input. ECN/RAW broker with deep liquidity required, ORDER_FILLING_FOK, 50-point deviation, and MaxSpread=30 pips tolerance. Run LotMultiplier=1.0 (flat) on a small account first; only scale 1.3-1.5 once the basket TP cadence is visible in your backtest, and reduce MaxGridLevels from 6 to 4 before raising the multiplier on a sub-$2,000 account.
Strategy Logic
Pipsgrowth EX03011 Grid — Strategy Logic Analysis (from .mq5 source)
Family: Grid
Magic: 22203011
Version: 2.00
BRIEF:
Gold grid martingale EA that places grid orders at fixed step intervals with lot multiplier, supporting random, RSI, or breakout entry methods. Includes basket TP, trailing, and drawdown protection with daily profit/loss limits. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
IsNewCycleAllowed()CheckEntrySignal()PlaceGridOrders()CloseAllPositions()DeleteAllPendingOrders()DeleteOppositePendingOrders()CountOpenPositions()CountPendingOrders()CalculateAveragePrice()GetBasketProfit()GetTotalLotSize()CheckMarginLevel()- ...and 18 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (30 total across 9 groups):
- [===
GRIDSETTINGS===]GridStep= 50 // Grid step distance (pips) - [===
GRIDSETTINGS===]MaxGridLevels= 6 // Maximum grid levels - [===
GRIDSETTINGS===]UseBuyGrid=true// Enable buy side grid - [===
GRIDSETTINGS===]UseSellGrid=true// Enable sell side grid - [===
MARTINGALESETTINGS===]InitialLot=0.01// Initial lot size - [===
MARTINGALESETTINGS===]LotMultiplier=1.0// Lot size multiplier (1.0= disabled) - [===
MARTINGALESETTINGS===]UseDynamicLots=false// Calculate lots based on balance - [===
PROFIT&LOSSSETTINGS===]TakeProfit= 20 // Take profit (pips from average) - [===
PROFIT&LOSSSETTINGS===]BasketProfitPercent=20.0// OR close at profit % of account - [===
PROFIT&LOSSSETTINGS===]MaxDrawdownPercent=80.0// Maximum drawdown before force close - [===
PROFIT&LOSSSETTINGS===]TrailingDistance= 10 // Trail profit by pips (0 = disabled) - [===
ENTRYSETTINGS===]EntryType=ENTRY_RANDOM// Entry method - [===
ENTRYSETTINGS===] RSI_Period = 14 //RSIperiod (if usingRSIentry) - [===
ENTRYSETTINGS===]BreakoutBars= 48 // Lookback bars for breakout (4H = 48x5min) - [===
TIMEFILTERS===]StartHour= 7 // Trading start hour (GMT) - [===
TIMEFILTERS===]EndHour= 16 // Trading end hour (GMT) - [===
TIMEFILTERS===]TradeMonday=true// Trade on Monday - [===
TIMEFILTERS===]TradeTuesday=true// Trade on Tuesday - [===
TIMEFILTERS===]TradeWednesday=true// Trade on Wednesday - [===
TIMEFILTERS===]TradeThursday=true// Trade on Thursday - [===
TIMEFILTERS===]TradeFriday=true// Trade on Friday - [===
RISKMANAGEMENT===]MaxSpread= 30 // Maximum spread (pips) - [===
RISKMANAGEMENT===]MaxTotalLots=1.0// Maximum total lot size - [===
RISKMANAGEMENT===]MinFreeMarginPercent=20.0// Minimum free margin percentage - [===
OPTIONALFEATURES===]UseNewsFilter=false// Enable news filter - [===
OPTIONALFEATURES===]DailyProfitTarget=100.0// Daily profit target % (0 = disabled) - [===
OPTIONALFEATURES===]DailyLossLimit=50.0// Daily loss limit % (0 = disabled) - [===
GENERALSETTINGS===]MagicNumber=22203011// Magic number forEAtrades - [===
GENERALSETTINGS===]InpTradeComment= "Psgrowth.com Expert_03011" // Trade comment - [=== Hardening Trade Safety ===]
InpHrdMaxConsecLoss= 0 // +------------------------------------------------------------------+
// Pipsgrowth EX03011 Grid — Execution Flow (from source analysis)
// Family: Grid
// Gold grid martingale EA that places grid orders at fixed step intervals with lot multiplier, supporting random, RSI, or breakout entry methods. Includes basket TP, trailing, and drawdown protection with daily profit/loss limits. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: standard set
Initialize state variables
Detect broker GMT offset
ON_TICK:
1. Refresh indicator buffers (closed-bar shift=1)
2. Manage existing positions:
- Break-even check
- ATR trailing stop
- Profit lock ratchet
- Time-based exit
- Opposite-signal exit
3. If new bar:
a. ClassifyRegime() — ADX/ATR/BB regime detection
b. NoTradeGate() checks:
- Market open + session filter
- Spread limit
- Cooldown after loss
- Consecutive loss limit
- Kill switch
- Max drawdown
- Max concurrent positions
- Daily/weekly loss limits
c. GenerateSignal() — strategy-specific entry logic
d. CheckConfirm() — HTF alignment + R:R + ADX minimum
e. Calculate position size from risk %
f. Execute with retry logic
g. Mark bar to prevent duplicates
ON_TESTER:
Custom fitness = weighted(RecoveryFactor, ROI, ProfitFactor, TradeCount, Sharpe, Drawdown)Optimization Profile
How to Install This EA on MT5
- 1Download the .mq5 file using the button above
- 2Open MetaTrader 5 on your computer
- 3Click File → Open Data Folder in the top menu
- 4Navigate to MQL5 → Experts and paste the .mq5 file there
- 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
- 6Drag the EA onto a chart — H1 or H4 is recommended for grid EAs
- 7Set grid step (pips), maximum orders, and lot size in the EA dialog
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| GridStep | 50 | Grid step distance (pips) |
| MaxGridLevels | 6 | Maximum grid levels |
| UseBuyGrid | true | Enable buy side grid |
| UseSellGrid | true | Enable sell side grid |
| InitialLot | 0.01 | Initial lot size |
| LotMultiplier | 1.0 | Lot size multiplier (1.0 = disabled) |
| UseDynamicLots | false | Calculate lots based on balance |
| TakeProfit | 20 | Take profit (pips from average) |
| BasketProfitPercent | 20.0 | OR close at profit % of account |
| MaxDrawdownPercent | 80.0 | Maximum drawdown before force close |
| TrailingDistance | 10 | Trail profit by pips (0 = disabled) |
| EntryType | ENTRY_RANDOM | Entry method |
| RSI_Period | 14 | RSI period (if using RSI entry) |
| BreakoutBars | 48 | Lookback bars for breakout (4H = 48x5min) |
| StartHour | 7 | Trading start hour (GMT) |
| EndHour | 16 | Trading end hour (GMT) |
| TradeMonday | true | Trade on Monday |
| TradeTuesday | true | Trade on Tuesday |
| TradeWednesday | true | Trade on Wednesday |
| TradeThursday | true | Trade on Thursday |
| TradeFriday | true | Trade on Friday |
| MaxSpread | 30 | Maximum spread (pips) |
| MaxTotalLots | 1.0 | Maximum total lot size |
| MinFreeMarginPercent | 20.0 | Minimum free margin percentage |
| UseNewsFilter | false | Enable news filter |
| DailyProfitTarget | 100.0 | Daily profit target % (0 = disabled) |
| DailyLossLimit | 50.0 | Daily loss limit % (0 = disabled) |
| MagicNumber | 22203011 | Magic number for EA trades |
| InpTradeComment | "Psgrowth.com Expert_03011" | Trade comment |
| InpHrdMaxConsecLoss | 0 | +------------------------------------------------------------------+ |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX03011 GoldGridMartingale_EA — grid with martingale lot multiplier and basket management, full 12-layer stack."
#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>
#include <Trade/OrderInfo.mqh>
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| ENUMERATIONS |
//+------------------------------------------------------------------+
enum ENUM_ENTRY_TYPE
{
ENTRY_RANDOM = 0, // Random Entry (Simple)
ENTRY_RSI = 1, // RSI-Based Entry
ENTRY_BREAKOUT = 2 // Breakout Entry
};
enum ENUM_CYCLE_STATE
{
CYCLE_INACTIVE = 0, // No active cycle
CYCLE_BUY = 1, // Buy cycle active
CYCLE_SELL = 2 // Sell cycle active
};
//+------------------------------------------------------------------+
//| INPUT PARAMETERS |
//+------------------------------------------------------------------+
//--- Grid Settings
input group "=== GRID SETTINGS ==="
input int GridStep = 50; // Grid step distance (pips)
input int MaxGridLevels = 6; // Maximum grid levels
input bool UseBuyGrid = true; // Enable buy side grid
input bool UseSellGrid = true; // Enable sell side grid
//--- Martingale Settings
input group "=== MARTINGALE SETTINGS ==="
input double InitialLot = 0.01; // Initial lot size
input double LotMultiplier = 1.0; // Lot size multiplier (1.0 = disabled)
input bool UseDynamicLots = false; // Calculate lots based on balance
//--- Profit & Loss Settings
input group "=== PROFIT & LOSS SETTINGS ==="
input int TakeProfit = 20; // Take profit (pips from average)
input double BasketProfitPercent = 20.0; // OR close at profit % of account
input double MaxDrawdownPercent = 80.0; // Maximum drawdown before force close
input int TrailingDistance = 10; // Trail profit by pips (0 = disabled)
//--- Entry Settings
input group "=== ENTRY SETTINGS ==="
input ENUM_ENTRY_TYPE EntryType = ENTRY_RANDOM; // Entry method
input int RSI_Period = 14; // RSI period (if using RSI entry)
input int BreakoutBars = 48; // Lookback bars for breakout (4H = 48x5min)
//--- Time Filters
input group "=== TIME FILTERS ==="Full source code available on download
Educational purposes only. Do NOT use with real money. Test on demo accounts only.
Clear Warning: Educational Purposes Only
Clear Warning: This Expert Advisor is for educational and testing purposes only. Do NOT use it with real money. Test only on demo accounts. Trading with real money involves substantial risk of capital loss. This does not constitute investment advice.
Recommended Brokers for This EA
These EAs run on MT5 — use a regulated broker with fast execution and tight spreads
Markets.com
Exness
IC Markets
Similar Expert Advisors
View All Expert AdvisorsMore Grid strategy EAs from our library
Pipsgrowth EX03022 Grid
Pipsgrowth.com EX03022 HedgingGridEA — hedging + grid recovery, full 12-layer stack.
Pipsgrowth EX03027 Grid
Pipsgrowth.com EX03027 Gold_EMA_SuperTrend — EMA crossover + SuperTrend pyramid scalper, full 12-layer stack.
Pipsgrowth EX03021 Grid
Pipsgrowth.com EX03021 GridXPro — grid with optional martingale for major pairs, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.