P
PipsGrowth
GridOpen Source – Free

Pipsgrowth EX03027 Grid

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX03027 Gold_EMA_SuperTrend — EMA crossover + SuperTrend pyramid scalper, full 12-layer stack.

Overview

Pipsgrowth EX03027 is a pyramid-style scalper that builds a position up to five layers deep, but only when an EMA(9/21) crossover agrees with a manual SuperTrend(10, 3.0) state machine. The EA was written for XAUUSD on the M5 chart, runs an internal iMA + iATR stack, and was designed so a single directional move can be scaled into without martingale multiplication: every layer is sized by the same risk-percent formula, just capped by MaxLotSize.

The signal path is straightforward. On every tick that survives the risk gate, OnTick copies the latest three values from the fast EMA and slow EMA buffers, with the buffers set as series so the most recent closed bar sits at index 1. A buy is recognized when fastMA[1] is above slowMA[1] while fastMA[2] was still at or below slowMA[2], and a sell is the mirror. That crossover is then filtered by superTrendDirection: a buy only fires when the SuperTrend state is +1 (uptrend), a sell only when it is -1 (downtrend). A flat or missing SuperTrend value produces no entry, even on a perfect EMA cross.

The SuperTrend itself is computed inline rather than via iCustom. InitSuperTrendHistory replays 200 bars on initialization to seed the state variables (final upper band, final lower band, and direction) so the EA does not start with a broken state. After init, CalculateSuperTrend runs once per new bar inside OnTick, guarded by a static lastCalcTime that compares iTime(_Symbol, _Period, 0). The basic upper band is (High + Low) / 2 + multiplier * ATR, and the basic lower band is the mirror; the final band is the basic band unless the previous bar's close violated the prior final band, in which case the final band tightens. Direction flips when the bar close pierces the active final band on the other side.

Pyramiding is layered on top of the first position. When a position is open and UsePyramiding is true, ManagePyramid walks PositionsTotal in reverse, picks the most recently opened position belonging to this EA's magic, and measures the distance from that entry to the current bid (for longs) or ask (for shorts). If the price has moved at least PyramidStep_Pips = 30 pips in the favorable direction and MinSecondsBetweenAdds = 60 seconds have elapsed since lastTradeTime, another layer is added — but only if SuperTrend still agrees with the existing direction. MaxLayers defaults to 5, so a fully built pyramid is the first entry plus four adds. Lots are not multiplied: every layer goes through the same CalcLot path, and the only ceiling is MaxLotSize = 10.0.

Position management is partial in the current build. The safety switch UseBEAfterLayer2 calls ApplySLToAll(GetAveragePrice()) once the position count reaches 2, which sets every layer's stop to the volume-weighted average entry, effectively moving the basket to breakeven. UseTrailAfterLayer3 is wired up but the trailing block in ManageExitLogic is unfinished in the source: it calculates trailDist and the current price but never actually modifies the stop, so once a pyramid reaches three layers the EA does not ratchet the SL forward behind price. A reverse EMA crossover is the actual exit signal — IsReverseSignal calls CloseAllPositions on a crossover against the current direction, which is the path the strategy relies on to take profit.

Risk control sits in two layers. The first is the live gate at the top of OnTick: IsRiskStopHit checks the running daily P&L against DailyMaxLossPct = 5.0% of initialEquityOfDay, and that one switch halts the EA for the rest of the day if tripped. MaxEquityDDPct = 10.0% is exposed in the inputs but is not used to gate OnTick in the current code. The second is IsSafeToTrade_EX03027, which rejects entries (but not exits) when the local time falls outside the detected GMT London 7-16 and New York 12-21 windows, when equity is below InpEquityFloor, when realized losses exceed InpDailyLossLimit or InpWeeklyLossLimit, when the account balance is at or above InpCapitalCap, when g_dailyTrades has hit InpMaxTradesPerDay = 50, or when the consecutive-loss counter has reached InpMaxConsecLosses. The OnTradeTransaction handler also installs a 30-minute cooldown after a third consecutive loss in the current session, even when the consec-losses input is set to 0.

Sizing is auto by default. With UseAutoLot = true, CalcLot multiplies account balance by RiskPerTradePct = 0.5% / 100, divides by stopPts * tickVal to get a notional lot, clamps to MaxLotSize, and floors to the symbol's volume step. With UseAutoLot = false, every layer simply uses InitialLot = 0.01. Slippage tolerance is SlippagePts = 5 points, and execution retries TryOpen_EX03027 up to three times with a 200ms sleep on REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED retcodes before giving up on the tick. Filling is set to ORDER_FILLING_FOK.

