P
PipsGrowth
GridOpen Source – Free

Pipsgrowth EX03011 Grid

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX03011 GoldGridMartingale_EA — grid with martingale lot multiplier and basket management, full 12-layer stack.

Overview

Pipsgrowth EX03011 is a Gold grid martingale built around a single principle: once a fresh cycle begins, the EA queues 1-6 pending stops at fixed 50-pip spacing in the chosen direction, then lets price walk the ladder. There is no per-trade stop loss on individual orders. The risk envelope is the basket itself, and the EA manages that envelope through weighted-average price targets, basket-profit percentage, a drawdown kill switch, and a margin-level emergency. If any of those trip, the entire grid is force-closed and the cycle resets to CYCLE_INACTIVE.

The cycle starts from scratch on every tick where CountOpenPositions and CountPendingOrders both return zero. OnInit enforces the symbol whitelist at startup — XAUUSD, XAUUSDm, GOLD, XAU, XAUUSD.raw, XAUUSD., or XAUUSD.i — and refuses any other symbol with an Alert and INIT_FAILED. It also warns if AccountInfoInteger(ACCOUNT_LEVERAGE) is below 1:500, since a 6-level grid with martingale scaling punishes low leverage.

Three entry modes sit behind the ENUM_ENTRY_TYPE input. ENTRY_RANDOM sets direction from tick.time parity: it reads SymbolInfoTick and computes lastRandom = (int)(tick.time % 2), then routes to the buy side if UseBuyGrid is true (and falls back to sell only if buy is disabled). The effect is buy-biased randomisation, not 50/50. ENTRY_RSI is the cleaner mode: it creates g_rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, RSI_Period=14, PRICE_CLOSE) at init, and on each cycle-check tick it reads CopyBuffer(0, 0, 2). RSI > 50 fires a buy; RSI < 50 fires a sell, with UseBuyGrid and UseSellGrid as the only filters. ENTRY_BREAKOUT calls CopyHigh and CopyLow over the last BreakoutBars=48 five-minute bars (4 hours) and fires when SymbolInfoDouble(SYMBOL_LAST) clears the highest high (buy) or breaks the lowest low (sell).

When CheckEntrySignal returns true, PlaceGridOrders walks MaxGridLevels iterations. Level 1 sits at currentPrice ± gridStepPrice (50 pips) as a BUY_STOP or SELL_STOP, level 2 at ± 2 × gridStepPrice, and so on up to MaxGridLevels=6. Lot sizing is martingale: lot = InitialLot × LotMultiplier^(level-1). With LotMultiplier=1.0 (default) the lots are flat at InitialLot=0.01. Bumping it to 1.4 turns the ladder into 0.01, 0.014, 0.0196, 0.0274, 0.0384, 0.0538 — that escalation is what the 80% drawdown ceiling is designed to absorb. CalculateLotSize also enforces a MaxTotalLots=1.0 cap, so the final lot is reduced if the running total plus the new level would exceed that ceiling. Each order goes through a 3-retry OrderOpen loop with 100ms sleeps between failures, and OrderCalcMargin is called first; if required margin > 50% of free margin, the loop breaks early.

When a stop fills, the next tick detects openPositions > 0 and sets g_cycleState = CYCLE_BUY or CYCLE_SELL. DeleteOppositePendingOrders(ORDER_TYPE_BUY) cleans up any straggling sell-side pending orders, leaving the live basket to work the average. GetBasketProfit, CalculateAveragePrice, and UpdateTrailingProfit run on every tick while the cycle is active.

The basket take-profit is dual-mode. Method 1 watches CalculateAveragePrice (a volume-weighted average of all position open prices) and closes the basket when price has moved TakeProfit=20 pips in the cycle's favor — bid for buy cycles, ask for sell cycles. Method 2 closes when basket profit as a percentage of account balance reaches BasketProfitPercent=20%. The first to fire wins, and the cycle resets.

Trailing kicks in once basket profit reaches 50% of the basket target. g_trailingActive flips true, g_maxBasketProfit is set to the current basket profit, and on every subsequent tick the EA compares the current profit to the trailing threshold (max profit minus TrailingDistance=10 pips, converted to a percentage). When profit falls back through that level, takeProfitHit is set and CloseAllPositions + DeleteAllPendingOrders runs. The trailing is in pips-of-percentage territory rather than price-pips; the 0.1 multiplier on TrailingDistance is an approximate scaling from pips to percent, intentional in the code as a rough conversion rather than a precise trailing band.

