Pipsgrowth EX03003 Grid
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX03003 AdvancedGrid_XAUUSD_5M — pure hedged grid with lot multiplier and basket TP, full 12-layer stack.
Overview
Pipsgrowth EX03003 Grid is a pure hedged grid system for XAUUSD on the five-minute chart. There is no indicator stack feeding a signal — the entry logic is mechanical and price-driven. The EA opens a paired Buy and Sell at the start of every cycle, then watches each side as a separate basket, adding a fresh layer every time price moves one grid step against the most recent entry on that side. The basket is closed as a unit when the average price of that side moves InpTakeProfit points back in the EA's favor. Two baskets means two independent profit-and-loss engines running side by side, and only the side that survives a sustained move against it ends up doing the heavy averaging.
The whole architecture is built around a single function — ManageBasket() — which is invoked from OnTick() for POSITION_TYPE_BUY and again for POSITION_TYPE_SELL. On every tick, it walks the open positions in reverse, filtering by symbol, magic, and type, accumulating a volume-weighted average price and tracking the price of the last added position. If the count is zero or the basket is empty, the function exits early. Otherwise it computes avgPrice /= totalVol and then runs two checks. The first check is the basket take-profit: for Buy baskets it asks whether mysymbol.Bid() > avgPrice + InpTakeProfit * mysymbol.Point(). If yes, CloseAll(POSITION_TYPE_BUY) is called and the basket is flattened. The same logic inverts for the Sell basket, where the trigger is mysymbol.Ask() < avgPrice - InpTakeProfit * mysymbol.Point(). The second check is the grid-add: if the existing count is below InpMaxLayers, the function calculates the next lot as NormalizeDouble(InpInitialLot * MathPow(InpMultiplier, count), 2), snaps it to the broker's lot step with MathRound(newLot / step) * step, and floors it to mysymbol.LotsMin(). The new layer is then opened only if price has moved one full InpGridStep away from the most recent entry on that side.
The lot multiplier is the single most consequential input. With InpMultiplier = 1.0 (the default) the EA is a fixed-lot grid — every layer costs the same as the first, and the worst-case exposure grows linearly with layer count. With InpMultiplier = 1.5 the second layer is 1.5× the first, the third is 2.25×, and by layer ten the notional has grown by a factor of 57.7. A 2.0 multiplier is full Martingale and explodes the capital requirement after just a few layers; a 1.2 multiplier is a soft progression that most prop-firm challenges can survive but that still accelerates losses on a sustained trend. The default 200-point grid step (20 pips on a 5-digit gold broker) gives roughly 50 points of buffer between any two layers, but on a 5-minute chart that distance is regularly cleared by single candles during London or New York opens. The 400-point basket TP means each basket targets 40 pips of average-price recovery before it cashes out — a tight target that works well in oscillation and gets shredded by one-directional sessions.
The session layer in this EA is not just a precaution — it is the only reason the grid survives long enough to be useful. InpUseGMTSessions defaults to true, and the active window is the union of London (07:00–16:00 GMT) and New York (12:00–21:00 GMT). The InActiveSession_EX03003() function converts server time to GMT via ServerToGMT_EX03003() (which subtracts the auto-detected offset from DetectGMTOffset_EX03003(), a best-of heuristic that scores -12 to +12 by weekday and hour), then tests the resulting hour against both windows and rejects weekends outright. Outside the union of those two windows the EA simply does not start a new basket. This is critical for XAUUSD: the Asian session routinely produces 100-to-200-pip one-directional moves that will pile up six or seven losing layers on the wrong side before New York opens, and the resulting floating drawdown is the standard failure mode of this kind of grid.
The safety stack is layered in IsSafeToTrade_EX03003(). New basket starts are blocked when the GMT session is closed, when g_cooldownUntil is in the future, when the equity floor InpEquityFloor has been breached, when realized daily losses exceed InpDailyLossLimit, when realized weekly losses exceed InpWeeklyLossLimit, when the balance has reached or exceeded the InpCapitalCap, when the daily trade counter g_dailyTrades has hit InpMaxTradesPerDay, or when g_consecLosses has reached InpMaxConsecLosses. The cooldown itself is wired into OnTradeTransaction(): every time a deal closes with a loss, g_consecLosses increments, and when it reaches three the system sets g_cooldownUntil = TimeCurrent() + InpCooldownMinutes * 60. The next basket start is then blocked for the configured window — 30 minutes by default. A win resets the counter to zero. The trade-transaction hook also updates g_realizedToday and g_realizedWeek using profit plus swap plus commission, which is what the daily and weekly loss checks actually compare against.
The optional time filter InpTimeFilter (default false) is a server-time gate with a string-based start and end. The CheckTime() function pulls the current hour and minute into a StringFormat("%02d:%02d", ...) and compares against InpStartTime and InpEndTime (defaults "08:00" and "20:00"). When InpTimeFilter is off, the gate is permissive. This is a coarse filter, and the GMT session gate is the more reliable mechanism — but it can be useful for traders who want to constrain the EA to a specific clock window that does not align with the default London-New York overlap.
Execution is straight-through via the standard CTrade wrapper. TryBuy_EX03003(), TrySell_EX03003(), and TryClose_EX03003() each validate the lot against the broker's SYMBOL_VOLUME_MIN, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_STEP (using MathFloor(lots / step) * step), call OrderCalcMargin to make sure the account has free margin, and then attempt the order up to three times with a 200ms sleep on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, TRADE_RETCODE_PRICE_OFF, or TRADE_RETCODE_PRICE_CHANGED. The filling mode is ORDER_FILLING_FOK (set in OnInit()) and the slippage is InpSlippage = 3 points. OnInit() also enforces the four sanity checks that the rest of the EA assumes: InpInitialLot >= SYMBOL_VOLUME_MIN, InpGridStep > 0, InpMaxLayers >= 1, and InpMaxSpread > 0. If any of these fail, the EA refuses to start with INIT_FAILED and prints a config error message.
OnTester() returns (profit / maxDD) * (pf > 1 ? pf : 0), gated on maxDD > 0 and trades >= 10. Strategies that bleed slowly into a max-DD tail but still net positive get penalized heavily; strategies that print low-trade-but-high-edge curves get rewarded. The function is a pure fitness score — it does not change the live behavior at all — but the Strategy Tester uses it to rank optimization passes, so the EA's parameter tuning will gravitate toward settings that combine positive net with controlled drawdown and a profit factor above one.
What the trader is actually running is two simultaneous martingale-style baskets, one long and one short, with independently managed averaging and a per-basket recovery target. The default configuration assumes a 200-point (20-pip) step and 400-point (40-pip) basket TP — which is a tight range that will produce many small wins in sideways sessions and occasional large drawdowns in trending ones. The capital profile is exactly what the inputs suggest: with InpMaxLayers = 10 and InpMultiplier = 1.0, the worst-case net exposure on either side is 0.10 lots at an average price that is 1,000 points (100 pips) below the worst entry; with InpMultiplier = 1.5 the same scenario compounds to 1.14 lots and a margin requirement that grows with the cube of the move. The EA is honest about this: there is no recovery algorithm, no martingale cap, no insurance hedge — the safety comes from session gates, cooldown, and the user's own discipline on the multiplier and max-layers inputs.
Strategy Deep Dive
On every tick, OnTick() refreshes the symbol and bails if mysymbol.Spread() > InpMaxSpread. UpdateDailyCounters_EX03003() rolls the daily and weekly P&L buckets when the server day or week changes. ManageBasket() is then called twice — once for POSITION_TYPE_BUY, once for POSITION_TYPE_SELL — and each call walks the open positions in reverse, accumulates a volume-weighted average price, finds the price of the most recent layer, and decides between two outcomes: close the entire basket if price has moved InpTakeProfit points past the average in the EA's favor, or open a new layer if price has moved InpGridStep points past the last entry in the wrong direction and the count is below InpMaxLayers. The first action of a brand-new cycle — when PositionsTotal() == 0 and CheckTime() is satisfied — is to fire both TryBuy_EX03003() and TrySell_EX03003() at InpInitialLot to seed the two baskets. The session gate in InActiveSession_EX03003() is enforced before any new basket can start, and the trade-transaction hook tracks realized P&L plus consecutive losses to drive the 30-minute cooldown that fires after the third loss in a row.
A new basket starts when no positions of either type are open for the EA's magic on the symbol. The first action is to open one Buy and one Sell simultaneously at InpInitialLot (default 0.01) using TryBuy_EX03003() and TrySell_EX03003(). From that point on, additional layers are added by ManageBasket(): a new layer opens on a side only when price has moved one full InpGridStep (default 200 points / 20 pips) beyond the most recent entry on that side, and the lot for layer N is InpInitialLot * MathPow(InpMultiplier, N-1), snapped to the broker's lot step. A new layer can only be added if the existing count on that side is below InpMaxLayers (default 10), the spread is below InpMaxSpread (250 points), the GMT session is active, and IsSafeToTrade_EX03003() returns true.
The exit is per-basket, not per-trade. For the Buy basket, ManageBasket() checks mysymbol.Bid() > avgPrice + InpTakeProfit * mysymbol.Point() on every tick; for the Sell basket it checks mysymbol.Ask() < avgPrice - InpTakeProfit * mysymbol.Point(). When the condition is true, CloseAll(type) walks the positions for that side in reverse and closes each via TryClose_EX03003() (3 retries at 200ms on requote/timeout/price-off/price-changed). A win in the trade-transaction hook resets g_consecLosses to zero; a loss increments it. After three consecutive losses, g_cooldownUntil is set to TimeCurrent() + InpCooldownMinutes * 60 (30 minutes default), and any new basket start is blocked until the cooldown expires.
There is no per-trade stop-loss on grid layers — every layer enters with sl=0 and tp=0 in TryBuy_EX03003/TrySell_EX03003. Risk control is global: InpMaxLayers (default 10) caps the number of averaging entries on each side, and the safety stack in IsSafeToTrade_EX03003() halts new basket starts when equity breaches InpEquityFloor, when daily realized losses exceed InpDailyLossLimit, or when weekly realized losses exceed InpWeeklyLossLimit. A 30-minute cooldown (default InpCooldownMinutes) fires after three consecutive losses via OnTradeTransaction().
The take-profit is per-basket, not per-trade, and is the average-price recovery of the side. InpTakeProfit (default 400 points / 40 pips) is the distance in points from the volume-weighted average price. The Buy basket closes when bid >= avgPrice + InpTakeProfit * Point; the Sell basket closes when ask <= avgPrice - InpTakeProfit * Point. The check runs on every tick from ManageBasket() and triggers CloseAll(type) when the condition is met. There is no per-trade TP — every individual layer is opened with tp=0 and exits only when the basket as a whole reaches its recovery target.
Built for XAUUSD on the M5 timeframe with the high-spread, high-volatility profile of gold spot. The 200-point grid step and 400-point basket TP (defaults) match a typical 20–40 pip oscillation range that shows up in London and New York sessions. Use a low-spread ECN or RAW-spread broker with sub-pip commissions, and run on a VPS with low latency to the broker — every layer is opened in response to a 20-pip adverse move, and requotes during volatile opens will compound. Minimum recommended balance: $100 per 0.01-lot layer, with the assumption that InpMultiplier stays at 1.0; any move above 1.0 scales capital requirements sharply. Best for traders who understand that a hedged grid with 10 layers per side and 40-pip recovery is a high-risk, range-bound strategy that will fail on a one-directional news session — pair it with strict discipline on InpMaxLayers, InpMultiplier, and the daily and weekly loss limits. Risk level: VERY HIGH.
Strategy Logic
Pipsgrowth EX03003 Grid — Strategy Logic Analysis (from .mq5 source)
Family: Grid
Magic: 22203003
Version: 2.00
BRIEF:
Pure grid EA that opens hedged Buy and Sell positions, adds grid layers at fixed step intervals with lot multiplier, and closes the basket when average price reaches take profit. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
ManageBasket()CloseAll()CheckTime()DetectGMTOffset_EX03003()ServerToGMT_EX03003()InActiveSession_EX03003()UpdateDailyCounters_EX03003()IsSafeToTrade_EX03003()TryBuy_EX03003()TrySell_EX03003()TryClose_EX03003()OnTradeTransaction()
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (13 total across 5 groups):
- [=== Grid Settings ===]
InpGridStep= 200 // GridStep(points) - [=== Grid Settings ===]
InpMultiplier=1.0// LotMultiplier(1.0= Fixed, >1.0= Martingale) - [=== Grid Settings ===]
InpMaxLayers= 10 // Max Layers per Side - [=== Money Management ===]
InpInitialLot=0.01// Initial Lot Size - [=== Money Management ===]
InpTakeProfit= 400 // TakeProfit(points) - Global Average? - [=== Trade Management ===]
InpMagicNumber=22203003// Magic Number - [=== Trade Management ===]
InpTradeComment= "Psgrowth.com Expert_03003" // TradeComment - [=== Trade Management ===]
InpMaxSpread= 250 // MaxSpread(points) - [=== Trade Management ===]
InpSlippage= 3 // Slippage - [=== Filters ===]
InpTimeFilter=false// Use Time Filter? - [=== Filters ===]
InpStartTime= "08:00" // Start Time - [=== Filters ===]
InpEndTime= "20:00" // End Time - [=== Hardening Trade Safety ===]
InpMaxConsecLosses= 0 // --- Hardening Globals
// Pipsgrowth EX03003 Grid — Execution Flow (from source analysis)
// Family: Grid
// Pure grid EA that opens hedged Buy and Sell positions, adds grid layers at fixed step intervals with lot multiplier, and closes the basket when average price reaches take profit. 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 |
|---|---|---|
| InpGridStep | 200 | Grid Step (points) |
| InpMultiplier | 1.0 | Lot Multiplier (1.0 = Fixed, >1.0 = Martingale) |
| InpMaxLayers | 10 | Max Layers per Side |
| InpInitialLot | 0.01 | Initial Lot Size |
| InpTakeProfit | 400 | Take Profit (points) - Global Average? |
| InpMagicNumber | 22203003 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_03003" | Trade Comment |
| InpMaxSpread | 250 | Max Spread (points) |
| InpSlippage | 3 | Slippage |
| InpTimeFilter | false | Use Time Filter? |
| InpStartTime | "08:00" | Start Time |
| InpEndTime | "20:00" | End Time |
| InpMaxConsecLosses | 0 | --- Hardening Globals |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX03003 AdvancedGrid_XAUUSD_5M — pure hedged grid with lot multiplier and basket TP, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
CTrade trade;
CPositionInfo position;
CSymbolInfo mysymbol;
CAccountInfo account;
//--- Input Groups
input group "=== Grid Settings ==="
input int InpGridStep = 200; // Grid Step (points)
input double InpMultiplier = 1.0; // Lot Multiplier (1.0 = Fixed, >1.0 = Martingale)
input int InpMaxLayers = 10; // Max Layers per Side
input group "=== Money Management ==="
input double InpInitialLot = 0.01; // Initial Lot Size
input int InpTakeProfit = 400; // Take Profit (points) - Global Average?
// Let's use Per-Basket TP logic (Avg Price + TP).
input group "=== Trade Management ==="
input int InpMagicNumber = 22203003; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_03003"; // Trade Comment
input int InpMaxSpread = 250; // Max Spread (points)
input int InpSlippage = 3; // Slippage
input group "=== Filters ==="
input bool InpTimeFilter = false; // Use Time Filter?
input string InpStartTime = "08:00"; // Start Time
input string InpEndTime = "20:00"; // End Time
input group "=== Hardening GMT Sessions ==="
input bool InpUseGMTSessions = true;
input int InpLondonStartGMT = 7;
input int InpLondonEndGMT = 16;
input int InpNewYorkStartGMT = 12;
input int InpNewYorkEndGMT = 21;
input group "=== Hardening Capital Protection ==="
input double InpEquityFloor = 0.0;
input double InpDailyLossLimit = 0.0;
input double InpWeeklyLossLimit = 0.0;
input double InpCapitalCap = 0.0;
input group "=== Hardening Trade Safety ==="
input int InpMaxTradesPerDay = 50;
input int InpCooldownMinutes = 30;
input int InpMaxConsecLosses = 0;
//--- Hardening Globals
double g_realizedToday = 0;
double g_realizedWeek = 0;
datetime g_dayStartTime = 0;
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 EX03026 Grid
Pipsgrowth.com EX03026 USDJPY_Aggressive_Pyramid — MTF Hull MA pyramid with regime detection, full 12-layer stack.
Pipsgrowth EX03001 Grid
Pipsgrowth.com EX03001 Thanos Grid Adaptive — bidirectional ATR-spaced stop-order grid, full 12-layer stack.
Pipsgrowth EX03020 Grid
Pipsgrowth.com EX03020 GridScalperMA — dynamic grid with MA trend filter, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.