Pipsgrowth EX03023 Grid
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX03023 XAUUSDGridStrategy — layered grid with basket profit close, full 12-layer stack.
Overview
Pipsgrowth EX03023 is a price-step grid EA built for XAUUSD on the M5 timeframe (it also works on H1). It does not read any technical indicator, does not compute a regime score, and does not wait for a moving-average cross or a momentum threshold. Every decision is mechanical: it arms a fixed ladder of pending limit orders at 50-point intervals from the entry anchor, lets the market decide which orders fill, and exits the entire basket the moment the unrealized aggregate crosses a single threshold. That narrowness is the point — there is no model to recalibrate, no volatility filter to fight, and no signal ambiguity. Either the grid is armed and waiting or it is closed and idle.
The arming logic lives in OnTick(). On every tick the EA first runs a hard drawdown guard: it computes (balance - equity) / balance * 100 and, if the result exceeds InpMaxDrawdown (20% by default), calls CloseAllTrades() and returns. That is the EA's panic stop — once a 20% peak-to-trough excursion is observed on the live account, the basket is force-flattened and every pending order is deleted in the same pass. After the DD guard, the EA checks the live spread with SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) and aborts the rest of the tick if the spread is above InpMaxSpread (50 points). Then IsSafeToTrade_EX03023() validates session, cooldown timer, equity floor, daily/weekly realized loss, capital cap, max trades per day, and consecutive loss count before any new logic runs.
If the basket is still alive, the EA evaluates the close condition. GetBasketProfit() walks PositionsTotal() from newest to oldest and sums the profit, swap, and commission of every position whose magic number is InpMagicNumber (22203023) and whose symbol matches the chart. When CountOpenTrades() > 0 and that aggregate is greater than or equal to InpTakeProfit * _Point * InpGridLevels * InpLotSize * 100, the EA calls CloseAllTrades(), flips gridInitialised to false, and waits for a fresh cycle. With the default InpTakeProfit=100, InpGridLevels=5, InpLotSize=0.01, the close threshold for XAUUSD works out to roughly $0.50 of combined floating profit across the basket — a small, repeatable target designed to be hit often rather than heroically.
If no positions are open and gridInitialised is false, the EA captures the current ask and bid, stores them in gridBuyBase and gridSellBase, and sets gridInitialised = true. It then calls OpenBuyGrid(), which places InpGridLevels BuyLimit orders stepping down from gridBuyBase at InpGridStep * _Point intervals. With the default step of 50 points on XAUUSD, that produces five BuyLimits at approximately -0.00, -0.50, -1.00, -1.50, -2.00 USD relative to the anchor. The anchor is the ask at the moment the basket opens, so the first level is at or inside the spread and typically fills immediately, turning into the seed position; the rest queue below as price pulls back. Each order is sent through TryBuyLimit_EX03023, which retries up to three times on REQUOTE or TIMEOUT with a 200ms sleep between attempts before giving up.
If InpBothDirections is set to true, the EA additionally calls OpenSellGrid(), which mirrors the same ladder upward from gridSellBase — five SellLimits stepping up at 50-point intervals. With the default of false, only the buy ladder arms. That is the EA's directional knob: a single boolean that turns a one-sided buy-grid into a symmetric two-sided grid.
There are no per-trade stop losses and no per-trade take profits. Every level enters at the same size (InpLotSize = 0.01) and exits only when the basket is force-closed. The two ways the basket can close are: (1) the profit threshold is reached — CloseAllTrades() runs, the EA cancels all pending orders, resets gridInitialised, and the cycle restarts on the next zero-position tick; or (2) the drawdown guard fires and the EA flattens everything immediately.
OnTradeTransaction() is the only piece of the EA that updates state outside OnTick(). When a deal is added with the matching magic and symbol, it bumps g_dailyTrades on entries, accumulates realized P&L into g_realizedToday and g_realizedWeek on exits, and increments g_consecLossesHD on losses. If three consecutive losses stack up, the EA sets g_cooldownUntil = TimeCurrent() + InpCooldownMinutes * 60 (default 30 minutes) and refuses new entries until the timer expires. This is a hardcoded trigger count of 3 — the user-facing InpMaxConsecLosses (default 0, disabled) is a separate guard read by IsSafeToTrade_EX03023() that triggers at whatever threshold the user sets; the 30-minute cooldown is the EA's built-in safety floor.
The session filter uses DetectGMTOffset_EX03023() to auto-pick a GMT offset between -12 and +12 by scoring candidate offsets on weekday validity and trading-hour range, then walks the local server time through that offset. InActiveSession_EX03023() blocks weekends entirely, then returns true for any hour between InpLondonStartGMT (7) and InpLondonEndGMT (16) and any hour between InpNewYorkStartGMT (12) and InpNewYorkEndGMT (21). With InpUseGMTSessions set to true, the EA only operates inside the union of those two windows — a tight, liquid band that captures the bulk of XAUUSD's volume without spending server time on dead Asian hours when gold's typical daily range is still forming.
OnTester() returns (profit / maxDD) * (pf > 1 ? pf : 0) and gates the result on maxDD > 0 and trades >= 10, so optimization prefers robust E/R profiles that survive at least ten resolved cycles and have a profit factor above 1. With the small basket-TP target of $0.50, the typical strategy tester run will close dozens of baskets across a multi-year backtest, which gives the metric enough samples to differentiate parameter sets without overfitting to a single trade.
In practice this means the EA produces frequent, small wins (closed baskets) interrupted by occasional, larger losing cycles (drawdown-driven flattenings). The InpMaxDrawdown knob is the real risk dial: lowering it to 10% shortens losing cycles but raises the risk of being whipsawed out of a recovery, while leaving it at 20% gives baskets more room to mean-revert at the cost of deeper peak-to-trough excursions. The grid step and lot size together determine how many lots are exposed if every level fills before the basket resolves — at 5 levels × 0.01, that is 0.05 lots of XAUUSD running against the trend during a sustained move, with no protective stops on individual legs. This EA is not a system for traders who require per-trade stop losses. It is a structure for traders who think in baskets, accept the risk profile of a non-stopped grid, and want every decision in the code to be visible without wading through indicator plumbing.
Two practical notes before deployment. First, the InpMaxSpread filter of 50 points is sized for XAUUSD's typical 15–30 point spread on a low-cost broker; widening it will let the EA run on noisier venues but exposes it to slippage on entry. Tightening it below 20 will block the EA from arming the grid during the volatile first minutes of the London open. Second, the basket profit threshold scales with InpTakeProfit * InpGridLevels * InpLotSize * 100, so any combination that preserves the product — for example InpTakeProfit=200, InpGridLevels=5, InpLotSize=0.01 — produces a $1.00 target basket, while halving any one of them halves the target. The four-quadrant relationship is the only dial that matters for tuning win rate vs. win size, and it is intentionally exposed.
Strategy Deep Dive
On every tick the EA runs a peak-to-trough drawdown guard against the live account; if (balance - equity) / balance * 100 exceeds InpMaxDrawdown (20%), CloseAllTrades() flattens positions and deletes pending orders in a single pass. After the guard, the spread filter (50 points) and IsSafeToTrade_EX03023() validate the trading window: session, cooldown timer, equity floor, daily/weekly loss, capital cap, max trades per day, and consecutive-loss count. With the basket still alive and the spread clean, GetBasketProfit() sums profit + swap + commission across all positions matching magic 22203023 and the chart symbol; if that aggregate crosses InpTakeProfit * _Point * InpGridLevels * InpLotSize * 100 the basket is force-closed and the cycle restarts. When the position count is zero, the EA captures the current ask/bid as the grid anchor, sets gridInitialised = true, and arms the buy ladder (and optionally the sell ladder) at 50-point intervals. OnTradeTransaction() updates realized P&L, daily trade count, and the consecutive-loss counter; three stacked losses trigger a hardcoded 30-minute cooldown via g_cooldownUntil.
Arms a fixed ladder of BuyLimit orders stepping down from the current ask in 50-point intervals (default 5 levels at 0.01 lots each). If InpBothDirections is true, also arms a mirrored SellLimit ladder stepping up from the bid at the same step and size. No indicators, no signal — the grid is mechanical.
Closes the entire basket (positions + pending orders) the moment aggregate floating profit ≥ InpTakeProfit * _Point * InpGridLevels * InpLotSize * 100. With defaults, that's roughly $0.50 across the XAUUSD basket. There are no per-trade stops or targets — exit is basket-level only.
No per-trade stop loss. A global drawdown guard monitors (balance - equity) / balance * 100 on every tick; if it exceeds InpMaxDrawdown (default 20%), the EA calls CloseAllTrades() and flattens everything. This is the only stop in the system.
Basket profit target only: InpTakeProfit * _Point * InpGridLevels * InpLotSize * 100 points × lot value, default ~$0.50 across 0.05 lots. No per-trade TP. The basket re-arms automatically after a successful close once a new zero-position tick fires.
Traders with at least $100 starting capital who want a transparent, indicator-free grid on XAUUSD M5 (works on H1) and are willing to accept the basket-level risk profile. Best run on a low-spread broker (50-point max-spread filter assumes typical 15–30 point spreads) inside the London 7:00–16:00 and New York 12:00–21:00 GMT windows when XAUUSD liquidity is deepest. The 20% drawdown cap and 30-minute post-3-losses cooldown make it suitable for accounts that can tolerate deep, infrequent drawdowns in exchange for frequent small basket wins.
Strategy Logic
Pipsgrowth EX03023 Grid — Strategy Logic Analysis (from .mq5 source)
Family: Grid
Magic: 22203023
Version: 2.00
BRIEF:
XAUUSD grid strategy EA that places layered buy/sell grid orders at fixed step intervals and closes the entire basket when overall profit target is reached. Includes drawdown safety and spread filter
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
OpenBuyGrid()OpenSellGrid()FillMissingLevels()GetBasketProfit()CountOpenTrades()CountTrades()CountPendingOrders()CloseAllTrades()DetectGMTOffset_EX03023()ServerToGMT_EX03023()InActiveSession_EX03023()UpdateDailyCounters_EX03023()- ...and 6 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (9 total across 4 groups):
- [=== Identity ===]
InpMagicNumber=22203023// Magic Number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_03023" // TradeComment - [=== Grid Settings ===]
InpGridStep= 50 // GridStep(points between levels) - [=== Grid Settings ===]
InpGridLevels= 5 // Maximum Grid Levels - [=== Grid Settings ===]
InpLotSize=0.01// Lot Size perlevel - [=== Grid Settings ===]
InpTakeProfit= 100 // Basket TakeProfit(points) - [=== Safety ===]
InpMaxDrawdown=20.0// Max Drawdown % to pause - [=== Safety ===]
InpBothDirections=false// Trade both Buy and Sell grids - [=== Trade Settings ===]
InpMaxSpread= 50 // MaxSpread(points)
// Pipsgrowth EX03023 Grid — Execution Flow (from source analysis)
// Family: Grid
// XAUUSD grid strategy EA that places layered buy/sell grid orders at fixed step intervals and closes the entire basket when overall profit target is reached. Includes drawdown safety and spread filter
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 |
|---|---|---|
| InpMagicNumber | 22203023 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_03023" | Trade Comment |
| InpGridStep | 50 | Grid Step (points between levels) |
| InpGridLevels | 5 | Maximum Grid Levels |
| InpLotSize | 0.01 | Lot Size per level |
| InpTakeProfit | 100 | Basket Take Profit (points) |
| InpMaxDrawdown | 20.0 | Max Drawdown % to pause |
| InpBothDirections | false | Trade both Buy and Sell grids |
| InpMaxSpread | 50 | Max Spread (points) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX03023 XAUUSDGridStrategy — layered grid with basket profit close, full 12-layer stack."
#include <Trade\Trade.mqh>
input group "=== Identity ==="
input int InpMagicNumber = 22203023; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_03023"; // Trade Comment
input group "=== Grid Settings ==="
input double InpGridStep = 50; // Grid Step (points between levels)
input int InpGridLevels = 5; // Maximum Grid Levels
input double InpLotSize = 0.01; // Lot Size per level
input int InpTakeProfit = 100; // Basket Take Profit (points)
input group "=== Safety ==="
input double InpMaxDrawdown = 20.0; // Max Drawdown % to pause
input bool InpBothDirections = false; // Trade both Buy and Sell grids
input group "=== Trade Settings ==="
input int InpMaxSpread = 50; // Max Spread (points)
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;
CTrade trade;
double gridBuyBase = 0;
double gridSellBase = 0;
bool gridInitialised = false;
//--- Hardening Globals
double g_realizedToday = 0;
double g_realizedWeek = 0;
datetime g_dayStartTime = 0;
datetime g_weekStartTime = 0;
int g_gmtOffset = 3;
int g_dailyTrades = 0;
int g_consecLossesHD = 0;
datetime g_cooldownUntil = 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 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.