Pipsgrowth EX03001 Grid
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX03001 Thanos Grid Adaptive — bidirectional ATR-spaced stop-order grid, full 12-layer stack.
Overview
Pipsgrowth EX03001 Thanos Grid Adaptive is a stop-order grid built for traders who want to layer into a position when price moves against the first entry. The EA is broker-portable and ships with a 12-layer execution stack wired in fixed order: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester. Magic number 22203001, version 2.00.
How the grid is actually built. The first trade is a market order generated by the signal engine. Once that order is on, ManageGrid() places a pending stop at a distance of InpGridATRSpacing times ATR (default 1.5 times ATR(14)) from the current bid or ask, in the same direction as the signal. The pending is a BUYSTOP above ask on a long or a SELLSTOP below bid on a short. When (and if) price continues against the position and triggers the stop, ManageGrid() queues the next stop, with lot size scaled by InpLotMultiplier raised to the level (default 1.3) - level 1 keeps the base lot, level 2 multiplies by 1.3, level 3 by 1.69, level 4 by 2.20, level 5 by 2.86. The grid is hard-capped at GRID_MAX_LEVELS = 5 per side, so the EA will not place a 6th stop in the same direction regardless of input settings.
Important default-state note. InpPyramidEnabled defaults to false. Out of the box, the EA only takes the initial market trade and never activates the pending-stop layers. To engage the grid, the user must flip InpPyramidEnabled to true. This is deliberate: the EA is shipped with grid scaling OFF so the trader can verify the signal and the position management logic on a single trade before committing to multi-layer scaling. The lot-multiplier input (default 1.3) and the grid spacing input (1.5 times ATR) only matter once the grid is enabled.
Signal formation. The signal engine runs only on a new bar. On the closed bar at shift 1, the EA compares close[1] to the upper and lower Bollinger Band (period 20, deviation 2.0). If close[1] breaks above the upper band AND the regime classifier returns a trend-permitting label, the EA produces a +1 buy signal. A close below the lower band produces a -1 sell signal under the same condition. Confidence is logged at 55 for the band break. A fallback fires when the bar body exceeds 0.7 times ATR - bullish body yields +1, bearish body yields -1, with confidence 40. The fallback exists so the EA still trades after a large-range expansion even if the close stays inside the bands.
Regime classifier. ClassifyRegime() reads ATR(14) and ADX(14) on the current timeframe plus Bollinger Bands (20, 2.0) on the current timeframe. It computes the ATR's 100-bar percentile rank against a 25/75 threshold and the BB-width's 100-bar percentile rank against a 20/80 threshold. Seven labels come out: Breakout (ADX at or above 25 with both ATR and BB width in their top quartile), StrongTrend (ADX at or above 25 outside the breakout condition), WeakTrend (ADX between 18 and 25 outside compression), Range (ADX between 18 and 25 in compression), Expand (ATR or BB width top quartile with ADX below 18), Compress (ATR or BB width bottom quartile with ADX below 18), and Choppy (the default catch-all). The signal engine treats only StrongTrend, WeakTrend, Breakout, and Expand as tradeable. NoTradeCheck() adds a separate hard gate: if InpUseRegimeGate is on, ADX below 15 blocks entries outright.
Confirmation layer. ConfirmEntry() rejects the trade if ATR is zero (data warmup), the session check fails (in live mode), the HTF EMA(50) on H1 disagrees with the direction (price below the EMA on a long, above on a short), RSI(14) is overbought on a long (above 70) or oversold on a short (below 30), or the computed reward-to-risk ratio is below 1.2. The HTF EMA(50) on H1 is the one-sided trend-direction filter - it pulls the grid into the higher-timeframe trend and stops the EA from buying into H1 resistance or selling into H1 support. The 1.2 minimum R/R is enforced as a ratio between the fixed 2.5R TP and the 2R SL distance, so it always passes in normal conditions but fails if ATR drops to zero.
Risk and sizing. Position size is computed by CalcLots(): take InpRiskPercent (0.5% default) of effective capital, divide by the loss-per-lot for the SL distance (InpATR_SL_Mult times ATR = 2 times ATR by default), then clamp to the broker's lot min/max/step via ClampVolume(). Effective capital is the lesser of InpCapitalCapAmount and account equity - so with InpCapitalCapAmount set to 0 (the default), the cap is disabled and full equity is used. InpCapitalCapFloor (default 50) blocks new entries when the capped effective capital drops below $50.
Daily loss limit is 3% of effective capital; weekly loss limit is 6%. Both are computed against deals with this magic number (DEAL_MAGIC equals 22203001) and applied via MagicDayPnL() and MagicWeekPnL() inside NoTradeCheck(). A 30-minute cooldown is triggered after 3 consecutive losses, set in OnTradeTransaction() and honored by NoTradeCheck() until the cooldown timer expires.
The kill switch input (InpKillSwitch) is the emergency close - when set to true, the EA calls CloseAll() on the next tick, cancels pending orders, and refuses new entries until the input is flipped back.
Position management. For every open position, ManageOpenPositions() runs each tick and applies four management rules in this order. First, break-even: when price reaches 1R from entry (where 1R equals InpATR_SL_Mult times ATR), the SL is moved to entry plus the broker's stops_level so the trade cannot go negative. Second, ATR trailing: a Chandelier-style trail at 2.5 times ATR(14) below the current bid (for longs) or above the current ask (for shorts), applied only when the trail is forward of the current SL. Third, time exit: positions held longer than 600 bars on the current timeframe are force-closed. On M5 that is 50 hours, on H1 it is 25 days. Fourth, regime Choppy exit: if the regime classifier returns Choppy on a subsequent bar, the position is closed regardless of profit or loss.
TryModify_EX03001() retries the SL/TP modification up to 3 times at 200ms intervals on REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED retcodes. TryClosePartial_EX03001() does the same for partial closes used inside the time-exit and regime-exit paths.
Session handling. InpUseGMTSessions defaults to false. When left off, the EA trades 24/5 on weekdays and the InSession() helper simply blocks Saturday and Sunday. When turned on, InActiveSession_EX03001() requires the GMT hour to be inside either London (7 to 16 GMT) or New York (12 to 21 GMT). DetectGMTOffset_EX03001() runs at init and walks the offset range -12 to +12 to find the score that places the server time inside a weekday 7-21 GMT window - a small auto-calibration step that avoids hardcoding the broker's GMT offset in the source.
OnTester fitness. The tester pass returns (netProfit times profitFactor) divided by (1 plus balanceDrawdown), with a hard gate of 30 or more trades. If the EA trades fewer than 30 times in the backtest, OnTester returns 0 and the genetic optimizer discards the pass. This biases the optimizer toward inputs that produce enough trades to be statistically meaningful.
What to expect in a backtest. Because the entry is on a new-bar closed-candle breakout, the EA naturally skips inside bars and re-enters on the next confirmed breakout. The signal engine produces relatively few trades on its own (a handful per week on M5 XAUUSD), but once InpPyramidEnabled is true, each trade can spawn up to 5 grid layers. With the default 0.5% risk per layer, a fully-filled 5-layer grid commits 0.5% times (1 + 1.3 + 1.69 + 2.20 + 2.86), or about 3.8% of equity, to a single direction. On a $100 account that is only $3.80 of risk in absolute terms, which is why the source declares a $100 minimum deposit - but a serious grid user should size up to $1,000 or more to absorb the worst-case multi-layer drawdown on XAUUSD's typical 1.5 to 2.0 ATR intraday range.
Design asymmetry. The EA is built as a stop-order grid, not a market-execution grid. The 1.5 times ATR pending-stop distance is the key parameter - smaller spacing means more layers fill in normal volatility, larger spacing means fewer layers but tighter risk on a real breakout. Combined with the 2 times ATR hard SL on each layer and the 2.5R final TP, the design is asymmetric: a single 1R move covers the risk on the first layer; a 2.5R move pays for the entire trade plus the unfilled layers' opportunity cost.
Strategy Deep Dive
Thanos-Grid reads ATR(14), Bollinger Bands (20, 2.0), ADX(14), and RSI(14) on the current timeframe plus an EMA(50) on H1 as the higher-timeframe trend filter. On every new bar, the closed candle's close is compared to the Bollinger bands - a close above the upper band with the regime classifier returning StrongTrend, WeakTrend, Breakout, or Expand triggers a long market order; a close below the lower band triggers a short. ConfirmEntry then checks that the H1 EMA(50) agrees with the direction, that RSI(14) is not in the opposite extreme, and that the resulting reward/risk clears 1.2 - if any check fails, the trade is dropped. After the market order fills, ManageGrid() places a pending stop at 1.5 times ATR(14) beyond the entry when InpPyramidEnabled is true, with the lot scaled by 1.3 raised to the level, hard-capped at 5 layers. ManageOpenPositions() then runs each tick, applying the 1R break-even ratchet, the 2.5 times ATR Chandelier trail, the 600-bar time exit, and the Choppy-regime force-close. The whole stack is gated by NoTradeCheck(), which blocks entries on kill switch, below the equity floor, active cooldown, daily or weekly loss-limit breach, max-concurrent reached, or ADX below 15.
First trade: a market order in the signal direction, fired on a new bar when close[1] closes above the Bollinger upper band (long) or below the lower band (short) AND the regime classifier returns StrongTrend, WeakTrend, Breakout, or Expand. ConfirmEntry then requires HTF EMA(50) on H1 to agree with the direction, RSI(14) to not be extended in the wrong zone, and the resulting reward/risk to clear 1.2. After the market order fills, ManageGrid() places a pending BUYSTOP or SELLSTOP at InpGridATRSpacing times ATR (default 1.5 times ATR(14)) beyond the current price, but only when InpPyramidEnabled is true. The grid is hard-capped at GRID_MAX_LEVELS = 5 per side, with each level's lot scaled by InpLotMultiplier raised to the level index (default 1.3x per level).
Each individual position is held until the 2.5R TP fills or the 2.5 times ATR Chandelier trail below bid (long) or above ask (short) is hit. Break-even fires at 1R profit, moving the SL to entry plus the broker stops_level so the trade cannot lose. A time exit closes positions held longer than 600 bars (50 hours on M5, 25 days on H1). If the regime classifier later returns Choppy, the position is closed regardless of P&L. There is no basket-level close - exits are per-trade only.
Each trade carries a hard per-trade SL at InpATR_SL_Mult times ATR (default 2 times ATR(14)) on the entry bar. The SL is actively ratcheted to break-even at 1R profit and then trailed by 2.5 times ATR(14) Chandelier-style below bid (long) or above ask (short). The portfolio as a whole is bounded by 3% daily / 6% weekly loss-of-equity limits and a 30-minute cooldown triggered by 3 consecutive losses.
TP is a fixed multiple of the SL distance via FINAL_TP_R = 2.5, giving a 2.5:1 reward/risk on every entry. With SL at 2 times ATR and TP at 5 times ATR, a typical XAUUSD M5 trade targets roughly 250-500 points depending on volatility. TP is per-layer - each grid level carries its own 2.5R exit, so filled layers close independently rather than as a basket.
Designed for XAUUSD on M5 and H1 - the Bollinger band signal and the ATR-based grid spacing both work best on a pair with measurable intraday volatility. Minimum recommended balance: $1,000 (the source declares $100 but a fully-filled 5-layer grid with the default 1.3x lot multiplier commits roughly 3.8% of equity, so $1,000+ gives room to absorb a multi-layer adverse move). Run on a low-spread ECN or RAW-spread broker because the EA opens both market orders and pending stops - high spreads compound across grid layers. Avoid running during high-impact news events unless you set a wider spread filter; the EA does not include a built-in news window (NEWS_BLOCK_MINUTES = 0).
Strategy Logic
Pipsgrowth EX03001 Grid — Strategy Logic Analysis (from .mq5 source)
Family: Grid
Magic: 22203001
Version: 2.00
BRIEF:
Bidirectional STOP-order grid (BUYSTOP/SELLSTOP) at ATR distance from price, scale-in by multiplier, per-direction profit take and shared-basket loss cap. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester. Grid default OFF, hard-capped
INDICATOR STACK:
ATRBBADXRSIEMA
KEY FUNCTIONS:
NormPrice()StopsLevelPrice()EffCapital()BelowFloor()MagicDayPnL()MagicWeekPnL()ReadBuffer()GetSpreadPts()GetSpreadAvgPts()InSession()NewsBlocked()ClampVolume()- ...and 23 more
INTERNAL CONSTANTS (26 total):
ATR_PERIOD= 14 //ATRperiodBB_PERIOD= 20 // Bollinger periodBB_DEV=2.0// Bollinger deviationADX_PERIOD= 14 //ADXperiodRSI_PERIOD= 14 //RSIperiodRSI_OVERSOLD= 30 //RSIoversold (signal side)RSI_OVERBOUGHT= 70 //RSIoverbought (signal side)HTF_TF=PERIOD_H1// Higher timeframeHTF_EMA_PERIOD= 50 //HTFEMAperiodATR_PCTILE_LOOKBACK= 100 //ATRpercentile lookback barsATR_PCTILE_LO= 25 // Low percentile (Compress)ATR_PCTILE_HI= 75 // High percentile (Expand)BB_WIDTH_LOOKBACK= 100 //BB-width percentile lookbackGRID_MAX_LEVELS= 5 // Hard cap on grid levels per sideBE_R_MULT=1.0// Break-even at 1R- ...and 11 more
INPUT PARAMETERS (25 total across 8 groups):
- [=== Identity ===]
InpMagic=22203001// Magic number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_03001" // Trade comment - [=== Identity ===]
InpSlippagePts= 30 // Max slippage (points) - [=== Capital Cap ===]
InpCapitalCapAmount=0.0// Real-money cap ($) - [=== Capital Cap ===]
InpCapitalCapFloor=50.0// Equity floor ($, block entries) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk per trade (% ofeffective_capital) - [=== Risk & Sizing ===]
InpDailyLossLimitPct=3.0// Daily loss limit (% ofeffective_capital) - [=== Risk & Sizing ===]
InpWeeklyLossLimitPct=6.0// Weekly loss limit (% ofeffective_capital) - [=== Risk & Sizing ===]
InpMaxConcurrent= 10 // Max concurrent positions (thisEA/symbol) - [=== Risk & Sizing ===]
InpATR_SL_Mult=2.0// Hard SL =ATR* mult - [=== Risk & Sizing ===]
InpDryRun=false// Dry-run (no live sends) - [=== Signal / Entry ===]
InpAllowBuy=true// AllowBUYentries - [=== Signal / Entry ===]
InpAllowSell=true// AllowSELLentries - [=== Signal / Entry ===]
InpGridATRSpacing=1.5// Grid spacing (ATRmultiples) - [=== Scaling / Pyramid ===]
InpPyramidEnabled=false// Enable grid scaling (defaultOFF) - [=== Scaling / Pyramid ===]
InpLotMultiplier=1.3// Per-levellot multiplier (capped) - [=== Regime / Manage ===]
InpUseRegimeGate=true// Gate entries by regime - [=== Regime / Manage ===]
InpKillSwitch=false// Emergency kill switch (close all) - [=== Hardening
GMTSessions ===]InpUseGMTSessions=false// UseGMT-based session filter - [=== Hardening
GMTSessions ===]InpLondonStartGMT= 7 // London session start (GMT) - [=== Hardening
GMTSessions ===]InpLondonEndGMT= 16 // London session end (GMT) - [=== Hardening
GMTSessions ===]InpNewYorkStartGMT= 12 // New York session start (GMT) - [=== Hardening
GMTSessions ===]InpNewYorkEndGMT= 21 // New York session end (GMT) - [=== Hardening Trade Safety ===]
InpMaxTradesPerDay= 50 // Max trades per day (0=off) - [=== Hardening Trade Safety ===]
InpCooldownMinutes= 30 // Cooldown after 3 consecutive losses (minutes)
// Pipsgrowth EX03001 Grid — Execution Flow (from source analysis)
// Family: Grid
// Bidirectional STOP-order grid (BUYSTOP/SELLSTOP) at ATR distance from price, scale-in by multiplier, per-direction profit take and shared-basket loss cap. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester. Grid default OFF, hard-capped
ON_INIT:
Create indicator handles: ATR, BB, ADX, RSI, EMA
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 |
|---|---|---|
| InpMagic | 22203001 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_03001" | Trade comment |
| InpSlippagePts | 30 | Max slippage (points) |
| InpCapitalCapAmount | 0.0 | Real-money cap ($) |
| InpCapitalCapFloor | 50.0 | Equity floor ($, block entries) |
| InpRiskPercent | 0.5 | Risk per trade (% of effective_capital) |
| InpDailyLossLimitPct | 3.0 | Daily loss limit (% of effective_capital) |
| InpWeeklyLossLimitPct | 6.0 | Weekly loss limit (% of effective_capital) |
| InpMaxConcurrent | 10 | Max concurrent positions (this EA/symbol) |
| InpATR_SL_Mult | 2.0 | Hard SL = ATR * mult |
| InpDryRun | false | Dry-run (no live sends) |
| InpAllowBuy | true | Allow BUY entries |
| InpAllowSell | true | Allow SELL entries |
| InpGridATRSpacing | 1.5 | Grid spacing (ATR multiples) |
| InpPyramidEnabled | false | Enable grid scaling (default OFF) |
| InpLotMultiplier | 1.3 | Per-level lot multiplier (capped) |
| InpUseRegimeGate | true | Gate entries by regime |
| InpKillSwitch | false | Emergency kill switch (close all) |
| InpUseGMTSessions | false | Use GMT-based session filter |
| InpLondonStartGMT | 7 | London session start (GMT) |
| InpLondonEndGMT | 16 | London session end (GMT) |
| InpNewYorkStartGMT | 12 | New York session start (GMT) |
| InpNewYorkEndGMT | 21 | New York session end (GMT) |
| InpMaxTradesPerDay | 50 | Max trades per day (0=off) |
| InpCooldownMinutes | 30 | Cooldown after 3 consecutive losses (minutes) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX03001 Thanos Grid Adaptive — bidirectional ATR-spaced stop-order grid, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Trade\DealInfo.mqh>
//=========================== Tunable constants ====================//
#define ATR_PERIOD 14 // ATR period
#define BB_PERIOD 20 // Bollinger period
#define BB_DEV 2.0 // Bollinger deviation
#define ADX_PERIOD 14 // ADX period
#define RSI_PERIOD 14 // RSI period
#define RSI_OVERSOLD 30 // RSI oversold (signal side)
#define RSI_OVERBOUGHT 70 // RSI overbought (signal side)
#define HTF_TF PERIOD_H1 // Higher timeframe
#define HTF_EMA_PERIOD 50 // HTF EMA period
#define ATR_PCTILE_LOOKBACK 100 // ATR percentile lookback bars
#define ATR_PCTILE_LO 25 // Low percentile (Compress)
#define ATR_PCTILE_HI 75 // High percentile (Expand)
#define BB_WIDTH_LOOKBACK 100 // BB-width percentile lookback
#define GRID_MAX_LEVELS 5 // Hard cap on grid levels per side
#define BE_R_MULT 1.0 // Break-even at 1R
#define PARTIAL_TP1_R 1.0 // Partial TP at 1R (50%)
#define FINAL_TP_R 2.5 // Final TP at 2.5R
#define TRAIL_ATR_MULT 2.5 // ATR trailing multiplier (Chandelier-style)
#define MAX_BARS_IN_TRADE 600 // Max bars per position
#define COOLDOWN_BARS 5 // Bars to wait after stop
#define SESSION_START_HOUR 7 // Server-time session start
#define SESSION_END_HOUR 21 // Server-time session end
#define NEWS_BLOCK_MINUTES 0 // 0 = no manual news window
#define SPREAD_X_AVG_MAX 3.0 // Max spread multiple vs avg
#define SPREAD_AVG_LOOKBACK 50 // Bars for spread avg
#define MIN_RR_RATIO 1.2 // Min reward/risk to enter
//=========================== Inputs (18 total) ====================//
input group "=== Identity ==="
input long InpMagic = 22203001; // Magic number
input string InpTradeComment = "Psgrowth.com Expert_03001";// Trade comment
input int InpSlippagePts = 30; // Max slippage (points)
input group "=== Capital Cap ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable // Enable capital cap
input double InpCapitalCapAmount = 0.0; // Real-money cap ($)
input double InpCapitalCapFloor = 50.0; // Equity floor ($, block entries)
input group "=== Risk & Sizing ==="
input double InpRiskPercent = 0.5; // Risk per trade (% of effective_capital)
input double InpDailyLossLimitPct = 3.0; // Daily loss limit (% of effective_capital)
input double InpWeeklyLossLimitPct= 6.0; // Weekly loss limit (% of effective_capital)
input int InpMaxConcurrent = 10; // Max concurrent positions (this EA/symbol)
input double InpATR_SL_Mult = 2.0; // Hard SL = ATR * mult
input bool InpDryRun = false; // Dry-run (no live sends)
input group "=== Signal / Entry ==="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.