P
PipsGrowth
GridOpen Source – Free

Pipsgrowth EX03021 Grid

MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1

Pipsgrowth.com EX03021 GridXPro — grid with optional martingale for major pairs, full 12-layer stack.

Overview

Pipsgrowth EX03021 GridXPro is a directional long grid EA that builds a single one-sided ladder of buy orders whenever the position stack is empty, and unwinds the whole basket as soon as combined unrealized P/L clears a profit threshold. There are no indicators and no per-trade stops. The only analytical input is the price ladder itself, expressed in InpGridStep (default 50 points). On every tick where CountOpen() returns zero and the static active flag is false, the EA fires a market buy at the current ask (TryBuy_EX03021(InpInitialLot, ask, 0, 0, ...)) and then immediately arms a sequence of pending BuyLimit orders at descending prices: ask - i * InpGridStep * _Point for i = 1 to InpMaxLevels - 1 (default InpMaxLevels = 10, so the ladder has 9 pending limits stacked under the entry). The active flag prevents the same ladder from being rebuilt until the basket is closed and reset.

The lot for each pending limit follows one of two regimes selected by InpMartingale. When the boolean is false (the safer default), every level trades InpInitialLot (0.01). When true, level i trades NormalizeDouble(InpInitialLot * pow(InpMultiplier, i), 2) — so with the default InpMultiplier = 1.5 and 10 levels, the bottom of the stack reaches 0.01 × 1.5^9 = 0.38 lots, and the geometric sum across the 10 levels is around 0.65 lots of notional exposure. The martingale switch is therefore the single most consequential input in the entire file: it transforms the EA from a flat-scaling grid into a convex one, and most users will leave it off.

The exit is also a single all-or-nothing rule. OnTick reads the combined unrealized P/L of every position whose POSITION_MAGIC matches InpMagicNumber (22203021) via BasketProfit(), and compares it to InpGridStep * _Point * CountOpen() * 100 * 0.5. The threshold therefore scales linearly with both the grid step and the number of open levels — fill the ladder deeper, and the basket needs a larger dollar move in the favorable direction to trigger the close. When the threshold is reached the EA calls CloseAll(), which walks PositionsTotal() in reverse and calls trade.PositionClose(ticket) on each magic-matching ticket (wrapped by TryClose_EX03021), and then walks OrdersTotal() and trade.OrderDelete(ticket) on each magic-matching pending order. The active flag is reset, and the next empty-state tick will rebuild a fresh ladder. There is no per-trade take-profit and no per-trade stop-loss on any individual order; the only exit is the basket-level trip.

