Pipsgrowth EX03008 Grid
MT5 Expert Advisor (Open Source) · XAUUSD · M15, M5, H1
Pipsgrowth.com EX03008 G4_PyramidPro — multi-indicator pyramid with Hull MA, Supertrend and S/R, full 12-layer stack.
Overview
Pipsgrowth EX03008 is a pyramid-style grid EA that only opens fresh exposure when a four-source trend score, a multi-touch support/resistance map, and a Supertrend flip line all agree on direction. The entry engine refuses trades during flat volatility, refuses trades when the market has no higher-high/higher-low (or lower-low/lower-high) sequence, and refuses to add a second leg unless price has already moved PyramidStepPips in the trade's favor. With AddOnTrendContinuation set to true and MaxPositions raised above 1, the EA will stack up to PyramidLevels (default 5) entries in the same direction, each 50 pips beyond the previous one's entry price — turning a single momentum read into a scaled trend trade.
The four-source trend score is built inside AnalyzeTrend. A Hull Moving Average of period HullPeriod (default 21) is computed by hand on the user-selected HullTimeframe (the MQL code accepts codes 1-7 mapped to M1, M5, M15, M30, H1, H4, D1; an out-of-range code falls back to H1, and the 8 written in the source comment block is not a valid MQL timeframe and resolves to the same fallback). A Supertrend on SuperTrendTimeframe (also accepting codes 1-7, falling back to H1) using SuperTrendPeriod (default 10) and SuperTrendMultiplier (default 3.0) provides the second vote. Two more votes come from raw price action: whether the latest close is above or below the previous close, and whether the latest close is above or below the Hull line. The four booleans are summed, divided by four, and pushed into a 14-bar rolling average trendScore. The averaged score is then bucketed into trendStrength: anything above 0.7 becomes strong bull (+2), above 0.3 becomes weak bull (+1), symmetric negatives become weak/strong bear, and anything inside ±0.3 reads as flat (0).
GenerateSignals combines trendStrength with a market-structure read and a support/resistance proximity read. DetectMarketStructure walks StructureLookback (default 50) bars and marks a swing high only if SwingHighLowBars (default 5) bars on each side have a lower high; symmetric for swing lows. The function then requires that the most recent swing high be above the prior swing high AND the most recent swing low be above the prior swing low to declare a bullishStructure; the opposite pattern declares a bearishStructure. DetectSupportResistance clusters all detected swing highs/lows into at most 10 buckets; an SRTolerance (default 0.5) of pipSize*10 is the merge distance. After the merge, levels with fewer than SRMinTouches (default 2) touches are filtered out, and the rest are sorted by touch count.
A long is only armed if trendStrength is +1 or +2, superTrendDir is +1, the current close is above the Hull, the recent swing pattern is bullishStructure, AND the current price is within SRTolerance*10 of a qualified support level. The short mirror requires a bearish trend, a flipped Supertrend, a close below Hull, a bearish swing pattern, and proximity to a qualified resistance. GenerateSignals also sets an avoidTrade flag if the ATR(14)/price ratio is above 0.002 (a volatility regime that the EA's risk model treats as too noisy) or below 0.0002 (treated as a low-liquidity regime). An additional flat-regime veto fires whenever trendStrength rolls back to 0.
Position management lives in ManagePositions. If buyPositions exceeds 0 and the new bar's trendStrength has flipped bearish OR the Supertrend has flipped OR price has crossed below Hull, the EA closes all buy positions via ClosePositionsByType. The same symmetric exit fires for shorts. If the new signal matches the existing direction and buyPositions is below MaxPositions, the EA either opens a fresh trade (no position of that type) or, when AddOnTrendContinuation is on and buyPositions is below PyramidLevels, opens an additional trade if the current close is at least PyramidStepPips*10 pips above GetLastPositionPrice. The default MaxPositions is 1, which means the EA behaves as a single-entry trend follower until the user raises that cap. AllowHedging is false by default, so when the EA flips direction it first closes the opposing leg before opening the new one.
Trailing runs on every new bar when UseDynamicTrailing is on, and the trailing distance is itself regime-adaptive. ManageTrailingStops shrinks the effective trailing stop to TrailingStopPips0.5 when trendStrength is 0 and to TrailingStopPips0.7 when trendStrength is ±1; it stays at the full TrailingStopPips (default 30) when the trend is strong (±2). The function only ratchets the stop forward when the position is in profit past the dynamic trailing distance, and only when the new stop improves on the old stop by at least TrailingStepPips (default 10) pips. Every modify call goes through TryModify_EX03008, which retries up to 3 times at 200 ms on REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED and otherwise accepts TRADE_RETCODE_DONE / DONE_PARTIAL.
Hard risk sits in two layers. The first is CheckRiskManagement, which runs after the trading logic. It tracks accountHigh = max(accountHigh, balance) on each new bar, computes drawdownPercent as (accountHigh - equity)/accountHigh*100, and if drawdownPercent >= MaxDrawdownPercent (default 20) it calls CloseAllPositions and — if CloseAllOnMaxLoss is on — calls ExpertRemove() to detach the EA from the chart. A symmetric daily-loss guard checks dailyLoss/StartingBalance*100 against MaxDailyLossPercent (default 10) and unwinds everything the same way. The second layer is the hardening stack in IsSafeToTrade_EX03008: it refuses to run if not inside the configured London (7-16 GMT) or New York (12-21 GMT) window, if the equity is below InpEquityFloor, if today's realized P&L has dropped below -InpDailyLossLimit, if this week's realized has dropped below -InpWeeklyLossLimit, if the account balance has reached InpCapitalCap, if g_dailyTrades has reached InpMaxTradesPerDay, or if g_consecLosses has reached InpMaxConsecLosses. All of those thresholds are 0 in the default inputs except InpMaxTradesPerDay (50) and InpCooldownMinutes (30) — the EA arms a 30-minute cooldown after 3 consecutive losing deals. A separate cooldown is enforced when g_cooldownUntil has not yet expired.
Execution uses CTrade with a magic of 22203008 and the comment string InpTradeComment. TryBuy_EX03008 and TrySell_EX03008 floor the requested LotSize to the symbol's volume step, clamp it inside min/max lot, run an OrderCalcMargin pre-check against ACCOUNT_MARGIN_FREE (and abort with a logged message if there isn't enough), and then attempt the order up to 3 times at 200 ms intervals on the same transient retcodes. The pair is XAUUSD by default but the source explicitly marks the EA portable to FX majors and metals, since every level is computed in pips via pipSize*10 with no symbol-specific scaling. The suggested timeframe is M15 and the file is built to work from M5 through H1; above H1 the swing-detection lookback starts to under-sample structure, and below M5 the four-source trend score gets noisy on every micro-flick. Because the entry gating is strict and the pyramid step is 50 pips, expect low trade frequency with most of the year spent waiting for the next qualifying trend + S/R + Supertrend alignment.
Strategy Deep Dive
EX03008 runs a per-new-bar pipeline in OnTick: UpdateIndicators rebuilds the Hull MA and Supertrend on their selected timeframes, DetectMarketStructure finds swing highs/lows inside a StructureLookback window, DetectSupportResistance clusters the swings into 10 levels and filters out anything with fewer than SRMinTouches touches, AnalyzeTrend combines the four trend votes into a 14-bar averaged score and buckets it into a five-state trendStrength (-2 to +2), and GenerateSignals declares buySignal, sellSignal, or avoidTrade. ManagePositions then either opens the first leg, adds a pyramid layer if the price has moved 50 pips beyond the last entry and AddOnTrendContinuation is on, or unwinds the existing leg when any of the four trend sources flips. ManageTrailingStops ratchets the SL forward every new bar with a trend-strength-scaled distance, CheckRiskManagement calls CloseAllPositions (and ExpertRemove) on max DD or max daily loss, and the hardening stack in IsSafeToTrade_EX03008 blocks new entries outside London/New York GMT windows, past the daily or weekly loss cap, past the daily trade count, or while a 30-minute cooldown is still active after three consecutive losers.
A long entry requires trendStrength >= +1, superTrendDir == +1, the latest close above the Hull line, a bullishStructure pattern (HH+HL on the most recent swing pair), and proximity (within SRTolerance*10 pips) to a support level with at least SRMinTouches touches. The short mirror requires symmetric bearish conditions plus proximity to a qualified resistance. The volatility gate (ATR(14)/price inside 0.0002-0.002) and the flat-regime veto (trendStrength == 0) further restrict entries.
The EA fires opposite-side exits whenever the new-bar trend score flips sign, the Supertrend flips, or price crosses the Hull line in the opposite direction — ClosePositionsByType unwinds the entire leg. If AddOnTrendContinuation is on, pyramid adds fire only after the price has moved PyramidStepPips*10 pips beyond the previous entry. Daily-loss or max-drawdown breaches call CloseAllPositions and, if CloseAllOnMaxLoss is on, ExpertRemove() detaches the EA entirely.
Each entry receives an InitialStopLossPips (default 50) pips below the ask for longs and above the bid for shorts. A dynamic trailing stop ratchets forward on every new bar, shrinking to 50% of TrailingStopPips when the trend score flattens, 70% when weak, and the full TrailingStopPips (default 30) when the trend is strong, advancing only by TrailingStepPips (default 10) pips at a time. There is no per-trade global stop-out cap beyond MaxDrawdownPercent (default 20) or MaxDailyLossPercent (default 10), which both close everything and remove the EA from the chart.
Each entry receives an InitialTakeProfitPips (default 100) pips above the ask for longs and below the bid for shorts, giving a fixed 1:2 reward-to-risk ratio against the 50-pip stop. There is no basket-level profit target; the TakeProfit is set per position and is preserved as the trailing stop ratchets behind price.
Built for XAUUSD on the M15 chart (with M5 and H1 as accepted secondary timeframes). Recommended starting balance is $100 — the EA's risk gates key off StartingBalance (default 100) for the daily-loss check, so smaller accounts use the same default percentages. Best run on an ECN/RAW-spread account with low latency and at least the standard 50-pip stop room; bear in mind MaxPositions defaults to 1, so the EA behaves as a single-entry trend follower until the user raises both MaxPositions and verifies the pyramid step suits the account size.
Strategy Logic
Pipsgrowth EX03008 Grid — Strategy Logic Analysis (from .mq5 source)
Family: Grid
Magic: 22203008
Version: 2.00
BRIEF:
Advanced pyramid trading EA combining Hull MA, Supertrend, market structure, and support/resistance analysis. Pyramids into trends with trailing stops and daily risk management. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
OnTradeTransaction()IsNewBar()CheckDailyReset()UpdateIndicators()CalculateHullMA()CalculateSuperTrend()DetectMarketStructure()DetectSupportResistance()AnalyzeTrend()GenerateSignals()GetATR()ManagePositions()- ...and 20 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (2 total across 2 groups):
- [===
HULLMASETTINGS===]HullTimeframe= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) - [===
SUPERTRENDSETTINGS===]SuperTrendTimeframe= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
// Pipsgrowth EX03008 Grid — Execution Flow (from source analysis)
// Family: Grid
// Advanced pyramid trading EA combining Hull MA, Supertrend, market structure, and support/resistance analysis. Pyramids into trends with trailing stops and daily risk management. 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 |
|---|---|---|
| HullTimeframe | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) |
| SuperTrendTimeframe | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX03008 G4_PyramidPro — multi-indicator pyramid with Hull MA, Supertrend and S/R, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Indicators\Indicators.mqh>
CTrade trade;
CPositionInfo positionInfo;
COrderInfo orderInfo;
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
switch(tf)
{
case 1: return PERIOD_M1;
case 2: return PERIOD_M5;
case 3: return PERIOD_M15;
case 4: return PERIOD_M30;
case 5: return PERIOD_H1;
case 6: return PERIOD_H4;
case 7: return PERIOD_D1;
default: return PERIOD_H1;
}
}
ENUM_TIMEFRAMES g_HullTimeframe = PERIOD_H1;
ENUM_TIMEFRAMES g_SuperTrendTimeframe = PERIOD_H1;
input group "=== TRADING SETTINGS ==="
input double LotSize = 0.01;
input double StartingBalance = 100;
input int MaxPositions = 1;
input bool AllowHedging = false;
input int MagicNumber = 22203008;
input string InpTradeComment = "Psgrowth.com Expert_03008";
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
switch(tf)
{
case 1: return PERIOD_M1;
case 2: return PERIOD_M5;
case 3: return PERIOD_M15;
case 4: return PERIOD_M30;
case 5: return PERIOD_H1;
case 6: return PERIOD_H4;
case 7: return PERIOD_D1;
default: return PERIOD_H1;
}
}
ENUM_TIMEFRAMES g_HullTimeframe = PERIOD_H1;
ENUM_TIMEFRAMES g_SuperTrendTimeframe = PERIOD_H1;
input group "=== PYRAMID SETTINGS ==="
input int PyramidLevels = 5;
input double PyramidStepPips = 50;
input bool AddOnTrendContinuation = true;
input bool CloseAllOnTrendReversal = true;
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.