The session layer is double-stacked. The visible TradingSessionHours input is parsed by IsTradingTime into a server-time window (default "08:00-20:00"), which gates raw tick processing. On top of that, InActiveSession_EX03027 rebuilds the time in GMT using DetectGMTOffset_EX03027 (a heuristic that walks offsets from -12 to +12 and scores the candidate that lands on a weekday between 07:00 and 21:00 GMT) and accepts the trade only inside the London or New York windows. The result is a Gold scalper that effectively only acts during the London and New York sessions in GMT, regardless of where the broker's server clock sits.

A small dashboard label in the upper-left corner reports the current state when ShowDashboard is on. It lists status (Running or RISK STOP HIT), SuperTrend direction (UP / DOWN / FLAT), open count against MaxLayers, the day's running loss percentage, and current account equity, refreshed on every tick. The label is created with ObjectCreate as OBJ_LABEL and torn down in OnDeinit.

What to expect on a backtest. OnTester scores the EA as (profit / maxDD) * (profitFactor when PF > 1) with a hard floor of zero when maxDD is zero or trades < 10, so the optimizer is rewarded for return per unit of equity drawdown rather than raw profit. In practice, EX03027 produces a sequence of EMA crosses that line up with SuperTrend flips, opens a five-layer pyramid on the strongest trends, sits on breakeven on the second layer, and exits on the next counter-crossover or per-trade TP at 80 pips. Traders who want a real trailing stop behind a deep pyramid will need to extend ManageExitLogic — that piece is the obvious place to add the trail that is currently declared in the inputs but not implemented in the code.

Strategy Deep Dive

On every tick that survives the risk and session gates, OnTick copies the last three values from the fast and slow EMA buffers with ArraySetAsSeries, derives a buy or sell crossover from index 1 vs index 2, and then reads the SuperTrend direction (a manual state machine updated only on new bars) to confirm the cross. The first entry is the most conservative: it requires both an EMA cross and SuperTrend agreement with that direction, with the basket flat. ManagePyramid then watches the most recently opened position, waits PyramidStep_Pips = 30 pips in the favorable direction, and opens another layer — at the same lot size, not multiplied — provided the 60-second cooldown has passed and SuperTrend has not flipped. The SL is 50 pips and TP is 80 pips on every layer, then once the position count reaches 2, ApplySLToAll(GetAveragePrice()) moves every stop to the basket's average entry. The day-over-day risk layer is enforced in two places: IsRiskStopHit blocks all processing once the day's P&L breaches DailyMaxLossPct = 5.0%, and IsSafeToTrade_EX03027 refuses new entries outside the GMT London/New York session mask, below the equity floor, past the daily/weekly loss limit, or above the cap balance. OnTradeTransaction tracks realized P&L and forces a 30-minute cooldown after a third consecutive loss even when the consec-losses input is left at 0.

Entry Signal

Entry triggers on a confirmed EMA(9) crossing above EMA(21) (or the mirror for sells), gated by an in-house SuperTrend(10, 3.0) state machine that must read +1 for buys and -1 for sells. The crossover is detected on the most recent closed bar (index 1 vs index 2), so the EA never acts on a still-forming candle. A first position opens when the basket is flat; pyramids add at every 30-pip favorable step up to MaxLayers = 5, with a 60-second cooldown between additions and SuperTrend agreement required for every layer.

Exit Signal

Exits are driven by a reverse EMA crossover: when a buy-side pyramid sees the fast EMA drop below the slow EMA (or vice versa for sells), IsReverseSignal calls CloseAllPositions to flatten every layer in one pass. Per-trade take-profit at 80 pips is attached to every entry, so a single layer can also exit on its own TP before a counter-signal arrives. The basket is moved to breakeven via ApplySLToAll(GetAveragePrice()) once a second position is live, which seeds the exit path with a zero-risk stop on the average entry.

Stop Loss

Each position opens with a 50-pip stop loss computed by PipsToPoints(StopLossPips) in OpenTrade. After the second layer opens, ApplySLToAll rewrites every layer's stop to the volume-weighted average entry, putting the basket at breakeven. The trailing stop declared in the inputs (UseTrailAfterLayer3 + TrailOffsetPips = 20) is not actually implemented in ManageExitLogic — the EA does not ratchet the stop forward behind price once the pyramid reaches three layers.

Take Profit

