P
PipsGrowth
GridOpen Source – Free

Pipsgrowth EX03020 Grid

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

Pipsgrowth.com EX03020 GridScalperMA — dynamic grid with MA trend filter, full 12-layer stack.

Overview

Pipsgrowth EX03020 GridScalperMA is a trend-following grid that places a full ladder of limit orders whenever a single moving-average trigger fires. It is built around one rule: if the bid is above the EMA(50), fire a buy ladder; if it is below, fire a sell ladder. There is no per-trade stop-loss and no per-trade take-profit. The whole grid is closed as a basket the moment cumulative floating profit reaches a configurable target, or it is force-closed when account drawdown breaches a hard cap. That single design choice — basket management instead of individual trade management — defines the entire character of the EA.

The MA filter is created in OnInit() via iMA(_Symbol, PERIOD_CURRENT, InpMAPeriod, 0, InpMAMethod, PRICE_CLOSE). The default is a 50-period EMA on close, but InpMAPeriod (default 50), InpMAMethod (default MODE_EMA), and InpSignalType (default "MA") are all exposed. The source code only implements the MA branch — the "BOS" branch listed in the input is not wired in the file, so setting InpSignalType = "BOS" produces no signal. Treat it as a placeholder. Signals are evaluated on the closed bar: CopyBuffer(hMA, 0, 1, 1, ma) reads the most recent completed candle, then bid > ma[0] flips the grid long, bid < ma[0] flips it short. The signal only fires when no positions are open (openCount == 0 && !gridActive).

When the signal fires, PlaceGrid() builds a ladder of up to InpMaxOrders (default 8) entries. The first order is a market order: TryBuy_EX03020(lot, 0, 0, 0, InpTradeComment) for longs, TrySell_EX03020(...) for shorts. The remaining InpMaxOrders - 1 orders are pending limits spaced InpGridStep apart. For a buy grid, level i sits at gridBase - i * InpGridStep * _Point; for a sell grid, at gridBase + i * InpGridStep * _Point. gridBase is captured as the ask at the moment of the long trigger, or the bid at the moment of the short trigger. That means the grid always extends against the direction of the trigger, into deeper drawdown — the classic grid profile.

Lot sizing per level is controlled by InpLotMultiply (default false) and InpMultiplier (default 1.5). With multiplication off, every level fires at the same InpLotSize (default 0.01). With multiplication on, level i fires at InpLotSize * pow(InpMultiplier, i) — so a 0.01 start with a 1.5 multiplier produces 0.01, 0.02 (rounded to step), 0.02, 0.03, 0.05, 0.08, 0.11, 0.17. The volume is then clamped against SYMBOL_VOLUME_MIN/MAX/STEP and the lot is floored to the broker step. OrderCalcMargin() is called before each market send; if required margin exceeds free margin, the buy/sell is skipped.

There are no per-position SL or TP values in the order sends — every parameter for SL and TP in TryBuy_EX03020, TrySell_EX03020, TryBuyLimit_EX03020, and TrySellLimit_EX03020 is hard-coded to 0. Risk is controlled at the basket level. The basket take-profit is computed inline in OnTick() as InpTakeProfit * _Point * openCount * InpLotSize * 100. With defaults (60 points × openCount × 0.01 lot × 100), a fully-loaded 8-leg grid closes when basket profit hits roughly 4.80 USD-equivalent (the multiplier assumes 1 USD per 0.01 lot per point — accurate for XAUUSD micro lots on a USD account). As trades are closed and openCount drops, the live target also drops, so a partially-realized grid will exit at a lower floating total. The basket drawdown guard lives one block earlier: if (balance - equity) / balance * 100 > InpMaxDrawdown (default 25%), the EA calls CloseAll() and resets gridActive = false, ending the cycle.

Position lifecycle is split between OnTick() and OnTradeTransaction(). OnTick() runs every quote and is responsible for evaluating the signal, closing the basket, and firing PlaceGrid(). The five order helpers — TryBuy_EX03020, TrySell_EX03020, TryBuyLimit_EX03020, TrySellLimit_EX03020, and TryClose_EX03020 — all wrap the CTrade calls in a 3-attempt retry loop with 200 ms sleeps on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED. CloseAll() is a position-loop that calls TryClose_EX03020 for each open trade and a separate order-loop that calls TryOrderDelete_EX03020 to remove any still-pending limits. OnTradeTransaction() filters for TRADE_TRANSACTION_DEAL_ADD events matching the magic 22203020, accumulates realized P&L into g_realizedToday and g_realizedWeek, and triggers a 30-minute cooldown (default InpCooldownMinutes = 30) the moment the loss counter reaches 3. The cooldown applies as soon as g_consecLossesHD >= 3 regardless of InpMaxConsecLosses, but the blocking gate on the same counter only activates when InpMaxConsecLosses > 0 — so by default the EA cools down for 30 minutes after 3 consecutive losses but will keep trading after that.

