P
PipsGrowth
BreakoutOpen Source – Free

Pipsgrowth EX02029 Breakout

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX02029 Gaps  gap breakout trading with trailing stop, full 12-layer stack.

Overview

Pipsgrowth EX02029 is a gap-fade Expert Advisor — a mean-reversion specialist that buys into overnight gaps down and sells into overnight gaps up on the assumption that the unfilled portion will be closed during the next session. Where most breakout EAs in the EX02 family ride a clean range break, EX02029 deliberately fades the move that gap traders try to monetise. The execution path is intentionally minimal: a single gap threshold, fixed stops, fixed targets, and a stepped trailing stop — there are no oscillators, no ATR, no Donchian, and no Heikin-Ashi overlays. The whole signal resolves from two candles and one parameter.

The core detection lives in OnTick(). After the standard new-bar guard (a static datetime PrevBars that compares iTime to the previous tick's value) and the IsSafeToTrade_EX02029 gate, the EA pulls the most recent two rates with CopyRates on the configured g_tf (default M5) and runs a single inequality check on each side:

if(rates[0].open < rates[1].low - ExtGap) → OpenBuy at ask, SL = ask - ExtStopLoss, TP = ask + ExtTakeProfit if(rates[0].open > rates[1].high + ExtGap) → OpenSell at bid, SL = bid + ExtStopLoss, TP = bid - ExtTakeProfit

The gap magnitude is set by InpGap (default 1 pip, scaled by the m_adjusted_point helper that compensates for 3-digit and 5-digit broker pricing), and only the most recent closed bar is referenced — shift-1 by construction. Both entry paths run sequentially inside the same tick, so the EA can in principle open a buy and a sell within one bar if the gap condition somehow fires both ways, though in practice the open/close structure of the previous bar usually prevents that. There is a deliberate sanity check before the buy fires: if the computed SL is at or above the current bid, the position would be in violation of the broker's stop-level minimum, and the EA bails by setting PrevBars=0 to force a re-evaluation next tick rather than send a malformed order.

Position management is built around three pips-based inputs. InpStopLoss defaults to 50 pips, InpTakeProfit defaults to 50 pips (so the EA ships at a 1:1 risk-reward out of the box), and InpTrailingStop + InpTrailingStep default to 5 pips each. The Trailing() function runs on every tick — not just new bars — and for each open position belonging to this EA's magic (22202029) and symbol, it checks whether price has moved more than ExtTrailingStop+ExtTrailingStep beyond the entry in the favourable direction. If yes, and the existing stop is still behind that new threshold, it modifies the SL to ExtTrailingStop behind current price via TryModify_EX02029, which retries the modify up to three times at 200ms intervals on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED. Trailing only ever tightens in the profitable direction — there is no BE+lock step, no partial close, and no break-even pad. Once price has covered the trailing window the stop ratchets forward; if the SL never moves before TP, the trade closes at the fixed target.

The OnInit routine also enforces a strict invariant: InpTrailingStop!=0 with InpTrailingStep==0 returns INIT_PARAMETERS_INCORRECT with a localised Alert — trailing without a step would cause the modify call to fire on every tick and overload the trade server. That single guard catches the most common configuration mistake before any live tick. The remaining hardening runs in a separate module:

IsSafeToTrade_EX02029 is the all-in-one gate that wraps seven checks. IsMarketOpen_EX02029 blocks Saturday, Sunday, the first two hours of Monday (post-weekend rollover noise), and the last two hours of Friday. InActiveSession_EX02029 applies the optional London 7-16 / New York 12-21 GMT windows (gated by InpUseGMTSessions, which defaults to false so the EA is permissive by default). IsNewsTime_EX02029 queries MqlCalendarValue history for any HIGH-importance event in the ±30 minute window and blocks entries if found. The capital-protection check applies when InpCapAmount > 0 and refuses to trade if effective capital drops below InpCapFloor (1000 default). The equity-floor check refuses to trade if current equity is below g_initialBalance × InpMinEquityPct/100 (70% default). The daily-trade counter (g_tradesToday >= InpMaxTradesPerDay, default 10) and the cooldown timer (g_cooldownUntil > TimeCurrent()) round out the gate.

PnL bookkeeping happens in OnTradeTransaction. Every DEAL_ADD with the magic 22202029 on the current symbol updates g_realizedToday, g_realizedWeek, and g_tradesToday. Losing deals increment g_consecLosses; when that hits InpMaxConsecLosses (5 default), g_cooldownUntil is set to TimeCurrent() + InpCooldownHours*3600 (4 hours). UpdateDailyCounters_EX02029 rotates the daily and weekly counters when the day-of-month or month changes. The OnTester fitness function returns profit × profitFactor / maxDD, gated on a minimum of 10 trades — so the strategy optimiser rewards both absolute return and smoothness, with a hard floor on sample size.

The intended symbol per the runtime context is XAUUSD on M5 with a $100 minimum account, but the source is symbol-agnostic — the brief explicitly notes "FX Majors, Gold/Metals (portable)". Because the entire strategy resolves from open-to-open gap math with no volatility scaling, the only meaningful input for a different symbol is recalibrating InpGap (a 1-pip gap on EURUSD is small, on XAUUSD it is essentially noise, on NAS100 it is a major move). Traders who want fewer signals should raise InpGap; traders who want more should lower it. The EA is also timeframe-agnostic via the InpTimeFrame input, which routes through MapTimeframe_EX02029 — set it to 5 (PERIOD_H1) on less-liquid pairs where 1-pip gaps appear several times an hour on M5 and would otherwise over-trade.

Two practical caveats from the source. First, there is no spread filter and no slippage guard beyond the fixed 10-point m_slippage used in trade requests — a high-spread broker will eat most of a 1-pip edge before the order even lands, so this is strictly an ECN/RAW-spread deployment. Second, the 1:1 default RR means the strategy needs a fill rate above 50% to be net profitable, which a fade strategy on a noisy instrument may not achieve. Backtest on a tick-data-quality account before going live, and consider raising InpTakeProfit to 75 or 100 pips once the gap-fill behaviour is confirmed on your broker's data — the inputs are deliberately minimal so the trader can tune the RR without having to compensate for other built-in assumptions.

Strategy Deep Dive

On every tick where a new bar has formed on the configured g_tf, EX02029 fetches the last two rates via CopyRates, runs a single inequality on the open of bar[0] versus the high/low of bar[1] plus the InpGap threshold (default 1 pip), and fires OpenBuy or OpenSell with fixed SL and TP. The 50/50 pip default delivers a 1:1 RR; a stepped trailing stop with 5-pip stop and 5-pip step ratchets the SL forward only when price has cleared the trailing window in the profitable direction, retried up to three times per modify on requote/timeout/price-off/price-changed errors. A pre-trade guard rejects the entry if the computed SL would violate the broker stop-level minimum, and the IsSafeToTrade_EX02029 gate blocks entries outside the market-open window (Sat/Sun + Mon 0-2 + Fri 22-24), during high-impact news within ±30 minutes (when InpFilterNews is on), and while g_cooldownUntil from a 5-loss streak is still active.

Entry Signal

Long entry fires when the current bar opens below the previous bar's low minus the InpGap threshold (default 1 pip), betting on gap-fill to the upside. Short entry fires when the current bar opens above the previous bar's high plus the gap threshold, betting on gap-fill to the downside. The check runs on bar open (shift 1 reference) inside OnTick, after the IsSafeToTrade_EX02029 gate resolves clean.

Exit Signal

Fixed take-profit at InpTakeProfit pips (default 50) and a stepped trailing stop engage once price has moved InpTrailingStop+InpTrailingStep (5+5 pips) in the favourable direction. The Trailing() function modifies the SL forward only — it never widens the stop — and runs on every tick, not just on bar open. There is no break-even pad and no partial close; positions either close at the original TP, get stopped at the new ratcheted SL, or get stopped at the original SL if the gap fills fast enough to hit the target.

Stop Loss

Fixed stop-loss at InpStopLoss pips (default 50) computed from the entry Ask on a buy or entry Bid on a sell, scaled by the broker's point via the m_adjusted_point helper. A pre-order sanity check in OnTick rejects the buy if the computed SL would be at or above the current bid (broker stop-level violation), forcing a re-evaluation next tick instead of sending a malformed request.

Take Profit

Fixed take-profit at InpTakeProfit pips (default 50) for a 1:1 risk-reward out of the box. The default symmetry (50 pip SL / 50 pip TP) reflects the gap-fade thesis — the unfilled portion of an opening gap is expected to be roughly equal in magnitude to the gap itself, so the strategy ships without an RR bias. Raising InpTakeProfit to 75 or 100 pips on a broker with confirmed gap-fill behaviour is the standard first knob to turn.

Best For

Designed for XAUUSD M5 on a low-spread ECN/RAW broker, with a $100 minimum account. Works on FX majors and other metals with symbol-portable inputs, but InpGap and pip-based SL/TP need recalibration per symbol — 1 pip on EURUSD is small, on XAUUSD it is near-noise, on NAS100 it is a major move. Recommended for traders who understand gap-fade thesis and want a deliberately minimal, fully auditable signal: two candles, one threshold, fixed risk.

Strategy Logic

Pipsgrowth EX02029 Breakout — Strategy Logic Analysis (from .mq5 source)

Family: Breakout Magic: 22202029 Version: 2.00

BRIEF: Gap-trading EA that buys when a bar opens below the previous bar's low minus a gap threshold, and sells when a bar opens above the previous high plus a gap, with trailing stop

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • OnTradeTransaction()
  • RefreshRates()
  • CheckVolumeValue()
  • OpenBuy()
  • OpenSell()
  • Trailing()
  • PrintResultTrade()
  • PrintResultModify()
  • DetectGMTOffset_EX02029()
  • ServerToGMT_EX02029()
  • IsMarketOpen_EX02029()
  • InActiveSession_EX02029()
  • ...and 4 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (12 total across 5 groups):

  • [=== Identity ===] m_magic = 22202029 // Magic Number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_02029" // Trade Comment
  • [=== Strategy Parameters ===] InpGap = 1 // Gap (in pips)
  • [=== Strategy Parameters ===] InpTimeFrame = 0 // Timeframe (0=current,1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1,8=W1,9=MN1)
  • [=== Trade Management ===] InpLots = 0.1 // Lots
  • [=== Trade Management ===] InpStopLoss = 50 // Stop Loss (in pips)
  • [=== Trade Management ===] InpTakeProfit = 50 // Take Profit (in pips)
  • [=== Trade Management ===] InpTrailingStop = 5 // Trailing Stop (in pips)
  • [=== Trade Management ===] InpTrailingStep = 5 // Trailing Step (in pips)
  • [=== GMT Session Filter (Hardening) ===] InpNewYorkEndGMT = 21 // --- Hardening: Capital Protection ---
  • [=== Capital Protection (Hardening) ===] InpCapAmount = 0.0 // Capital cap amount (0=disabled)
  • [=== Capital Protection (Hardening) ===] InpDailyLossLimitPct = 5.0 // --- Hardening: Trade Safety ---
Pseudocode
// Pipsgrowth EX02029 Breakout — Execution Flow (from source analysis)
// Family: Breakout
// Gap-trading EA that buys when a bar opens below the previous bar's low minus a gap threshold, and sells when a bar opens above the previous high plus a gap, with trailing stop

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 an H1 or H4 chart
  7. 7Set the range detection period, breakout buffer, and lot size in the EA dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
m_magic22202029Magic Number
InpTradeComment"Psgrowth.com Expert_02029"Trade Comment
InpGap1Gap (in pips)
InpTimeFrame0Timeframe (0=current,1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1,8=W1,9=MN1)
InpLots0.1Lots
InpStopLoss50Stop Loss (in pips)
InpTakeProfit50Take Profit (in pips)
InpTrailingStop5Trailing Stop (in pips)
InpTrailingStep5Trailing Step (in pips)
InpNewYorkEndGMT21--- Hardening: Capital Protection ---
InpCapAmount0.0Capital cap amount (0=disabled)
InpDailyLossLimitPct5.0--- Hardening: Trade Safety ---
Source Code (.mq5)Open Source
Pipsgrowth_com_EX02029.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX02029 Gaps   gap breakout trading with trailing stop, full 12-layer stack."
//---
//==================================================================//
//                      TIMEFRAME MAPPING                            //
//==================================================================//
ENUM_TIMEFRAMES MapTimeframe_EX02029(int tf)
{
   switch(tf)
   {
      case 0:  return (ENUM_TIMEFRAMES)Period();
      case 1:  return PERIOD_M1;
      case 2:  return PERIOD_M5;
      case 3:  return PERIOD_M15;
      case 4:  return PERIOD_M30;
      case 5:  return PERIOD_H1;
      case 6:  return PERIOD_H4;
      case 7:  return PERIOD_D1;
      case 8:  return PERIOD_W1;
      case 9:  return PERIOD_MN1;
      default: return PERIOD_CURRENT;
   }
}

ENUM_TIMEFRAMES g_tf = PERIOD_CURRENT;

#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
CSymbolInfo    m_symbol;                     // symbol info object
//--- input parameters
input group "=== Identity ==="
input ulong    m_magic            = 22202029; // Magic Number
input string   InpTradeComment    = "Psgrowth.com Expert_02029"; // Trade Comment

input group "=== Strategy Parameters ==="
input ushort   InpGap             = 1;        // Gap (in pips)
input int       InpTimeFrame        = 0;        // Timeframe (0=current,1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1,8=W1,9=MN1)

input group "=== Trade Management ==="
input double   InpLots            = 0.1;      // Lots
input ushort   InpStopLoss        = 50;       // Stop Loss (in pips)
input ushort   InpTakeProfit      = 50;       // Take Profit (in pips)
input ushort   InpTrailingStop    = 5;        // Trailing Stop (in pips)
input ushort   InpTrailingStep    = 5;        // Trailing Step (in pips)
//---
ulong          m_slippage=10;                // slippage

// --- Hardening: GMT Session Filter ---
input group "=== GMT Session Filter (Hardening) ===";
input bool    InpUseGMTSessions       = false;
input int     InpLondonStartGMT       = 7;
input int     InpLondonEndGMT         = 16;
input int     InpNewYorkStartGMT      = 12;
input int     InpNewYorkEndGMT        = 21;

Full source code available on download

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

Tags:ex02029breakoutpipsgrowthfreemt5xauusd

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_EX02029.mq5
File Size26.2 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyBreakout
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100