Every entry attaches a fixed 80-pip take-profit (TakeProfitPips) computed as PipsToPoints(80) * _Point, so individual layers exit on their own TP without waiting for the basket signal. There is no basket-level TP — the only collective exit is the reverse EMA crossover via CloseAllPositions. With the default 50-pip SL and 80-pip TP, the per-layer risk/reward is 1:1.6.

Best For

Built for XAUUSD on M5, EX03027 needs an ECN or low-spread Gold broker to keep the spread gate (MaxSpread_Pips = 20) from blocking entries during volatile opens. Recommended balance: $100 minimum, but realistically $300+ to survive a 5-layer pyramid at 0.5% per layer through normal Gold volatility. Best run during the GMT London 7-16 and New York 12-21 windows enforced by InActiveSession_EX03027 — the EA will refuse to open outside those hours regardless of TradingSessionHours. The VERY_HIGH risk label reflects both the pyramid depth and the incomplete trailing implementation, so this is suited to traders who are comfortable with basket exposure and willing to extend ManageExitLogic themselves if they want a real ratchet behind deep pyramids.

Strategy Logic

Pipsgrowth EX03027 Grid — Strategy Logic Analysis (from .mq5 source)

Family: Grid Magic: 22203027 Version: 2.00

BRIEF: Equal-lot pyramid scalper using EMA crossover + SuperTrend confirmation. Pyramiding with fixed or auto lot capped by MaxLotSize (no martingale). Breakeven after layer 2, trailing after layer 3. Session filter and daily/equity drawdown stops. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • OpenTrade()
  • ManagePyramid()
  • ManageExitLogic()
  • IsRiskStopHit()
  • UpdateDailyStats()
  • GetAveragePrice()
  • ApplySLToAll()
  • CloseAllPositions()
  • CountPositions()
  • IsReverseSignal()
  • CalculateSuperTrend()
  • InitSuperTrendHistory()
  • ...and 16 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (20 total across 6 groups):

  • [=== Risk Management ===] InitialLot = 0.01 // Fixed Lot (if AutoLot=false)
  • [=== Risk Management ===] UseAutoLot = true // Use Dynamic Lot Sizing
  • [=== Risk Management ===] RiskPerTradePct = 0.5 // Risk % per trade (e.g. 0.5%)
  • [=== Risk Management ===] MaxLotSize = 10.0 // Hard cap for Lot Size
  • [=== Risk Management ===] MaxEquityDDPct = 10.0 // Hard Stop if Equity drops > X%
  • [=== Risk Management ===] DailyMaxLossPct = 5.0 // Stop trading for day if Loss > X%
  • [=== Trade Settings ===] UsePipsInputs = true // Inputs below in Pips (true) or Points (false)
  • [=== Trade Settings ===] StopLossPips = 50 // Initial Stop Loss
  • [=== Trade Settings ===] TakeProfitPips = 80 // Initial Take Profit (per trade)
  • [=== Trade Settings ===] SlippagePts = 5 // Max Slippage in Points
  • [=== Pyramiding ===] MaxLayers = 5 // Max open positions
  • [=== Pyramiding ===] PyramidStep_Pips = 30 // Min distance for next layer
  • [=== Pyramiding ===] MinSecondsBetweenAdds = 60 // Cooldown between entries
  • [=== Management ===] UseBEAfterLayer2 = true // Move SL to BE after 2 trades
  • [=== Management ===] UseTrailAfterLayer3 = true // Trail SL after 3 trades
  • [=== Management ===] TrailOffsetPips = 20 // Distance to trail behind price (if enabled)
  • [=== Filters ===] MaxSpread_Pips = 20.0 // Max allowed spread
  • [=== Filters ===] MinFreeMarginPct = 300.0 // Min Free Margin % to open new trade
  • [=== Filters ===] TradingSessionHours = "08:00-20:00" // "HH:MM-HH:MM" (Server Time)
  • [=== Hardening Trade Safety ===] InpMaxConsecLosses = 0 // --- Global Variables ---
Pseudocode
// Pipsgrowth EX03027 Grid — Execution Flow (from source analysis)
// Family: Grid
// Equal-lot pyramid scalper using EMA crossover + SuperTrend confirmation. Pyramiding with fixed or auto lot capped by MaxLotSize (no martingale). Breakeven after layer 2, trailing after layer 3. Session filter and daily/equity drawdown stops. 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

Optimized Brokers:
ExnessIC Markets
Optimized Symbols:
XAUUSD
Optimized Timeframes:
M5

