P
PipsGrowth
GridOpen Source – Free

Pipsgrowth EX03010 Grid

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX03010 GoldPyramid_XAUUSD_5M — ADX/EMA pyramid with risk-based lot sizing, full 12-layer stack.

Overview

Pipsgrowth EX03010 Grid is a minimal, indicator-light pyramid stacker for XAUUSD on the M5 chart. The whole entry engine runs on two MT5 indicators — iADX with a 14-period default and an EMA(50) trend filter — and the only thing the EA does is open a position when ADX confirms a trend, then keep adding to that position while price keeps running. The header calls it a 'Gold pyramid EA using ADX trend strength and EMA filter for entry' and that description is unusually literal: there is no regime classifier, no multi-timeframe alignment, no Heikin-Ashi, no HTF confirmation. The 16 input parameters expose almost every tunable constant in the code, because the source uses 0 #define constants — every magic number is an input.

The first trade is opened by CheckSignal(), which runs only on a closed bar (the OnTick handler keeps a static datetime lastBar and only fires the signal path when the bar changes). CheckSignal() reads ADX(1) and EMA(1) with CopyBuffer and grabs iClose(_Symbol, _Period, 1). A long signal requires ADX(1) > InpADXThreshold (25.0 by default) AND close(1) > EMA(1). A short signal requires ADX(1) > 25.0 AND close(1) < EMA(1). Critically, the function counts existing positions first and returns immediately if any buy or sell is open — CheckSignal() never opens into an existing pyramid, it only seeds it. The first trade is the seed; everything else is ManagePyramid().

ManagePyramid() runs on every tick (no new-bar gate) and is the only path that adds to an existing position. It counts open buys and sells with the magic filter, and for the side that is below InpMaxPositions (3 by default) it walks the position list to find the extremal ticket: the highest open buy price for long stacking, the lowest open sell price for short stacking. If the current bid is more than InpPyramidDist (200 points) above the highest buy, it opens another buy. The mirror fires for sells. Every pyramid layer uses the same CalculateLotSize() formula as the seed trade — the EA does not scale pyramid lots, the new ticket gets the same risk-percent-sized lot as the first one. There is one quirk worth flagging: InpProfitLock is exposed in the input group 'Pyramiding' with a default of 100 and a comment that reads 'Min Profit needed to Add', but the ManagePyramid() function never reads it. The 'profit-locked' framing in the brief is aspirational — the live logic is distance-locked, not profit-locked. Users who want profit-gated stacking have to add the check themselves or treat the input as documentation.

CalculateLotSize() converts InpRiskPercent (0.5% by default — explicitly lowered for pyramiding per the input comment) into a notional risk budget, divides by the per-point value of the symbol across InpStopLoss (400 points), and rounds the result down to the broker's lot step. If InpRiskPercent is 0 or the symbol's tick math is degenerate, it falls back to InpFixedLot (0.01). The lot is then clamped to SymbolInfoDouble min/max and re-rounded. The 0.5% default is the right call for a 3-layer pyramid on gold — three tickets against you at 1% each is a known bad day, three at 0.5% is a recoverable one.

Per-trade protective levels are fixed. InpStopLoss is 400 points (4.00 USD on a 0.01 XAUUSD ticket at 1 USD/point) and InpTakeProfit is 1200 points (12.00 USD on the same ticket) — a 1:3 reward-to-risk ratio. The TP is intentionally wide for a trend EA: the comment in the source reads 'Wide for Trend' and the math fits a 3-layer pyramid whose average entry is dragged toward the running top. The 1:3 RR plus a 200-point pyramid step means the average layer needs roughly 400 points of trend before the basket breaks even, which is the right read for XAUUSD M5 bursts.

Trade management has only two safety switches in the entry path: a spread filter that returns out of OnTick when the broker's spread exceeds InpMaxSpread (250 points — 25.0 pips on a 2-decimal XAUUSD broker), and the full IsSafeToTrade_EX03010 gate. The gate runs in this order: InActiveSession_EX03010 (London 7-16 GMT ∪ NY 12-21 GMT if InpUseGMTSessions is true, weekend blocked), g_cooldownUntil vs TimeCurrent(), InpEquityFloor (disabled at 0.0), InpDailyLossLimit and InpWeeklyLossLimit (both 0.0 disabled), InpCapitalCap (returns false when balance >= cap, also 0.0 disabled), InpMaxTradesPerDay (50), and finally InpMaxConsecLosses (0 default → disabled). The session math is fed by DetectGMTOffset_EX03010(), a best-of-scan over offsets from -12 to +12 that scores weekday 1-5 with +10 and hour 7-21 with +5, and stamps the winner into g_gmtOffset at init.