The session and no-trade stack is the standard PipsGrowth hardening layer. DetectGMTOffset_EX03020() runs at init and tests offsets from -12 to +12 against the current server time, scoring each candidate by whether it lands on a weekday (score 10) and whether it lands in 07-21 hour-of-day (score 5); the highest-scoring offset becomes g_gmtOffset. InActiveSession_EX03020() then blocks Saturday and Sunday outright and only returns true if the GMT hour falls in either London (07-16 default) or New York (12-21 default). IsSafeToTrade_EX03020() also short-circuits on: equity floor (InpEquityFloor, default 0 = off), realized daily loss ≥ InpDailyLossLimit (default 0 = off), realized weekly loss ≥ InpWeeklyLossLimit (default 0 = off), balance ≥ InpCapitalCap (default 0 = off), g_dailyTrades >= InpMaxTradesPerDay (default 50), and the consec-loss gate described above. The daily/weekly counters roll over inside UpdateDailyCounters_EX03020() when the day-of-month or day-of-week changes. A 40-point spread filter runs on every tick before any other check.

The EA does not ship an OnTester for genetic optimization in the strict sense — it does ship double OnTester(), which returns (profit / maxDD) * (PF > 1 ? PF : 0) provided maxDD > 0 and trades >= 10. Otherwise it returns 0. Combined with the lack of per-trade SL/TP, the natural optimization surface is the grid step, the basket TP, the lot size, and the EMA period — not stop placement.

What to expect in a backtest: on a trending pair, the grid will load quickly in the trend direction and either close on basket TP within a few legs or run deep into a counter-trend reversal. The default 25% drawdown cap is what ends a bad cycle — it is a single number covering the whole account, not a per-grid cap, so running multiple EAs on the same account with the same magic can clash. There is no news filter, no slippage guard beyond the 30-point SetDeviationInPoints, and no time-based exit per individual trade. Two design parameters control the risk curve almost entirely: InpGridStep (tighter = more fills, deeper total exposure before recovery) and InpTakeProfit (lower = faster cycles, more commissions). The XAUUSD pairing is the suggested deployment; the M5 and H1 timeframes are both tested. EURUSD and other FX majors can run with this same source because the price-point math is generic, but the basket TP formula's per-point multiplier of 100 is calibrated to gold micro lots on USD accounts — on a $1-pip FX pair, raise InpTakeProfit accordingly to keep the dollar target equivalent.

The minimum balance recommendation is $100 for the defaults (0.01 lot, 8 levels, XAUUSD), but only because the spread cap of 40 points is generous; a low-spread ECN or RAW broker keeps the ladder from getting chopped. Because the EA has no individual stop-loss, the practical floor is set by InpMaxDrawdown and how much of the account you are willing to lose on a single cycle — set that number before the EA ever trades, not after the first loss.

Strategy Deep Dive

On every tick, OnTick() first checks the spread cap (40 points) and calls IsSafeToTrade_EX03020() — that function runs the active-session filter, the equity floor, the daily/weekly loss limit, the capital cap, the daily trade counter, and the consec-loss gate. If the safety stack passes, the EA reads the most recent closed MA value, compares bid to EMA(50), and either flips the grid long or short. PlaceGrid() then sends the first order as a market order and queues up to 7 pending limits stepping InpGridStep (30 points) into the counter-trend direction. Every subsequent tick monitors basket profit and triggers CloseAll() when the basket TP threshold is hit; the same CloseAll() is also called when account drawdown breaches InpMaxDrawdown. OnTradeTransaction() tracks realized P&L and applies a 30-minute cooldown after 3 consecutive losses.

Entry Signal

Entry is triggered on a single moving-average cross of the bid: when bid > EMA(50) and no positions are open, gridActive flips true with gridDir = 1 and PlaceGrid() fires a buy ladder. When bid < EMA(50), a sell ladder is built. The first order of the ladder is a market order, the remaining 7 are pending limits spaced InpGridStep (30 points) apart against the trigger direction. Lot size defaults to 0.01 per level, with optional InpLotMultiply (1.5×) escalation.

Exit Signal

Exit is basket-level, not per-trade. The grid is closed the moment GetBasketProfit() >= InpTakeProfit * _Point * openCount * InpLotSize * 100 — at defaults, this is roughly $4.80 for a fully-loaded 8-leg gold grid. A hard drawdown guard runs first: if (balance - equity) / balance * 100 > InpMaxDrawdown (25% default), CloseAll() is called and the cycle resets. A 30-minute cooldown is applied after 3 consecutive realized losses regardless of the InpMaxConsecLosses input.

Stop Loss

There is no per-trade stop-loss. The SL/TP parameters in every TryBuy/TrySell/TryBuyLimit/TrySellLimit call are hard-coded to 0. The single risk control is the account-level drawdown cap: when floating loss exceeds InpMaxDrawdown (default 25% of balance), CloseAll() force-closes every position and pending limit. The 30-minute cooldown after 3 consecutive losses is the only structured pause.

Take Profit

Basket take-profit only. The TP value sent to the broker is 0 for every individual order. The basket is closed by OnTick() when GetBasketProfit() >= InpTakeProfit * _Point * openCount * InpLotSize * 100 — at defaults (60 points × openCount × 0.01 lot × 100), the threshold scales with the number of legs currently open. As legs close via SL or reversal, the live target also drops proportionally.