How to Install This EA on MT5

  1. 1Download the .mq5 file using the button above
  2. 2Open MetaTrader 5 on your computer
  3. 3Click File → Open Data Folder in the top menu
  4. 4Navigate to MQL5 → Experts and paste the .mq5 file there
  5. 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
  6. 6Drag the EA onto a chart — H1 or H4 is recommended for grid EAs
  7. 7Set grid step (pips), maximum orders, and lot size in the EA dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InitialLot0.01Fixed Lot (if AutoLot=false)
UseAutoLottrueUse Dynamic Lot Sizing
RiskPerTradePct0.5Risk % per trade (e.g. 0.5%)
MaxLotSize10.0Hard cap for Lot Size
MaxEquityDDPct10.0Hard Stop if Equity drops > X%
DailyMaxLossPct5.0Stop trading for day if Loss > X%
UsePipsInputstrueInputs below in Pips (true) or Points (false)
StopLossPips50Initial Stop Loss
TakeProfitPips80Initial Take Profit (per trade)
SlippagePts5Max Slippage in Points
MaxLayers5Max open positions
PyramidStep_Pips30Min distance for next layer
MinSecondsBetweenAdds60Cooldown between entries
UseBEAfterLayer2trueMove SL to BE after 2 trades
UseTrailAfterLayer3trueTrail SL after 3 trades
TrailOffsetPips20Distance to trail behind price (if enabled)
MaxSpread_Pips20.0Max allowed spread
MinFreeMarginPct300.0Min Free Margin % to open new trade
TradingSessionHours"08:00-20:00""HH:MM-HH:MM" (Server Time)
InpMaxConsecLosses0--- Global Variables ---
Source Code (.mq5)Open Source
Pipsgrowth_com_EX03027.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX03027 Gold_EMA_SuperTrend — EMA crossover + SuperTrend pyramid scalper, full 12-layer stack."

#include <Trade\Trade.mqh>

// --- Input Groups ---

input group "=== Risk Management ==="
input double InitialLot          = 0.01;      // Fixed Lot (if AutoLot=false)
input bool   UseAutoLot          = true;      // Use Dynamic Lot Sizing
input double RiskPerTradePct     = 0.5;       // Risk % per trade (e.g. 0.5%)
input double MaxLotSize          = 10.0;      // Hard cap for Lot Size
input double MaxEquityDDPct      = 10.0;      // Hard Stop if Equity drops > X%
input double DailyMaxLossPct     = 5.0;       // Stop trading for day if Loss > X%

input group "=== Strategy Settings ==="
input int    FastEMAPeriod       = 9;
input int    SlowEMAPeriod       = 21;
input ENUM_MA_METHOD MAMethod    = MODE_EMA;
input int    SuperTrendPeriod    = 10;
input double SuperTrendMultiplier = 3.0;

input group "=== Trade Settings ==="
input bool   UsePipsInputs       = true;      // Inputs below in Pips (true) or Points (false)
input int    StopLossPips        = 50;        // Initial Stop Loss
input int    TakeProfitPips      = 80;        // Initial Take Profit (per trade)
input int    SlippagePts         = 5;         // Max Slippage in Points
input int    MagicNumber         = 22203027;
input string InpTradeComment     = "Psgrowth.com Expert_03027";

input group "=== Pyramiding ==="
input bool   UsePyramiding       = true;
input int    MaxLayers           = 5;         // Max open positions
input int    PyramidStep_Pips    = 30;        // Min distance for next layer
input int    MinSecondsBetweenAdds = 60;      // Cooldown between entries

input group "=== Management ==="
input bool   UseBEAfterLayer2    = true;      // Move SL to BE after 2 trades
input bool   UseTrailAfterLayer3 = true;      // Trail SL after 3 trades
input int    TrailOffsetPips     = 20;        // Distance to trail behind price (if enabled)

input group "=== Filters ==="
input double MaxSpread_Pips      = 20.0;      // Max allowed spread
input double MinFreeMarginPct    = 300.0;     // Min Free Margin % to open new trade
input string TradingSessionHours = "08:00-20:00"; // "HH:MM-HH:MM" (Server Time)

input group "=== Visuals ==="
input bool   ShowDashboard       = true;

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 ==="

Full source code available on download

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

Tags:ex03027gridpipsgrowthfreemt5xauusd

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

Community

Sign in to contributeSign In

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

File NamePipsgrowth_com_EX03027.mq5
File Size29.0 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyGrid
Risk LevelVery High Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100