The risk stack above the basket has three independent cutoffs. The first is the margin-level emergency in OnTick: if AccountInfoDouble(ACCOUNT_MARGIN_LEVEL) is non-zero and below 100%, the EA calls CloseAllPositions + DeleteAllPendingOrders and returns immediately. The second is CheckMaxDrawdown: drawdown = (balance - equity) / balance, and if it reaches MaxDrawdownPercent=80% the same shutdown runs. The third is the MinFreeMarginPercent=20% gate inside CheckMarginLevel — when there are no positions, it blocks new cycles if free margin dips below 20% of balance; when there are positions, it blocks new cycles if margin level falls below 150%.

Daily and intraday risk are split. CheckDailyLimits compares current balance to g_dailyStartBalance; if the day's profit reaches DailyProfitTarget=100% the EA blocks new cycles, and if it hits -DailyLossLimit=-50% the same. The OnTradeTransaction handler is the bookkeeping layer: it parses HistoryDealGetInteger(DEAL_ENTRY), increments g_dailyTrades on DEAL_ENTRY_IN, accumulates g_realizedToday and g_realizedWeek on DEAL_ENTRY_OUT, and increments g_consecLossesHD on each loss. After 3 consecutive losses, g_cooldownUntil = TimeCurrent() + InpCooldownMinutes * 60 (30 minutes by default) — this is a fixed threshold in the code, not the InpHrdMaxConsecLoss input (which gates the IsSafeToTrade check at a separate, larger value). The hardening block also exposes InpEquityFloor, InpHrdDailyLoss, InpHrdWeeklyLoss, and InpCapitalCap, all of which default to 0/disabled. When InpUseGMTSessions=true (default) the EA adds a London 7-16 ∪ New York 12-21 GMT gate via InActiveSession_EX03011; outside those hours — and on Saturday/Sunday — no new cycles fire regardless of the basic StartHour=7 / EndHour=16 input.

The news filter is intentionally minimal. IsNewsTime() blocks new cycles only on the first Friday of the month between 13:00 and 15:00 (NFP window), and only when UseNewsFilter=true (default false). There is no FOMC detection, no calendar feed — a trader who wants CPI or FOMC blocking has to layer it on top. The trade comment is hard-coded to 'Psgrowth.com Expert_03011' for identification, and the magic number 22203011 isolates this EA from any others running on the same account.

OnTester ranks candidates by (profit / maxDD) × max(0, profitFactor - 1), with hard gates of trades >= 10 and maxDD > 0. This favors strategies that produce meaningful trades with low relative drawdown and a profit factor above 1.0 — the right shape for a grid EA that runs a long cycle and closes cleanly. Trade-execution retries are 3 attempts at 100-200ms on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED return codes via TryOrderDelete_EX03011 and TryClose_EX03011; everything else (insufficient margin, invalid stops, market closed) breaks out of the retry loop immediately so the EA does not hammer the broker.

Operationally, the realistic minimum is not the listed $100. A 6-level gold grid with 50-pip spacing that needs room for the basket TP to develop is going to draw down before it cycles out; $1,000-$5,000 with leverage at 1:500 or higher is the working range, and any account that cannot absorb the full 6-level martingale escalation should reduce MaxGridLevels first, then reconsider LotMultiplier. The two are independent knobs but both feed the same drawdown ceiling.

Strategy Deep Dive

