Pipsgrowth EX03004 Grid
MT5 Expert Advisor (Open Source) · USDJPY · M5, H1
Pipsgrowth.com EX03004 Aggressive_Pyramid_Buy — buy-only pyramid with 8-13-21 EMA trend alignment, full 12-layer stack.
Overview
Pipsgrowth EX03004 is a one-direction, trend-pyramiding grid for USDJPY. It only buys. There is no short path anywhere in the code — no short entry function, no sell call, no close-on-short logic. The whole lifecycle is built around catching a bullish swing on JPY pairs, adding to it as price moves in favor, and dumping the entire stack the moment momentum cracks. That single-direction bias is not a default; it is the architecture, and it shapes every risk decision in the file.
The trend gate is a three-EMA stack at 8, 13, and 21 periods on the close. The IsBullishTrend() helper returns true only when EMA(8) sits above EMA(13) and EMA(13) sits above EMA(21) on the current bar — a strict ordering, not just a slope. The bearish-exit helper, IsReversalSignal(), watches for a single event: EMA(8) crossing below EMA(13) on the current bar while having been at or above EMA(13) on the previous bar. That one cross triggers CloseAllBuyPositions() and the EA returns for the tick. The 21-EMA does not gate entries directly, but its position under the stack filters out shallow bounces that would otherwise trigger the 8/13 cross too early.
The pyramid mechanic lives in ManagePyramidStrategy(), which runs on every tick when the trend is bullish and the safety stack clears. On a clean chart (no buy positions), the EA fires the initial entry: 0.10 lots by default (InpInitialLots), with a 30-pip initial stop below the ask. Once at least one buy is open, the function switches to pyramid mode. It walks the open positions, finds the highest open price, and only opens a new buy when the current ask is at least InpPyramidPips above that level (default 20 pips). A second guard: the most recent position must already be in profit. If the last pyramid is still red, the function returns and waits for the next qualifying tick. The pyramid stop is tighter than the initial one — ask minus 0.8 × pyramidDistance — so each new leg is protected closer to entry as the stack grows.
The break-even-secure step is what makes the pyramid workable. For every open buy, the function checks whether bid has cleared openPrice + 10 pips AND the current stop is still below the open. If both are true, it moves the stop to openPrice + InpSecurePips (2 pips above entry). That locks the position into a small guaranteed profit on the next adverse move. The 2-pip buffer is small enough to keep the trade from getting stopped out by a typical pullback into the prior candle's range, but large enough to cover spread + slippage in normal USDJPY conditions. Securing is one-shot — once a position is at BE+2, the EA does not ratchet the stop further; the pyramid's own new entries provide the next layer of protection.
Exit is intentionally minimal. There is no TP, no time-stop, no per-position partial close. The only closing path is the asymmetric EMA cross described above. The reasoning is built into the file name: aggressive pyramid. The EA is designed to catch a single directional move from start to finish, then reload on the next confirmed bullish stack. Holding through pullbacks is the whole point. The flip side is that drawdowns during a long pyramid can be substantial if the trend reverses sharply — the EA will sit in red through the entire unwind of the EMA stack, only closing once the 8 crosses below the 13.
The safety stack is layered. IsSafeToTrade_EX03004() blocks new entries when: outside the configured session (London 7-16 GMT ∪ NY 12-21 GMT when InpUseGMTSessions is true), inside a cooldown window (set to TimeCurrent() + 30 minutes after the third consecutive loss, when InpCooldownMinutes > 0), below the equity floor (InpEquityFloor), past the daily or weekly realized loss limit, above the capital cap, or having hit the daily trade ceiling (InpMaxTradesPerDay = 50). InpMaxConsecLosses is exposed but defaults to 0 (disabled) — the user has to set it explicitly for the consecutive-loss gate to fire. The session itself is computed through DetectGMTOffset_EX03004(), which does a brute-force search across offsets from -12 to +12, scoring each candidate by whether the resulting GMT hour lands on a weekday between 07:00 and 21:00, and the winner becomes g_gmtOffset.
Order execution is conservative. TryBuy_EX03004() runs a pre-trade margin check via OrderCalcMargin — if the required margin exceeds free margin, the buy is refused before any ticket is sent. The actual buy uses the trade object's SetTypeFilling(ORDER_FILLING_IOC) and SetDeviationInPoints(InpSlippage = 30), and retries up to three times at 200ms intervals if the broker returns REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED. TryModify_EX03004() and TryClose_EX03004() use the same retry pattern. There is no spread filter and no news filter in the source — a deliberate omission for a JPY-pair pyramid that wants to be in the market whenever the EMA stack permits.
The OnTester() fitness function is (profit / maxDD) × PF, but only if maxDD > 0 and at least 10 trades closed. PF is forced to 0 if it is at or below 1, so the optimizer is heavily biased toward parameter sets that produce a real edge, not raw profit on a lucky handful of trades. Because the EA has no fixed TP, the optimizer's job is to find EMA period combinations, pyramid distance, and secure pips that ride the longest trends and bail cleanly on the reverses.
Practical expectations. On USDJPY M5, the EA will typically fire 1-3 buys per trend, secure them to BE+2, and exit on the EMA cross. Pyramiding to the InpMaxPositions=10 cap is rare and requires a sustained 200+ pip move in JPY pip terms. Drawdown scales with pyramid depth — going from 1 to 5 open positions on a single reversal can leave a 100+ pip floating loss before the cross triggers. The minDeposit of $100 reflects the initial 0.10 lot sizing, but a serious deployment on JPY pairs with this pyramid depth should start with at least $500-$1,000 of headroom. The pair restriction is real: OnInit() prints a warning if the symbol doesn't contain 'JPY', and the pip value calculation in the source assumes 3- or 5-digit pricing. Plugging this EA into EURUSD without adjusting the pip math will produce 10x-off stops.
Strategy Deep Dive
On every tick, RefreshEMAData() copies two bars from each of the three EMA handles (8, 13, 21) into pre-allocated buffers set as series. IsBullishTrend() then checks the strict stack ordering on bar[0]; IsReversalSignal() looks for the 8-below-13 cross with the prior bar at-or-above. If the cross fires and any buy is open, CloseAllBuyPositions() flushes the entire stack and the function returns. Otherwise, on a bullish stack with IsSafeToTrade_EX03004() clear, ManagePyramidStrategy() walks all open buys, secures each profitable position to BE+2, and either opens the initial 0.10-lot buy (if empty) or adds a pyramid leg once price has advanced 20 pips above the highest buy and that buy is in profit. All order sends run through the retry wrapper, which loops three times at 200ms on requote/timeout/price-changed, and every close, modify, and buy verifies its return code is TRADE_RETCODE_DONE or DONE_PARTIAL. The OnTradeTransaction hook updates g_realizedToday, g_realizedWeek, g_dailyTrades, and triggers a 30-minute cooldown after the third consecutive loss when InpCooldownMinutes > 0.
Entries are buy-only and require a strict three-EMA bullish stack: EMA(8) > EMA(13) > EMA(21) on the current bar, with all three close-based. The first qualifying tick when no buy is open fires the initial 0.10-lot entry (InpInitialLots) with a 30-pip stop. Subsequent entries are pyramid legs: each opens when the current ask is at least 20 pips above the highest open buy (InpPyramidPips) AND the most recent position is in profit, up to a cap of 10 concurrent buys (InpMaxPositions).
The only exit is an asymmetric EMA cross: EMA(8) crossing below EMA(13) on the current bar while it was at-or-above EMA(13) on the previous bar. That one event triggers CloseAllBuyPositions(), which walks every open buy owned by the magic number and closes them via the trade object's PositionClose with three retries at 200ms. There is no TP, no time-stop, and no partial close at the position level.
Initial buys get a 30-pip stop below the ask (InpStopLossPips). Pyramid legs use a tighter stop at ask - 0.8 × pyramidDistance. The break-even-secure step then moves each position's stop to openPrice + 2 pips (InpSecurePips) once bid clears openPrice + 10 pips, locking in a small guaranteed profit on the next adverse move.
There is no take-profit input or TP field on any order. The trade is closed only by the EMA reversal cross; floating profits are protected by the break-even-secure step plus the per-leg pyramid stop, not by a fixed TP. Pyramiding itself is the profit-amplification mechanism.
Best deployed on USDJPY M5 with a low-spread ECN or Raw-spread account, in line with the 3- or 5-digit pricing assumed by the pip-value calculation in OnInit. Recommended balance: $500-$1,000 to absorb a pyramid stack of 3-5 open positions against the unavoidable drawdown of a long trend reversal — the listed $100 minimum is a hard floor, not a comfortable operating balance. The 8-13-21 EMA stack trades best during clean, sustained JPY directional moves (London and NY sessions, with InpUseGMTSessions = true to cut exposure during the quiet Asian rollover). Not suitable for ranging USDJPY days where the 8/13 cross fires repeatedly against a flat 21.
Strategy Logic
Pipsgrowth EX03004 Grid — Strategy Logic Analysis (from .mq5 source)
Family: Grid
Magic: 22203004
Version: 2.00
BRIEF:
Aggressive buy-only pyramid EA using 8-13-21 EMA trend alignment. Opens initial buy on bullish EMA stack, adds pyramid positions as price advances, secures trades to break-even, and exits all on EMA reversal cross. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
RefreshEMAData()IsBullishTrend()IsReversalSignal()CountOurBuyPositions()ManagePyramidStrategy()ValidateLotSize()CloseAllBuyPositions()OnTradeTransaction()DetectGMTOffset_EX03004()ServerToGMT_EX03004()InActiveSession_EX03004()UpdateDailyCounters_EX03004()- ...and 4 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (13 total across 5 groups):
- [=== Risk Settings ===]
InpInitialLots=0.10// Initial Lot Size - [=== Risk Settings ===]
InpPyramidLots=0.10// Pyramid LotSize(Flat stacking) - [=== Risk Settings ===]
InpStopLossPips=30.0// Initial StopLoss(pips) - [=== Pyramid Logic ===]
InpMaxPositions= 10 // Max concurrent buy positions - [=== Pyramid Logic ===]
InpPyramidPips=20.0// Distance in pips to add new trade - [=== Pyramid Logic ===]
InpSecurePips=2.0// Pips profit to lock in (BE + buffer) - [=== Trend
Logic(8-13-21EMA) ===]InpFastEMA= 8 // MomentumEMA(Fast) - [=== Trend
Logic(8-13-21EMA) ===]InpMediumEMA= 13 // TrailEMA(Medium) - [=== Trend
Logic(8-13-21EMA) ===]InpSlowEMA= 21 // TrendEMA(Slow) - [=== Trade Management ===]
InpMagicNum=22203004// Magic Number - [=== Trade Management ===]
InpTradeComment= "Psgrowth.com Expert_03004" // TradeComment - [=== Trade Management ===]
InpSlippage= 30 // MaxSlippage(points) - [=== Hardening Trade Safety ===]
InpMaxConsecLosses= 0 // +------------------------------------------------------------------+
// Pipsgrowth EX03004 Grid — Execution Flow (from source analysis)
// Family: Grid
// Aggressive buy-only pyramid EA using 8-13-21 EMA trend alignment. Opens initial buy on bullish EMA stack, adds pyramid positions as price advances, secures trades to break-even, and exits all on EMA reversal cross. 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 |
|---|---|---|
| InpInitialLots | 0.10 | Initial Lot Size |
| InpPyramidLots | 0.10 | Pyramid Lot Size (Flat stacking) |
| InpStopLossPips | 30.0 | Initial Stop Loss (pips) |
| InpMaxPositions | 10 | Max concurrent buy positions |
| InpPyramidPips | 20.0 | Distance in pips to add new trade |
| InpSecurePips | 2.0 | Pips profit to lock in (BE + buffer) |
| InpFastEMA | 8 | Momentum EMA (Fast) |
| InpMediumEMA | 13 | Trail EMA (Medium) |
| InpSlowEMA | 21 | Trend EMA (Slow) |
| InpMagicNum | 22203004 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_03004" | Trade Comment |
| InpSlippage | 30 | Max Slippage (points) |
| InpMaxConsecLosses | 0 | +------------------------------------------------------------------+ |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX03004 Aggressive_Pyramid_Buy — buy-only pyramid with 8-13-21 EMA trend alignment, full 12-layer stack."
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| INPUT PARAMETERS |
//+------------------------------------------------------------------+
input group "=== Risk Settings ==="
input double InpInitialLots = 0.10; // Initial Lot Size
input double InpPyramidLots = 0.10; // Pyramid Lot Size (Flat stacking)
input double InpStopLossPips = 30.0; // Initial Stop Loss (pips)
input group "=== Pyramid Logic ==="
input int InpMaxPositions = 10; // Max concurrent buy positions
input double InpPyramidPips = 20.0; // Distance in pips to add new trade
input double InpSecurePips = 2.0; // Pips profit to lock in (BE + buffer)
input group "=== Trend Logic (8-13-21 EMA) ==="
input int InpFastEMA = 8; // Momentum EMA (Fast)
input int InpMediumEMA = 13; // Trail EMA (Medium)
input int InpSlowEMA = 21; // Trend EMA (Slow)
input group "=== Trade Management ==="
input ulong InpMagicNum = 22203004; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_03004"; // Trade Comment
input int InpSlippage = 30; // Max Slippage (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;
//+------------------------------------------------------------------+
//| GLOBAL VARIABLES |
//+------------------------------------------------------------------+
CTrade g_trade;
int g_handleEMA8;
int g_handleEMA13;
int g_handleEMA21;
double g_bufferEMA8[];
double g_bufferEMA13[];
double g_bufferEMA21[];
double g_pipValue;
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.