P
PipsGrowth
GridOpen Source – Free

Pipsgrowth EX03019 Grid

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

Pipsgrowth.com EX03019 GoldGridMartingale — grid + martingale for XAUUSD, full 12-layer stack.

Overview

Pipsgrowth EX03019 — GoldGridMartingale is a fixed-step, long-only grid EA for XAUUSD, written as a minimal and direct take on the classic "ladder buy + basket close" approach. The source header talks about a 12-layer architecture, but the actual code is honest about what it does: a market buy to start a basket, a pre-placed ladder of BuyLimit orders at fixed price intervals, a basket-level profit target, and a hardening block that controls when new baskets are allowed to begin. There are no indicators on the chart, no signal-confirmation logic, and no per-trade stop-loss. Every decision comes down to price, count, and the equity/drawdown safety gates.

The entry path lives entirely inside OnTick(). On the first tick where the EA has no open positions and the active flag is false, the EA captures the current ask, sets basketBase = ask, flips active = true, and runs TryBuy_EX03019(InpInitialLot, ask, 0, 0, ...) to fire the initial market buy with no SL and no TP. The function does an OrderCalcMargin pre-check, then loops up to 3 times on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED with a 200ms Sleep() between attempts. After the market order is accepted, the EA loops from i = 1 to InpMaxLevels - 1 and places a BuyLimit at ask - i * InpGridStep * _Point. With the defaults — InpGridStep = 40 (40 cents of distance on a 2-decimal gold quote, or 0.40 on a 5-digit broker that quotes XAUUSD to two decimals), InpMaxLevels = 6, InpInitialLot = 0.01, InpMultiplier = 2.0 — the full ladder is six positions of 0.01 lots, since InpEnableMartingale defaults to false. Toggle it on and the lots escalate to 0.01, 0.02, 0.04, 0.08, 0.16, 0.32 (or however the broker's volume step rounds them), so the exposure profile flips from "all-in cheap" to "front-loaded revenge" the moment price drops through the ladder.

The exit path is the basket. BasketProfit() walks PositionsTotal() in reverse, filters by magic == 22203019 and symbol == _Symbol, and sums the position profits. OpenCount() does the same scan and returns the integer count. On every tick the EA checks if (cnt > 0 && basket >= InpTakeProfit * _Point * cnt * 100) — at the defaults, that is 80 cents per open position in account currency, because XAUUSD is 100 oz per lot and _Point * 100 = $1 of P&L per lot per whole dollar of price move. So 1 position = $80 target, 3 positions = $240, capped at whatever count is currently open. The moment that threshold is hit, CloseAll() walks the position list and the order list, calling TryClose_EX03019 and TryOrderDelete_EX03019 to flatten everything and cancel any remaining pending BuyLimits in the same pass. The active flag is then reset to false, so a fresh basket can form on the next flat tick.

There is no per-trade stop-loss, no trailing stop, no break-even, and no partial close. The SL inputs in trade.Buy() and trade.BuyLimit() are hard-coded to 0. Risk control lives entirely in the hardening input group, and almost all of it is off by default:

  • InpEquityFloor = 0 — set it to e.g. 200 and the EA stops opening new baskets once account equity drops below $200.
  • InpDailyLossLimit = 0 — if set, g_realizedToday <= -limit blocks new baskets.
  • InpWeeklyLossLimit = 0 — same idea on the weekly window.
  • InpCapitalCap = 0 — set it to e.g. 500 and the EA will not open new baskets once balance reaches $500 (i.e. a "stop trading once the account hits the target" cap).
  • InpMaxTradesPerDay = 50 — caps the number of fills per day.
  • InpCooldownMinutes = 30 with the implicit 3-loss trigger — g_cooldownUntil is armed inside OnTradeTransaction once g_consecLossesHD reaches 3.
  • InpMaxConsecLosses = 0 — this is the master switch; leaving it at 0 disables the cooldown entirely.

The four tightening defaults that matter for any live deployment: enable InpEquityFloor, enable InpDailyLossLimit, enable InpWeeklyLossLimit, and turn InpMaxConsecLosses on with a small value like 3 or 4. With all four at 0 and martingale off, a 6-level gold grid can still hand back weeks of profit in a single 240-cent move against the basket — the math is not on your side when the basket keeps averaging down into a runaway trend.

Session and time discipline is built into InActiveSession_EX03019(). The function pulls TimeCurrent(), converts to GMT via ServerToGMT_EX03019 (which subtracts the auto-detected g_gmtOffset found by DetectGMTOffset_EX03019 — a best-of -12..+12 heuristic that scores weekday and 07:00–21:00 hours), and checks two windows: London 07:00–16:00 and New York 12:00–21:00. If InpUseGMTSessions is on and the current hour falls in neither window, IsSafeToTrade_EX03019 returns false and the EA refuses to open a basket. Saturdays, Sundays, and the Asian session (00:00–07:00 GMT) are all flat by default. This is the right behaviour for a long-only gold grid — the heavy liquidity that closes baskets lives in London and the New York morning.

The OnTradeTransaction hook is the bookkeeping backbone. Every DEAL_ADD event filtered by magic 22203019 and the current symbol is unpacked: DEAL_ENTRY_IN increments g_dailyTrades; DEAL_ENTRY_OUT (or DEAL_ENTRY_INOUT) sums profit + swap + commission into g_realizedToday and g_realizedWeek, then either increments g_consecLossesHD (loss) or resets it to 0 (win). The cooldown trigger is hard-coded to 3 consecutive losses — once that fires, g_cooldownUntil = TimeCurrent() + 30*60 and the EA holds the line for 30 minutes before re-evaluating. UpdateDailyCounters_EX03019 rolls the daily window when the server-day changes and the weekly window when the server-day-of-week changes, so a basket that runs from Friday's close into Monday's open keeps its g_realizedWeek continuity while g_realizedToday resets at midnight.

The OnTester fitness function is a single line: (profit / maxDD) * (pf > 1 ? pf : 0), gated by maxDD > 0 and trades >= 10. That formulation rewards both recovery factor and profit factor, but zero PF returns zero fitness — so the optimizer prefers passes where the win rate is high enough that PF > 1 is meaningful. For grid EAs the trade count is rarely a problem, but the 10-trade gate does block optimization on very short backtests.

In terms of infrastructure, the EA calls trade.SetExpertMagicNumber(22203019) and trade.SetDeviationInPoints(30) in OnInit, then g_gmtOffset is auto-detected and g_dayStartTime / g_weekStartTime are seeded with TimeCurrent(). OnDeinit is empty — no cleanup, no chart-object teardown, no dashboard. There is no OnTrade, no timer, no chart event handler; the whole EA ticks off OnTick and the trade-transaction callback.

The honest read: this is a deliberately simple grid. No indicators, no fancy regime filter, no per-trade trail, no break-even, no partial close, no hedge leg, no news filter. It buys, it ladders, it waits for the basket to come back, and the safety stack is what keeps the account alive. The defaults are conservative on the martingale side (off) and unsafe on the loss-limit side (all zero) — turn on the loss limits before you flip the magic live.

Strategy Deep Dive

On every tick, OnTick() first calls UpdateDailyCounters_EX03019() to roll the daily/weekly P&L windows at midnight server time, then rejects the tick if SYMBOL_SPREAD > InpMaxSpread (50 points by default) or if IsSafeToTrade_EX03019() reports a blocked condition. With the gate clear, it sums up BasketProfit() and OpenCount() over positions filtered by InpMagicNumber = 22203019 and _Symbol; if any positions exist and the basket profit target is reached, CloseAll() flattens everything and resets the active flag. If the position count is zero and active is false — meaning no basket is in flight — the EA captures the current ask as basketBase, flips active = true, fires the initial market buy via TryBuy_EX03019, and lays down a ladder of InpMaxLevels-1 BuyLimit orders spaced InpGridStep * _Point below. Every order goes through a 3-attempt retry loop on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED with a 200ms backoff, and TryBuy_EX03019 does an explicit OrderCalcMargin pre-check so a margin shortfall fails fast without burning retry attempts. OnTradeTransaction hooks the trade engine's deal events to maintain g_realizedToday, g_realizedWeek, and g_consecLossesHD, and three consecutive losses automatically arm a g_cooldownUntil = TimeCurrent() + InpCooldownMinutes*60 (default 30 minutes) pause. The OnTester fitness function is (profit / maxDD) * (PF > 1 ? PF : 0) with a hard gate at 10 trades — any backtest with fewer deals or with maxDD <= 0 returns 0 and the optimizer skips that pass.

Entry Signal

The EA fires on the first tick where it has no open positions and the active flag is false — it opens a market buy at the current ask, captures that price as basketBase, then lays down a ladder of InpMaxLevels-1 BuyLimit orders at ask - i * InpGridStep * _Point for i = 1 .. levels-1. With martingale disabled (the default), every grid level uses the same InpInitialLot = 0.01; enabling martingale escalates each subsequent level by InpInitialLot * pow(InpMultiplier, i) with multiplier default 2.0. Entries are gated by the spread filter (≤ InpMaxSpread = 50 points), the GMT session filter (London 07:00–16:00 and New York 12:00–21:00), and the broader IsSafeToTrade guard (equity floor, daily/weekly loss caps, max trades per day, cooldown). Once a basket has positions, the EA holds it until the basket profit target is hit or a global safety gate trips.

Exit Signal

The primary exit is a basket-level profit target: when BasketProfit() >= InpTakeProfit * _Point * OpenCount() * 100, the EA calls CloseAll() to flatten every position and cancel every pending BuyLimit, then resets active = false so a fresh basket can form on the next flat tick. There is no per-order take-profit, no trailing stop, and no break-even — grid orders stay open until the basket hits the target or a global safety gate trips. OnTradeTransaction watches every DEAL_ADD and accumulates realized P&L into g_realizedToday and g_realizedWeek, which feed the loss-limit checks inside IsSafeToTrade_EX03019. A losing streak of InpMaxConsecLosses (default 0 = disabled) puts the EA into cooldown until g_cooldownUntil, halting new basket formation while open positions keep running.

Stop Loss

No individual grid order carries a stop-loss — the per-trade SL inputs are passed as 0 to both trade.Buy and trade.BuyLimit. Risk control is portfolio-level: the optional InpEquityFloor, InpDailyLossLimit, InpWeeklyLossLimit, and InpCapitalCap all sit at 0 by default, meaning the EA will not block new baskets until you set at least one of them — which is the single most important thing to do before going live with a 6-level gold grid.

Take Profit

The basket take-profit is InpTakeProfit * _Point * OpenCount() * 100 — a fixed 80 (default) per open position in account currency, so 1 position = $80, 3 positions = $240, capped at the open count. There is no per-order TP, no partial close, and no scaling out — when the basket hits, every position closes in one CloseAll() sweep and the pending BuyLimit ladder is canceled in the same pass.

Best For

Very-high-risk long-only gold grid for XAUUSD on M5 and H1 with a $100 nominal minimum, but the 6-level ladder and 2.0× martingale multiplier only make sense on accounts with at least $1,000 free margin per 0.01 lot of gold — go small (InpInitialLot = 0.01) and leave InpEnableMartingale at false for live trading. London (07:00–16:00 GMT) and the London–New York overlap (12:00–21:00 GMT) are the active sessions; weekends and the Asian session are flat, so don't expect fills outside those windows. Use a low-spread ECN broker (Exness, IC Markets) and set InpMaxSpread = 30 or lower on gold, since the basket is sensitive to spread cost on every grid level. Before going live, set InpEquityFloor, InpDailyLossLimit, InpWeeklyLossLimit, and InpMaxConsecLosses to non-zero values — leaving all of them at 0 means the EA will keep opening baskets until the account is empty.

Strategy Logic

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

Family: Grid Magic: 22203019 Version: 2.00

BRIEF: Grid + martingale system for XAUUSD. Places initial buy and a ladder of BuyLimit orders at fixed grid step intervals. Closes basket when combined profit target is reached. Martingale lot multiplier 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()
  • OpenCount()
  • CloseAll()
  • DetectGMTOffset_EX03019()
  • ServerToGMT_EX03019()
  • InActiveSession_EX03019()
  • UpdateDailyCounters_EX03019()
  • IsSafeToTrade_EX03019()
  • TryBuy_EX03019()
  • TryBuyLimit_EX03019()
  • TryClose_EX03019()
  • TryOrderDelete_EX03019()
  • ...and 1 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (1 total across 1 groups):

  • [=== Settings ===] InpEnableMartingale = false // Enable martingale lot progression
Pseudocode
// Pipsgrowth EX03019 Grid — Execution Flow (from source analysis)
// Family: Grid
// Grid + martingale system for XAUUSD. Places initial buy and a ladder of BuyLimit orders at fixed grid step intervals. Closes basket when combined profit target is reached. Martingale lot multiplier 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

EA Parameters

ParameterDefaultDescription
InpEnableMartingalefalseEnable martingale lot progression
Source Code (.mq5)Open Source
Pipsgrowth_com_EX03019.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX03019 GoldGridMartingale — grid + martingale for XAUUSD, full 12-layer stack."

#include <Trade\Trade.mqh>
input group "=== Settings ==="
input double InpInitialLot  = 0.01;
input double InpMultiplier  = 2.0;
input bool   InpEnableMartingale = false;  // Enable martingale lot progression
input int    InpGridStep    = 40;
input int    InpMaxLevels   = 6;
input int    InpTakeProfit  = 80;
input int    InpMagicNumber = 22203019;
input int    InpMaxSpread   = 50;
input string InpTradeComment = "Psgrowth.com Expert_03019";

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;
double basketBase = 0;
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;

void OnTick() {
   UpdateDailyCounters_EX03019();
   if(SymbolInfoInteger(_Symbol,SYMBOL_SPREAD) > InpMaxSpread) return;
   if(!IsSafeToTrade_EX03019()) return;
   double basket = BasketProfit();
   int    cnt    = OpenCount();
   if(cnt > 0 && basket >= InpTakeProfit * _Point * cnt * 100) { CloseAll(); active=false; return; }
   if(cnt == 0 && !active) {
      double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
      basketBase=ask; active=true;

Full source code available on download

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

Tags:ex03019gridpipsgrowthfreemt5xauusd

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