On every tick OnTick first runs the safety stack: UpdateDailyCounters_EX03011 rotates daily/weekly P&L totals, then a margin-level <100% emergency calls CloseAllPositions+DeleteAllPendingOrders and returns immediately, and the same shutdown runs when CheckMaxDrawdown sees drawdown >= MaxDrawdownPercent=80%. CountOpenPositions and CountPendingOrders then classify the state — if both are zero, g_cycleState becomes CYCLE_INACTIVE and the EA evaluates IsNewCycleAllowed and IsSafeToTrade_EX03011 (London 7-16 ∪ New York 12-21 GMT sessions, weekend guard, equity floor, daily/weekly loss caps, capital cap, trades-per-day cap, and the cooldown gate from g_cooldownUntil). The CheckEntrySignal switch picks a direction based on EntryType, and PlaceGridOrders queues 1-6 BUY_STOP or SELL_STOP pending orders at PipsToPrice(GridStep=50) intervals with lot = InitialLot × LotMultiplier^(level-1) capped at MaxTotalLots=1.0, each going through a 3-retry OrderOpen loop with 100ms sleeps on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED. When a stop fills, the next tick detects openPositions > 0, sets g_cycleState, and DeleteOppositePendingOrders cleans up stragglers on the other side; GetBasketProfit, CalculateAveragePrice, and UpdateTrailingProfit then monitor the cycle until one of the dual TP conditions or the trailing-stop logic fires. OnTradeTransaction updates g_realizedToday, g_realizedWeek, g_dailyTrades, and g_consecLossesHD, and at 3 consecutive losses sets g_cooldownUntil to TimeCurrent() + 30 minutes by default. OnTester ranks candidates by (profit/maxDD) × max(0, profitFactor-1) with hard gates of trades >= 10 and maxDD > 0.

Entry Signal

Entries are dispatched by ENUM_ENTRY_TYPE: ENTRY_RANDOM uses tick-time parity (lastRandom = (int)(tick.time % 2)) and routes to buy if UseBuyGrid is enabled, else sell — buy-biased, not 50/50. ENTRY_RSI reads g_rsiHandle (RSI_Period=14 on PRICE_CLOSE) and buys when RSI > 50, sells when RSI < 50, gated by UseBuyGrid/UseSellGrid. ENTRY_BREAKOUT compares SYMBOL_LAST to the BreakoutBars=48-bar (4-hour) high and low and fires when price clears either side. Whichever mode picks a direction, PlaceGridOrders then places 1-6 pending stops at PipsToPrice(GridStep=50) intervals above or below current price, with lot = InitialLot × LotMultiplier^(level-1) capped at MaxTotalLots=1.0.

Exit Signal

Basket-level dual-exit. Method 1 closes when the volume-weighted average price moves TakeProfit=20 pips in the cycle's favor (bid for buy cycles, ask for sell cycles). Method 2 closes when basket profit as a percent of account balance reaches BasketProfitPercent=20%. Trailing activates once basket profit reaches 50% of the basket target, locking in via g_maxBasketProfit and TrailingDistance=10 pips. The OnTradeTransaction handler tracks g_consecLossesHD; after 3 consecutive losses, g_cooldownUntil = TimeCurrent() + InpCooldownMinutes*60 (30 min by default) blocks new cycles even after the basket closes.

Stop Loss

No per-trade stop loss. Risk control is the basket: MaxDrawdownPercent=80% (drawdown = (balance-equity)/balance) triggers full shutdown via CloseAllPositions+DeleteAllPendingOrders, and an emergency margin-level cutoff fires if ACCOUNT_MARGIN_LEVEL < 100%. MinFreeMarginPercent=20% blocks new cycles when free margin drops too low, and the per-cycle MaxTotalLots=1.0 cap prevents single-cycle lot escalation from breaching the broker's exposure limits.

Take Profit

Dual-mode basket TP. Method 1 closes when weighted-average price moves TakeProfit=20 pips in the cycle's favor (bid for buy, ask for sell). Method 2 closes when basket profit as % of balance reaches BasketProfitPercent=20%. Trailing activates at 50% of basket target via UpdateTrailingProfit, then ratchets via g_maxBasketProfit minus TrailingDistance=10 pips. Whichever fires first wins, and the cycle resets to CYCLE_INACTIVE with all positions and pending orders cleared.

Best For

Gold/XAUUSD only — the OnInit symbol whitelist refuses any other symbol. M5 timeframe; the 50-pip grid spacing on 5-minute bars means cycles develop over 4-12 hours. Recommended balance $1,000-$5,000 with leverage >= 1:500, even though the listing shows $100 — a 6-level martingale grid needs capital to absorb the 80% drawdown ceiling. London 7-16 GMT and New York 12-21 GMT overlap (InpUseGMTSessions=true, no Sat/Sun); outside that window no new cycles fire regardless of the basic 7-16 input. ECN/RAW broker with deep liquidity required, ORDER_FILLING_FOK, 50-point deviation, and MaxSpread=30 pips tolerance. Run LotMultiplier=1.0 (flat) on a small account first; only scale 1.3-1.5 once the basket TP cadence is visible in your backtest, and reduce MaxGridLevels from 6 to 4 before raising the multiplier on a sub-$2,000 account.