The OnTradeTransaction hook tracks g_realizedToday, g_realizedWeek, and g_consecLosses. On every DEAL_ENTRY_OUT or DEAL_ENTRY_INOUT for the magic 22203010 on the current symbol, it accumulates profit+swap+commission into the day and week totals, increments g_consecLosses on a loss, and resets it to 0 on a win. There is a second quirk here: the cooldown branch is hard-coded to trigger at 3 consecutive losses, regardless of InpMaxConsecLosses. The source uses g_consecLosses >= 3 with InpCooldownMinutes (30) when InpCooldownMinutes > 0, so a user who wants the cooldown to fire at 5 losses has to edit the source — the input is not wired to the threshold. The default config (InpCooldownMinutes=30, magic-locked at 3 losses) means losing 3 in a row during a session stops new entries for 30 minutes.

Order execution goes through TryBuy_EX03010 / TrySell_EX03010, each of which does lot rounding, calls OrderCalcMargin to reject on insufficient free margin, then loops up to 3 times on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED with a 200 ms Sleep between attempts. On success, g_dailyTrades is incremented. The trade object is configured at OnInit with SetExpertMagicNumber, SetDeviationInPoints(3), and SetTypeFilling(ORDER_FILLING_FOK). The 3-point slippage tolerance is tight; on a high-latency connection the FOK retry path will burn through attempts and the EA will move on to the next tick.

The OnTester fitness function is a clean two-factor blend: (profit / maxDD) * (PF > 1 ? PF : 0), gated at maxDD > 0 and trades >= 10. The PF clamp means a sub-1.0 profit factor returns zero — a strategy that bleeds slowly into a small maxDD does not pass the tester gate. There is no min trade count beyond 10, no Sharpe component, no recovery factor, no trade-frequency shaping.

In a backtest, expect the EA to take very few trades on ranging days (ADX<25 simply never fires) and burst into a multi-layer run on trend days. The single biggest tuning lever is InpADXThreshold — drop it to 18 and the EA will fire on weaker trends, raise it to 30 and only the strongest moves produce a seed. The second lever is InpPyramidDist: tighter spacing builds the pyramid faster and exposes more to mean-reversion, wider spacing gives the seed trade room to breathe before the EA commits more risk. Users running this on a prop-firm challenge should wire InpDailyLossLimit and InpWeeklyLossLimit to the prop's daily and overall drawdown rules — leaving them at 0.0 means the EA will keep trading through a 50% account loss, which is the failure mode that ends most prop challenges.

The compiled .mq5 is portable across any MetaTrader 5 build that supports the standard Trade.mqh, PositionInfo.mqh, SymbolInfo.mqh, and AccountInfo.mqh includes. The EA will not run on MetaTrader 4. The magic number 22203010, the 0.01 fallback lot, the 0.5% risk default, and the 1:3 RR are tuned for a sub-$1000 XAUUSD micro account — the labelled minimum deposit is $100 but in practice the EA needs enough free margin to absorb a 3-layer stack at the configured risk, so $500 is the realistic floor for a live deployment.

Strategy Deep Dive

OnTick refreshes symbol rates, rotates daily and weekly counters when the date changes, and immediately bails out if the broker spread exceeds InpMaxSpread (250 points). The full IsSafeToTrade_EX03010 gate runs next — session check, cooldown timer, equity floor, daily/weekly loss limits, capital cap, and per-day trade cap. ManagePyramid() then runs on every tick, walking PositionsTotal() to find the extremal ticket on each side and adding a new layer when price advances InpPyramidDist (200 points) past it, capped at InpMaxPositions (3) per side with no profit gate. The first-trade path is gated behind a new-bar check, and CheckSignal() reads ADX(1) and EMA(1) once per closed bar to seed the pyramid with a long when ADX>25 and close>EMA, or a short when ADX>25 and close<EMA — but only if the EA has no open positions on the symbol. Every new ticket uses CalculateLotSize() with InpRiskPercent (0.5% default) and the fixed 400-point stop, and the order is sent through TryBuy_EX03010 / TrySell_EX03010 with three retry attempts at 200 ms on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED. The OnTradeTransaction hook updates g_realizedToday, g_realizedWeek, and g_consecLosses per closed deal, hard-coding a 30-minute cooldown at three consecutive losses. OnTester returns (profit / maxDD) × PF when PF>1, gated at maxDD>0 and trades>=10.