The protective stack around this simple core is fairly conservative. IsSafeToTrade_EX03021 returns false and the EA short-circuits when any of these conditions hold: not inside an active session (no Saturday/Sunday, plus London 7-16 GMT ∪ New York 12-21 GMT when InpUseGMTSessions is true — detected through the EA's own DetectGMTOffset_EX03021, which tests every offset from -12 to +12 and picks the one that scores highest on weekday-in-range plus hour-in-trading-day); TimeCurrent() < g_cooldownUntil; equity below InpEquityFloor; cumulative realized P/L for the day below -InpDailyLossLimit; weekly P/L below -InpWeeklyLossLimit; account balance at or above the InpCapitalCap ceiling; daily trade count at or above InpMaxTradesPerDay (50); or g_consecLossesHD >= InpMaxConsecLosses when that input is positive. Note the cooldown path is also triggered independently through OnTradeTransaction: whenever a closed deal for this magic shows a negative total (profit + swap + commission), the function increments g_consecLossesHD; once the count reaches 3 (a hardcoded threshold inside the transaction handler, separate from the InpMaxConsecLosses gate which is 0 by default) the EA sets g_cooldownUntil = TimeCurrent() + InpCooldownMinutes * 60 — 30 minutes by default. So even with InpMaxConsecLosses = 0 and InpMaxTradesPerDay = 50 left as the permissive defaults, the EA will still pause for half an hour after three back-to-back losses.

The trade functions are simple retry wrappers. TryBuy_EX03021 first clamps the lot down to the symbol's SYMBOL_VOLUME_STEP and within SYMBOL_VOLUME_MIN/MAX, then calls OrderCalcMargin to make sure margin is available — if marginRequired > ACCOUNT_MARGIN_FREE it prints a denial and returns without sending. The actual trade.Buy(...) is attempted up to three times, retrying only on TRADE_RETCODE_REQUOTE, _TIMEOUT, _PRICE_OFF, or _PRICE_CHANGED after a Sleep(200); any other retcode breaks the loop. TryBuyLimit_EX03021, TryClose_EX03021, and TryOrderDelete_EX03021 follow the same 3-attempt / 200 ms pattern. trade.SetDeviationInPoints(30) allows up to 3.0 pips of slippage on the market entry; pending limits are sent without deviation (they sit on the book until filled or deleted). The EA deliberately uses the symbol's current SYMBOL_VOLUME_STEP rather than a hardcoded 0.01, so it adapts to brokers that step in 0.001 or 0.1 lots.

OnTester returns a single number that drives the strategy tester optimizer: (profit / maxDD) * (pf > 1 ? pf : 0), guarded by maxDD > 0 and trades >= 10. The two factors are multiplied rather than added, so an optimizer that maximizes this value will favor profiles with both a high profit/maxDD ratio (calm equity) and a profit factor above 1.0. Below 10 trades the function returns 0, which means the optimizer will never promote a short backtest that doesn't actually trade — useful because empty grid ladders can produce a flat equity curve with zero trades and that should rank last, not first.

For live use, the relevant decisions are almost all the input values, not the logic. The default ladder of 10 levels with InpGridStep = 50 points and InpInitialLot = 0.01 requires roughly 0.10 lots of notional margin at the entry level, scaling up to about 0.65 lots notional if martingale is enabled. A broker with reasonable swap rates is preferable because the EA is designed to hold the basket for hours or days while the unwind completes; account types that pay negative swap on long gold or long majors will see the basket profit target erode quietly. Because the basket close scans PositionsTotal() for magic matches on every tick, the EA should be run on a single chart per symbol — running it twice on the same symbol (or on a different magic but same symbol with overlapping orders) will produce double-close races when both instances think the basket is theirs. The capital cap (InpCapitalCap > 0) is an underused but powerful safety: setting it to the maximum balance you want this EA to ever manage means the EA refuses to keep trading once the account has grown past that ceiling, which protects against unattended runaway compounding.

Strategy Deep Dive

On every tick the EA first rotates g_realizedToday/g_realizedWeek/g_dailyTrades when the day or week boundary crosses, then calls IsSafeToTrade_EX03021 which short-circuits on session, cooldown, equity floor, daily/weekly loss, capital cap, or daily-trade-count violations. If the gate passes, CountOpen() reports whether the basket is empty; if it is and active is false, the EA fires a market buy at the ask and arms a descending ladder of InpMaxLevels - 1 BuyLimits spaced by InpGridStep * _Point below it. Lots are flat at InpInitialLot when InpMartingale is off, or geometric at InpInitialLot * pow(InpMultiplier, i) when it's on. On subsequent ticks, the basket profit (BasketProfit() over every magic-matching position) is compared to a threshold that scales with InpGridStep and the open count, and CloseAll() fires when it's hit. The retry layer (TryBuy_EX03021, TryBuyLimit_EX03021, TryClose_EX03021, TryOrderDelete_EX03021) attempts each network-touching call up to 3 times at 200ms intervals on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED. OnTradeTransaction listens to TRADE_TRANSACTION_DEAL_ADD events for the magic, accumulates realized P/L into the daily/weekly totals, and forces a 30-minute cooldown once 3 consecutive losses register. OnTester returns (profit/maxDD) * (pf>1 ? pf : 0) for the optimizer, gated by trades >= 10 and maxDD > 0.

Entry Signal

Pipsgrowth EX03021 GridXPro enters long-only. On every tick where the position count for magic 22203021 is zero, it fires a market buy at the current ask of 0.01 lots and arms a ladder of 9 pending BuyLimit orders (with InpMaxLevels = 10) at descending prices of ask - i * 50 * _Point for i=1..9. The ladder rebuilds only after the basket has been closed and the static active flag has been reset.

Exit Signal

The exit is a basket-level trip only. On every tick, OnTick calls BasketProfit() to sum the unrealized P/L of every magic-matching position and compares it to InpGridStep * _Point * CountOpen() * 100 * 0.5. When the threshold is reached, CloseAll() walks positions in reverse and closes each via trade.PositionClose, then deletes every matching pending order. There is no per-trade SL and no per-trade TP.

Stop Loss

There is no per-trade stop-loss on any order. Risk is controlled at the basket level by InpEquityFloor, InpDailyLossLimit, InpWeeklyLossLimit, InpCapitalCap, the 50-trades-per-day cap, and the 30-minute cooldown that hard-fires after 3 consecutive losses via OnTradeTransaction.

Take Profit

The basket take-profit is the formula InpGridStep * _Point * CountOpen() * 100 * 0.5 — i.e. the threshold grows linearly with both the configured grid step (50 points by default) and the number of open positions. There is no per-trade take-profit; the EA only closes when the combined unrealized P/L clears this scaling target.

Best For

Best suited for traders running EX03021 on FX majors (EURUSD, GBPUSD, USDJPY) on the M5 timeframe, who want a one-sided long grid with a flat-scaling ladder and basket-only exits. Minimum recommended balance is $100 with the default 0.01-lot, 10-level, martingale-off configuration; raise the deposit or lower InpMaxLevels for live accounts since the EA is rated VERY_HIGH risk. Use a low-spread, swap-friendly ECN or standard account so the basket profit target is not eroded overnight, and run on a single chart per symbol to avoid magic-collision double-closes.

Strategy Logic

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

Family: Grid Magic: 22203021 Version: 2.00

BRIEF: Grid system with optional martingale lot progression for major pairs. Places initial buy and a ladder of BuyLimit orders at fixed grid step intervals. Closes basket on combined profit target. Martingale is OFF by default for safety. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • BasketProfit()
  • CountOpen()
  • CloseAll()
  • DetectGMTOffset_EX03021()
  • ServerToGMT_EX03021()
  • InActiveSession_EX03021()
  • UpdateDailyCounters_EX03021()
  • IsSafeToTrade_EX03021()
  • TryBuy_EX03021()
  • TryBuyLimit_EX03021()
  • TryClose_EX03021()
  • TryOrderDelete_EX03021()
  • ...and 1 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (0 total across 0 groups):

Pseudocode
// Pipsgrowth EX03021 Grid — Execution Flow (from source analysis)
// Family: Grid
// Grid system with optional martingale lot progression for major pairs. Places initial buy and a ladder of BuyLimit orders at fixed grid step intervals. Closes basket on combined profit target. Martingale is OFF by default for safety. 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:
M5H1

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
Source Code (.mq5)Open Source
Pipsgrowth_com_EX03021.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX03021 GridXPro — grid with optional martingale for major pairs, full 12-layer stack."

#include <Trade\Trade.mqh>
input group "=== Grid Settings ==="
input int    InpGridStep     = 50;
input bool   InpMartingale   = false;
input double InpMultiplier   = 1.5;
input double InpInitialLot   = 0.01;
input int    InpMaxLevels    = 10;
input group "=== Identity ==="
input int    InpMagicNumber  = 22203021;
input string InpTradeComment = "Psgrowth.com Expert_03021";

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;

CTrade trade;
bool active=false;

//--- Hardening Globals
double   g_realizedToday  = 0;
double   g_realizedWeek   = 0;
datetime g_dayStartTime   = 0;
datetime g_weekStartTime  = 0;
int      g_gmtOffset      = 3;
int      g_dailyTrades    = 0;
int      g_consecLossesHD = 0;
datetime g_cooldownUntil  = 0;

int OnInit() { trade.SetExpertMagicNumber(InpMagicNumber); trade.SetDeviationInPoints(30); g_gmtOffset = DetectGMTOffset_EX03021(); g_dayStartTime = TimeCurrent(); g_weekStartTime = TimeCurrent(); PrintFormat("GMT offset auto-detected: %d", g_gmtOffset); return INIT_SUCCEEDED; }
void OnDeinit(const int r) {}
void OnTick() {
   UpdateDailyCounters_EX03021();
   if(!IsSafeToTrade_EX03021()) return;
   int cnt=CountOpen();
   double basket=BasketProfit();
   if(cnt>0 && basket >= InpGridStep*_Point*cnt*100*0.5) { CloseAll(); active=false; return; }
   if(cnt==0 && !active) {
      active=true;
      double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
      TryBuy_EX03021(InpInitialLot,ask,0,0,InpTradeComment);

Full source code available on download

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

Tags:ex03021gridpipsgrowthfreemt5xauusd

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_EX03021.mq5
File Size12.0 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyGrid
Risk LevelVery High Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100