Strategy Logic

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

Family: Grid Magic: 22203011 Version: 2.00

BRIEF: Gold grid martingale EA that places grid orders at fixed step intervals with lot multiplier, supporting random, RSI, or breakout entry methods. Includes basket TP, trailing, and drawdown protection with daily profit/loss limits. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • IsNewCycleAllowed()
  • CheckEntrySignal()
  • PlaceGridOrders()
  • CloseAllPositions()
  • DeleteAllPendingOrders()
  • DeleteOppositePendingOrders()
  • CountOpenPositions()
  • CountPendingOrders()
  • CalculateAveragePrice()
  • GetBasketProfit()
  • GetTotalLotSize()
  • CheckMarginLevel()
  • ...and 18 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (30 total across 9 groups):

  • [=== GRID SETTINGS ===] GridStep = 50 // Grid step distance (pips)
  • [=== GRID SETTINGS ===] MaxGridLevels = 6 // Maximum grid levels
  • [=== GRID SETTINGS ===] UseBuyGrid = true // Enable buy side grid
  • [=== GRID SETTINGS ===] UseSellGrid = true // Enable sell side grid
  • [=== MARTINGALE SETTINGS ===] InitialLot = 0.01 // Initial lot size
  • [=== MARTINGALE SETTINGS ===] LotMultiplier = 1.0 // Lot size multiplier (1.0 = disabled)
  • [=== MARTINGALE SETTINGS ===] UseDynamicLots = false // Calculate lots based on balance
  • [=== PROFIT & LOSS SETTINGS ===] TakeProfit = 20 // Take profit (pips from average)
  • [=== PROFIT & LOSS SETTINGS ===] BasketProfitPercent = 20.0 // OR close at profit % of account
  • [=== PROFIT & LOSS SETTINGS ===] MaxDrawdownPercent = 80.0 // Maximum drawdown before force close
  • [=== PROFIT & LOSS SETTINGS ===] TrailingDistance = 10 // Trail profit by pips (0 = disabled)
  • [=== ENTRY SETTINGS ===] EntryType = ENTRY_RANDOM // Entry method
  • [=== ENTRY SETTINGS ===] RSI_Period = 14 // RSI period (if using RSI entry)
  • [=== ENTRY SETTINGS ===] BreakoutBars = 48 // Lookback bars for breakout (4H = 48x5min)
  • [=== TIME FILTERS ===] StartHour = 7 // Trading start hour (GMT)
  • [=== TIME FILTERS ===] EndHour = 16 // Trading end hour (GMT)
  • [=== TIME FILTERS ===] TradeMonday = true // Trade on Monday
  • [=== TIME FILTERS ===] TradeTuesday = true // Trade on Tuesday
  • [=== TIME FILTERS ===] TradeWednesday = true // Trade on Wednesday
  • [=== TIME FILTERS ===] TradeThursday = true // Trade on Thursday
  • [=== TIME FILTERS ===] TradeFriday = true // Trade on Friday
  • [=== RISK MANAGEMENT ===] MaxSpread = 30 // Maximum spread (pips)
  • [=== RISK MANAGEMENT ===] MaxTotalLots = 1.0 // Maximum total lot size
  • [=== RISK MANAGEMENT ===] MinFreeMarginPercent = 20.0 // Minimum free margin percentage
  • [=== OPTIONAL FEATURES ===] UseNewsFilter = false // Enable news filter
  • [=== OPTIONAL FEATURES ===] DailyProfitTarget = 100.0 // Daily profit target % (0 = disabled)
  • [=== OPTIONAL FEATURES ===] DailyLossLimit = 50.0 // Daily loss limit % (0 = disabled)
  • [=== GENERAL SETTINGS ===] MagicNumber = 22203011 // Magic number for EA trades
  • [=== GENERAL SETTINGS ===] InpTradeComment = "Psgrowth.com Expert_03011" // Trade comment
  • [=== Hardening Trade Safety ===] InpHrdMaxConsecLoss = 0 // +------------------------------------------------------------------+