Entry Signal

CheckSignal() opens the first trade on a closed bar when ADX(14) at shift=1 reads above 25.0 and the close(1) is on the same side of EMA(50) — long if close>EMA, short if close<EMA. The function counts open positions first and refuses to seed if any ticket with magic 22203010 is already live, so the first entry is always the pyramid's seed trade. Subsequent layers are added by ManagePyramid() on every tick when the current bid is at least InpPyramidDist (200 points) above the highest open buy, or the ask is at least that far below the lowest open sell, capped at InpMaxPositions (3) tickets per side.

Exit Signal

There is no managed exit beyond the per-trade SL and TP attached at order time. The fixed 400-point stop and 1200-point target on every ticket are the only exits the EA ever sends — no trailing, no breakeven, no opposite-signal close, no time-based exit. The basket is closed implicitly when every ticket hits its own SL or TP, or when the user manually closes the stack. The cooldown gate stops new entries but does not close existing positions.

Stop Loss

Every position gets a fixed InpStopLoss of 400 points (4.00 USD on a 0.01-lot XAUUSD ticket) attached at order time, and the EA never modifies that stop afterward — there is no trailing, no breakeven, no profit lock, and no basket-level drawdown cap. The risk on a 3-layer stack is therefore 12.00 USD on 0.01-lot tickets, which is why the InpRiskPercent default is 0.5% and not the more typical 1%.

Take Profit

Each ticket carries a fixed InpTakeProfit of 1200 points (12.00 USD on a 0.01-lot XAUUSD ticket), giving a 1:3 reward-to-risk ratio against the 400-point stop. The wide TP is intentional — the input comment reads 'Wide for Trend' — because the average entry of a 3-layer pyramid drags toward the running top, and only a 3R target gives the average layer room to close in profit. There is no basket-level TP and no per-ticket partial close.

Best For

Traders who want a single-instrument XAUUSD pyramid on M5 with a 1:3 per-trade RR and a 0.5% risk-per-layer default, willing to accept that there is no managed exit beyond the fixed SL and TP. The minimum deposit label is $100 but a realistic live floor is $500 to absorb a 3-layer stack on a 2.5-pip-point gold symbol with comfortable free margin. The London 7-16 ∪ NY 12-21 GMT session gate, the 250-point max-spread filter, and the FOK execution make a low-spread ECN broker mandatory; the 3-point slippage tolerance and ORDER_FILLING_FOK retry loop will burn through attempts on a high-latency connection. Very high risk profile — leave the pyramid disabled (InpEnablePyramid=false) or set InpMaxPositions=1 to run this as a flat single-entry trend EA.

Strategy Logic

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

Family: Grid Magic: 22203010 Version: 2.00