Best For

Minimum recommended balance: $100 on XAUUSD at the 0.01-lot default. The M5 and H1 timeframes are both supported; on M5 the basket cycles fast and per-leg exposure is shallow, on H1 the cycles are longer but the basket captures more pip movement. Use an ECN or RAW-spread broker — the 40-point spread cap is generous, but a low-spread account keeps the ladder from being chopped on entries. Sessions: London 07-16 GMT and New York 12-21 GMT, weekends off. This is a high-risk grid; InpMaxDrawdown is the parameter to set deliberately before going live.

Strategy Logic

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

Family: Grid Magic: 22203020 Version: 2.00

BRIEF: Dynamic grid scalper with MA trend filter. Places a grid of limit orders in the trend direction based on MA signal. Optional lot multiplication per level (OFF by default). Basket close on combined profit target with drawdown protection. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • PlaceGrid()
  • GetBasketProfit()
  • CountOpenTrades()
  • CloseAll()
  • DetectGMTOffset_EX03020()
  • ServerToGMT_EX03020()
  • InActiveSession_EX03020()
  • UpdateDailyCounters_EX03020()
  • IsSafeToTrade_EX03020()
  • TryBuy_EX03020()
  • TrySell_EX03020()
  • TryBuyLimit_EX03020()
  • ...and 4 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (13 total across 3 groups):

  • [=== Grid Settings ===] InpGridStep = 30 // Grid Step (points)
  • [=== Grid Settings ===] InpMaxOrders = 8 // Max Grid Orders
  • [=== Grid Settings ===] InpLotSize = 0.01 // Initial Lot Size
  • [=== Grid Settings ===] InpTakeProfit = 60 // Basket Take Profit (points)
  • [=== Grid Settings ===] InpLotMultiply = false // Multiply lots per level
  • [=== Grid Settings ===] InpMultiplier = 1.5 // Lot multiplier (if enabled)
  • [=== Signal ===] InpSignalType = "MA" // Signal: MA or BOS
  • [=== Signal ===] InpMAPeriod = 50 // Moving Average Period
  • [=== Signal ===] InpMAMethod = MODE_EMA // MA Method
  • [=== Trade Settings ===] InpMagicNumber = 22203020 // Magic Number
  • [=== Trade Settings ===] InpMaxSpread = 40 // Max Spread (points)
  • [=== Trade Settings ===] InpMaxDrawdown = 25.0 // Max Drawdown %
  • [=== Trade Settings ===] InpTradeComment = "Psgrowth.com Expert_03020" // Trade comment
Pseudocode
// Pipsgrowth EX03020 Grid — Execution Flow (from source analysis)
// Family: Grid
// Dynamic grid scalper with MA trend filter. Places a grid of limit orders in the trend direction based on MA signal. Optional lot multiplication per level (OFF by default). Basket close on combined profit target with drawdown protection. 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
InpGridStep30Grid Step (points)
InpMaxOrders8Max Grid Orders
InpLotSize0.01Initial Lot Size
InpTakeProfit60Basket Take Profit (points)
InpLotMultiplyfalseMultiply lots per level
InpMultiplier1.5Lot multiplier (if enabled)
InpSignalType"MA"Signal: MA or BOS
InpMAPeriod50Moving Average Period
InpMAMethodMODE_EMAMA Method
InpMagicNumber22203020Magic Number
InpMaxSpread40Max Spread (points)
InpMaxDrawdown25.0Max Drawdown %
InpTradeComment"Psgrowth.com Expert_03020"Trade comment
Source Code (.mq5)Open Source
Pipsgrowth_com_EX03020.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX03020 GridScalperMA — dynamic grid with MA trend filter, full 12-layer stack."

#include <Trade\Trade.mqh>

input group "=== Grid Settings ==="
input int    InpGridStep      = 30;    // Grid Step (points)
input int    InpMaxOrders     = 8;     // Max Grid Orders
input double InpLotSize       = 0.01;  // Initial Lot Size
input int    InpTakeProfit    = 60;    // Basket Take Profit (points)
input bool   InpLotMultiply   = false; // Multiply lots per level
input double InpMultiplier    = 1.5;   // Lot multiplier (if enabled)

input group "=== Signal ==="
input string InpSignalType    = "MA";  // Signal: MA or BOS
input int    InpMAPeriod      = 50;    // Moving Average Period
input ENUM_MA_METHOD InpMAMethod = MODE_EMA; // MA Method

input group "=== Trade Settings ==="
input int    InpMagicNumber   = 22203020; // Magic Number
input int    InpMaxSpread     = 40;    // Max Spread (points)
input double InpMaxDrawdown   = 25.0;  // Max Drawdown %
input string InpTradeComment  = "Psgrowth.com Expert_03020"; // Trade comment

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;
int    hMA;
double gridBase   = 0;
bool   gridActive = false;
int    gridDir    = 0; // 1=buy, -1=sell

//--- 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;

Full source code available on download

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

Tags:ex03020gridpipsgrowthfreemt5xauusd

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