Pseudocode
// Pipsgrowth EX03011 Grid — Execution Flow (from source analysis)
// Family: Grid
// Gold grid martingale EA that places grid orders at fixed step intervals with lot multiplier, supporting random, RSI, or breakout entry methods. Includes basket TP, trailing, and drawdown protection with daily profit/loss limits. 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
GridStep50Grid step distance (pips)
MaxGridLevels6Maximum grid levels
UseBuyGridtrueEnable buy side grid
UseSellGridtrueEnable sell side grid
InitialLot0.01Initial lot size
LotMultiplier1.0Lot size multiplier (1.0 = disabled)
UseDynamicLotsfalseCalculate lots based on balance
TakeProfit20Take profit (pips from average)
BasketProfitPercent20.0OR close at profit % of account
MaxDrawdownPercent80.0Maximum drawdown before force close
TrailingDistance10Trail profit by pips (0 = disabled)
EntryTypeENTRY_RANDOMEntry method
RSI_Period14RSI period (if using RSI entry)
BreakoutBars48Lookback bars for breakout (4H = 48x5min)
StartHour7Trading start hour (GMT)
EndHour16Trading end hour (GMT)
TradeMondaytrueTrade on Monday
TradeTuesdaytrueTrade on Tuesday
TradeWednesdaytrueTrade on Wednesday
TradeThursdaytrueTrade on Thursday
TradeFridaytrueTrade on Friday
MaxSpread30Maximum spread (pips)
MaxTotalLots1.0Maximum total lot size
MinFreeMarginPercent20.0Minimum free margin percentage
UseNewsFilterfalseEnable news filter
DailyProfitTarget100.0Daily profit target % (0 = disabled)
DailyLossLimit50.0Daily loss limit % (0 = disabled)
MagicNumber22203011Magic number for EA trades
InpTradeComment"Psgrowth.com Expert_03011"Trade comment
InpHrdMaxConsecLoss0+------------------------------------------------------------------+
Source Code (.mq5)Open Source
Pipsgrowth_com_EX03011.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX03011 GoldGridMartingale_EA — grid with martingale lot multiplier and basket management, full 12-layer stack."

#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>
#include <Trade/OrderInfo.mqh>
#include <Trade\Trade.mqh>

//+------------------------------------------------------------------+
//| ENUMERATIONS                                                      |
//+------------------------------------------------------------------+
enum ENUM_ENTRY_TYPE
{
   ENTRY_RANDOM = 0,      // Random Entry (Simple)
   ENTRY_RSI = 1,         // RSI-Based Entry
   ENTRY_BREAKOUT = 2     // Breakout Entry
};

enum ENUM_CYCLE_STATE
{
   CYCLE_INACTIVE = 0,    // No active cycle
   CYCLE_BUY = 1,         // Buy cycle active
   CYCLE_SELL = 2         // Sell cycle active
};

//+------------------------------------------------------------------+
//| INPUT PARAMETERS                                                  |
//+------------------------------------------------------------------+

//--- Grid Settings
input group "=== GRID SETTINGS ==="
input int GridStep = 50;                      // Grid step distance (pips)
input int MaxGridLevels = 6;                  // Maximum grid levels
input bool UseBuyGrid = true;                 // Enable buy side grid
input bool UseSellGrid = true;                // Enable sell side grid

//--- Martingale Settings
input group "=== MARTINGALE SETTINGS ==="
input double InitialLot = 0.01;               // Initial lot size
input double LotMultiplier = 1.0;             // Lot size multiplier (1.0 = disabled)
input bool UseDynamicLots = false;            // Calculate lots based on balance

//--- Profit & Loss Settings
input group "=== PROFIT & LOSS SETTINGS ==="
input int TakeProfit = 20;                    // Take profit (pips from average)
input double BasketProfitPercent = 20.0;      // OR close at profit % of account
input double MaxDrawdownPercent = 80.0;       // Maximum drawdown before force close
input int TrailingDistance = 10;              // Trail profit by pips (0 = disabled)

//--- Entry Settings
input group "=== ENTRY SETTINGS ==="
input ENUM_ENTRY_TYPE EntryType = ENTRY_RANDOM;  // Entry method
input int RSI_Period = 14;                    // RSI period (if using RSI entry)
input int BreakoutBars = 48;                  // Lookback bars for breakout (4H = 48x5min)

//--- Time Filters
input group "=== TIME FILTERS ==="

Full source code available on download

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

Tags:ex03011gridpipsgrowthfreemt5xauusd

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