BRIEF: Gold pyramid EA using ADX trend strength and EMA filter for entry. Pyramids into strong trends with risk-based lot sizing, fixed SL/TP, and profit-locked pyramid additions. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CheckSignal()
  • ManagePyramid()
  • CountPositions()
  • OpenBuy()
  • OpenSell()
  • CalculateLotSize()
  • DetectGMTOffset_EX03010()
  • ServerToGMT_EX03010()
  • InActiveSession_EX03010()
  • UpdateDailyCounters_EX03010()
  • IsSafeToTrade_EX03010()
  • TryBuy_EX03010()
  • ...and 2 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (16 total across 5 groups):

  • [=== Strategy Parameters ===] InpADXPeriod = 14 // ADX Period
  • [=== Strategy Parameters ===] InpADXThreshold = 25.0 // ADX Trend Strength
  • [=== Strategy Parameters ===] InpEMAPeriod = 50 // Trend Filter
  • [=== Money Management ===] InpRiskPercent = 0.5 // Risk Percent per Trade (Lower for Pyramiding)
  • [=== Money Management ===] InpFixedLot = 0.01 // Fixed Lot (if Risk=0)
  • [=== Money Management ===] InpStopLoss = 400 // Stop Loss (points)
  • [=== Money Management ===] InpTakeProfit = 1200 // Take Profit (points) (Wide for Trend)
  • [=== Pyramiding ===] InpEnablePyramid = true // Enable Pyramiding
  • [=== Pyramiding ===] InpMaxPositions = 3 // Max Positions Stacked
  • [=== Pyramiding ===] InpPyramidDist = 200 // Distance between entries (points)
  • [=== Pyramiding ===] InpProfitLock = 100 // Min Profit needed to Add
  • [=== Trade Management ===] InpMagicNumber = 22203010 // Magic Number
  • [=== Trade Management ===] InpTradeComment = "Psgrowth.com Expert_03010" // Trade Comment
  • [=== Trade Management ===] InpMaxSpread = 250 // Max Spread (points)
  • [=== Trade Management ===] InpSlippage = 3 // Slippage
  • [=== Hardening Trade Safety ===] InpMaxConsecLosses = 0 // --- Handles
Pseudocode
// Pipsgrowth EX03010 Grid — Execution Flow (from source analysis)
// Family: Grid
// Gold pyramid EA using ADX trend strength and EMA filter for entry. Pyramids into strong trends with risk-based lot sizing, fixed SL/TP, and profit-locked pyramid additions. 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
InpADXPeriod14ADX Period
InpADXThreshold25.0ADX Trend Strength
InpEMAPeriod50Trend Filter
InpRiskPercent0.5Risk Percent per Trade (Lower for Pyramiding)
InpFixedLot0.01Fixed Lot (if Risk=0)
InpStopLoss400Stop Loss (points)
InpTakeProfit1200Take Profit (points) (Wide for Trend)
InpEnablePyramidtrueEnable Pyramiding
InpMaxPositions3Max Positions Stacked
InpPyramidDist200Distance between entries (points)
InpProfitLock100Min Profit needed to Add
InpMagicNumber22203010Magic Number
InpTradeComment"Psgrowth.com Expert_03010"Trade Comment
InpMaxSpread250Max Spread (points)
InpSlippage3Slippage
InpMaxConsecLosses0--- Handles
Source Code (.mq5)Open Source
Pipsgrowth_com_EX03010.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX03010 GoldPyramid_XAUUSD_5M — ADX/EMA pyramid with risk-based lot sizing, full 12-layer stack."

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>

CTrade         trade;
CPositionInfo  position;
CSymbolInfo    mysymbol;
CAccountInfo   account;

//--- Input Groups
input group "=== Strategy Parameters ==="
input int      InpADXPeriod      = 14;       // ADX Period
input double   InpADXThreshold   = 25.0;     // ADX Trend Strength
input int      InpEMAPeriod      = 50;       // Trend Filter

input group "=== Money Management ==="
input double   InpRiskPercent    = 0.5;      // Risk Percent per Trade (Lower for Pyramiding)
input double   InpFixedLot       = 0.01;     // Fixed Lot (if Risk=0)
input int      InpStopLoss       = 400;      // Stop Loss (points)
input int      InpTakeProfit     = 1200;     // Take Profit (points) (Wide for Trend)

input group "=== Pyramiding ==="
input bool     InpEnablePyramid  = true;     // Enable Pyramiding
input int      InpMaxPositions   = 3;        // Max Positions Stacked
input int      InpPyramidDist    = 200;      // Distance between entries (points)
input int      InpProfitLock     = 100;      // Min Profit needed to Add

input group "=== Trade Management ==="
input int      InpMagicNumber    = 22203010; // Magic Number
input string   InpTradeComment   = "Psgrowth.com Expert_03010"; // Trade Comment
input int      InpMaxSpread      = 250;      // Max Spread (points)
input int      InpSlippage       = 3;        // Slippage

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;

//--- Handles
int    hADX;

Full source code available on download

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

Tags:ex03010gridpipsgrowthfreemt5xauusd

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_EX03010.mq5
File Size19.6 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyGrid
Risk LevelVery High Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100