P
PipsGrowth
BreakoutOpen Source – Free

Pipsgrowth EX02022 Breakout

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX02022 DonchianBreakout_XAUUSD_5M — Donchian breakout with trailing and pyramiding, full 12-layer stack.

Overview

Pipsgrowth EX02022 Breakout is a pure Donchian-channel breakout EA built for XAUUSD on the 5-minute chart. It runs a deliberately simple signal pipeline — a closed-bar close above the prior N-bar highest high triggers a long, a close below the prior N-bar lowest low triggers a short — and then layers position management on top of that signal. There is no ADX filter, no higher-timeframe trend gate, no body/range strength test, and no regime classifier in this code. The edge is expected to come from how the EA sizes, trails, pyramids, and protects capital, not from a heavily filtered entry.

The channel is constructed inline in CheckSignal() by walking the previous 1..InpPeriod bars and tracking the running maximum high and minimum low. With the default InpPeriod = 20, the EA watches the highest high and lowest low of the most recent 20 closed five-minute bars, which on gold is roughly 100 minutes of price action. A long fires when Close[1] closes above that high, a short fires when Close[1] closes below that low. The decision runs once per new bar (lastBar guard in OnTick()), so signal evaluation is stable and re-attempts won't spam orders within the same candle.

Risk defaults are noticeably more aggressive than the rest of the EX02 family. InpRiskPercent = 1.0 percent of account balance per trade (other EAs in this family default to 0.5%), and InpStopLoss = 400 points while InpTakeProfit = 1200 points — a hardcoded 1:3 reward-to-risk ratio baked into the order ticket, not a multiple of ATR. The lot sizing path goes through CalculateLotSize(), which divides balance * riskPercent / 100 by the per-lot risk implied by the 400-point stop, snaps the result down to the symbol's LotsStep(), and clamps to LotsMin() / LotsMax(). If the user sets InpRiskPercent = 0, the EA falls back to InpFixedLot = 0.01.

The single order retry logic is robust: OpenBuy() and OpenSell() both pre-check free margin via OrderCalcMargin(), then attempt trade.Buy() / trade.Sell() up to three times at 200 ms sleep between attempts, refreshing Ask/Bid between attempts, and breaking out on any non-recoverable retcode. Filling is forced to FOK via trade.SetTypeFilling(ORDER_FILLING_FOK). After the order is in, the same retcode-aware retry pattern runs in TryModify_EX02022() for the trailing-stop updates, also with a 200 ms back-off.

Pyramiding is the headline feature of this EA. With InpEnablePyramid = true (the default) and InpMaxPositions = 3, the EA will stack up to three long or three short positions in the same direction, but only if the existing position is in profit by at least InpMinProfitPoints = 250 points. That gating is enforced by IsGridSafe(), which loops over open positions for this symbol and magic and returns false if any one of them is below the threshold. The effect is that the EA only adds to a trade that is already working in the trader's favour — it does not average down into losers, and it does not pyramid faster than every 250 points (≈ 2.50 USD on a 0.01-lot XAUUSD) of favourable move on the existing position. This is the central risk-control design choice in the EA: aggressive 1:3 RR entries with a single position, optionally scaled up to a three-position stack on confirmed breakouts.

The trailing stop logic in ManageProfitLock() is a classic fixed-distance ratchet. Once price moves InpTrailStart = 300 points in profit on a position, the EA sets the new stop to Bid - InpTrailDistance = Bid - 150 points for longs (and the mirror for shorts). The ratchet only ever moves the stop closer to price — it never widens it. The check runs every tick, so the stop is updated on every price change once the activation threshold has been crossed, with no minimum step gap. With the default 300/150 settings, the trail activates at 3.00 USD of move and locks at 1.50 USD behind price, which leaves a comfortable buffer for the 5-minute volatility of gold.

The no-trade gate is implemented as a single IsSafeToTrade_EX02022() function that returns false on any of the following: market closed (Saturday, Sunday, or the Friday 22:00 cutoff), session filter not active (only checked when InpUseGMTSessions = true, which defaults to off), a high-impact news event inside ±30 minutes (InpFilterNews = true default, queried via CalendarValueHistory() for the symbol's country), equity below 70% of the initial balance, fewer than 10 trades already taken today, an active cooldown after 5 consecutive losses, or realized daily loss equal to or worse than InpDailyLossPct = 5% of the initial balance. The cooldown itself is implemented in OnTradeTransaction(), which is the only place in the EA that updates the cumulative g_realizedToday/g_realizedWeek P&L counters and the g_consecLosses loss streak; hitting 5 in a row sets g_cooldownUntil = TimeCurrent() + 4 hours.

The session filter, when enabled, is set to London 7-16 GMT and New York 12-21 GMT (the default InpNewYorkEndGMT = 21 is the only input visible at the end of the GMT group because the others use literal input declarations inside the body rather than at the top of file — a minor quirk of this source). When InpUseGMTSessions = false, which is the shipped default, the session gate is bypassed entirely and the EA will fire on a clean signal any time the market is open. The GMT offset used by the session and market-open checks is auto-detected by DetectGMTOffset_EX02022() via a brute-force search over offsets -12..+12, picking the one that best fits weekday 1-5 and 7-21 hour, defaulting to +3 if no better candidate scores.

The capital-cap feature is shipped disabled: InpCapAmount = 0.0 means the EA treats the full account balance as effective capital for sizing. Setting it to a positive value (the input expects a USD figure) caps the equity that the EA "sees" at min(balance, InpCapAmount), and InpCapFloor = 1000 enforces a minimum effective capital before trading is allowed. This is intended for users who want to run a small portion of their account through the EA without rewriting the risk percent.

The OnTester() custom fitness function is profit * profitFactor / maxDD, with two guard rails: profitFactor is clamped to the 0.001-1000 range, and the function returns 0 if fewer than 10 trades are present in the test (much looser than the >=30 gate other EAs in this family use). The optimizer will therefore prefer parameter sets with positive net P&L, a profit factor above 1, and low max drawdown, but it will not reject a low-trade-count backtest outright — useful for fast first-pass optimization runs.

In practical terms, this EA is for a trader who is comfortable with a relatively unfiltered breakout entry on gold and wants the position management to do the heavy lifting. The risk profile is medium: a single 1% risk trade with a 400-point stop, optionally scaled to three positions when the breakout extends, and a 150-point trailing stop that locks 300 points in. The recommended broker profile is one that can fill 0.01-lot orders on XAUUSD with reasonable slippage under the 250-point (2.50 USD) max-spread ceiling, an ECN/RAW account for best fill quality, and a server time that aligns with GMT +2/+3 so the auto-detected offset makes the session filter behave intuitively. The EA runs every tick for the position-management loop, so the host should have a low-latency connection to the broker to avoid stale-stop scenarios during fast gold spikes.

Strategy Deep Dive

The EA's OnTick() path runs three independent routines in order: a spread pre-filter (drops the tick immediately if mysymbol.Spread() > InpMaxSpread = 250 points), the trailing-stop manager ManageProfitLock() (which ratchets stops to 150 points behind price once a position is 300 points in profit), and the safety gate IsSafeToTrade_EX02022() (which blocks trading on closed markets, high-impact news inside ±30 min, equity below 70% of initial balance, daily loss equal to or worse than 5%, the 5-consecutive-loss 4-hour cooldown, and the 10-trades-per-day cap). The signal itself runs only on bar close via the lastBar guard, computing the Donchian channel inline and firing OpenBuy() / OpenSell() with the position-direction aware pyramid check IsGridSafe() ensuring any add-on only stacks on a position that is already in profit by at least 250 points, up to the 3-position cap.

Entry Signal

A long entry fires on a closed M5 bar when Close[1] closes above the highest high of the previous 20 bars (InpPeriod = 20); a short entry fires on a closed bar when Close[1] closes below the lowest low of the same lookback. The signal is checked once per new bar (tick-level guard in OnTick()), with no ADX, no body/range strength filter, and no higher-timeframe trend gate — the entry is a pure price-channel breakout.

Exit Signal

Positions exit by hitting the hardcoded stop-loss (400 points) or take-profit (1200 points = 1:3 RR), by the fixed trailing stop once price moves 300 points in favour (locking at 150 points behind), or by an external close (manual close, margin call). There is no opposite-signal exit and no time-based exit in this EA — exits are SL/TP/trailing only.

Stop Loss

Fixed 400-point stop-loss (InpStopLoss = 400) attached to the order ticket, used both as the trade SL and as the basis for lot sizing in CalculateLotSize(). The stop is placed immediately on entry and never widened; trailing only ratchets it closer to price after the 300-point activation threshold.

Take Profit

Fixed 1200-point take-profit (InpTakeProfit = 1200) attached to the order ticket, producing a 1:3 reward-to-risk ratio against the 400-point stop. There is no partial-close logic and no scaling-out — the entire position closes at the 1200-point target or at the trailing stop.

Best For

Best for a $100+ minimum-deposit XAUUSD M5 setup on a low-spread ECN/RAW broker that can keep typical spread under 250 points (2.50 USD) on gold. With InpRiskPercent = 1% and 1:3 RR per position, the EA suits a trader who wants a simple price-channel breakout signal plus aggressive position management (3-position pyramid) rather than a heavily filtered entry, and who is comfortable trading through London and New York overlap with the news filter absorbing high-impact events. Set InpUseGMTSessions = true if you want the EA restricted to those two sessions only; leave it false to trade any time the market is open.

Strategy Logic

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

Family: Breakout Magic: 22202022 Version: 2.00

BRIEF: Donchian channel breakout strategy for XAUUSD M5 with ATR-based sizing, profit lock trailing, safe pyramiding, and spread filter. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CheckSignal()
  • OpenBuy()
  • OpenSell()
  • ManageProfitLock()
  • IsGridSafe()
  • CalculateLotSize()
  • CountPositions()
  • DetectGMTOffset_EX02022()
  • ServerToGMT_EX02022()
  • IsMarketOpen_EX02022()
  • InActiveSession_EX02022()
  • IsNewsTime_EX02022()
  • ...and 5 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (21 total across 8 groups):

  • [=== Indicator Settings ===] InpPeriod = 20 // Donchian Period
  • [=== Indicator Settings ===] InpATRPeriod = 14 // ATR Period (for sizing)
  • [=== Money Management ===] InpRiskPercent = 1.0 // Risk Percent per Trade
  • [=== Money Management ===] InpFixedLot = 0.01 // Fixed Lot (if Risk=0)
  • [=== Money Management ===] InpStopLoss = 400 // Stop Loss (points)
  • [=== Money Management ===] InpTakeProfit = 1200 // Take Profit (points)
  • [=== Trade Management ===] InpMagicNumber = 22202022 // Magic Number
  • [=== Trade Management ===] InpTradeComment = "Psgrowth.com Expert_02022" // Trade Comment
  • [=== Trade Management ===] InpMaxSpread = 250 // Max Spread (points)
  • [=== Trade Management ===] InpSlippage = 3 // Slippage
  • [=== Profit Lock / Trailing ===] InpEnableTrail = true // Enable Trailing Stop
  • [=== Profit Lock / Trailing ===] InpTrailStart = 300 // Trail Start Distance (points)
  • [=== Profit Lock / Trailing ===] InpTrailStep = 100 // Trail Step (points)
  • [=== Profit Lock / Trailing ===] InpTrailDistance = 150 // Distance behind price (points)
  • [=== Pyramiding / Scaling ===] InpEnablePyramid = true // Enable Pyramiding
  • [=== Pyramiding / Scaling ===] InpMaxPositions = 3 // Max Open Positions
  • [=== Pyramiding / Scaling ===] InpMinProfitPoints = 250 // Min Profit (points) to Add Next
  • [=== 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 ---
  • [=== Trade Safety (Hardening) ===] InpNewsBufferMinutes = 30 // +------------------------------------------------------------------+
Pseudocode
// Pipsgrowth EX02022 Breakout — Execution Flow (from source analysis)
// Family: Breakout
// Donchian channel breakout strategy for XAUUSD M5 with ATR-based sizing, profit lock trailing, safe pyramiding, and spread filter. 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 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
InpPeriod20Donchian Period
InpATRPeriod14ATR Period (for sizing)
InpRiskPercent1.0Risk Percent per Trade
InpFixedLot0.01Fixed Lot (if Risk=0)
InpStopLoss400Stop Loss (points)
InpTakeProfit1200Take Profit (points)
InpMagicNumber22202022Magic Number
InpTradeComment"Psgrowth.com Expert_02022"Trade Comment
InpMaxSpread250Max Spread (points)
InpSlippage3Slippage
InpEnableTrailtrueEnable Trailing Stop
InpTrailStart300Trail Start Distance (points)
InpTrailStep100Trail Step (points)
InpTrailDistance150Distance behind price (points)
InpEnablePyramidtrueEnable Pyramiding
InpMaxPositions3Max Open Positions
InpMinProfitPoints250Min Profit (points) to Add Next
InpNewYorkEndGMT21--- Hardening: Capital Protection ---
InpCapAmount0.0Capital cap amount (0=disabled)
InpDailyLossLimitPct5.0--- Hardening: Trade Safety ---
InpNewsBufferMinutes30+------------------------------------------------------------------+
Source Code (.mq5)Open Source
Pipsgrowth_com_EX02022.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX02022 DonchianBreakout_XAUUSD_5M — Donchian breakout with trailing and pyramiding, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>

CTrade         trade;
CPositionInfo  position;
CSymbolInfo    mysymbol;
CAccountInfo   account;

//--- Input Groups
input group "=== Indicator Settings ==="
input int      InpPeriod         = 20;       // Donchian Period
input int      InpATRPeriod      = 14;       // ATR Period (for sizing)

input group "=== Money Management ==="
input double   InpRiskPercent    = 1.0;      // Risk Percent per Trade
input double   InpFixedLot       = 0.01;     // Fixed Lot (if Risk=0)
input int      InpStopLoss       = 400;      // Stop Loss (points)
input int      InpTakeProfit     = 1200;     // Take Profit (points)

input group "=== Trade Management ==="
input int      InpMagicNumber    = 22202022; // Magic Number
input string   InpTradeComment   = "Psgrowth.com Expert_02022"; // Trade Comment
input int      InpMaxSpread      = 250;      // Max Spread (points)
input int      InpSlippage       = 3;        // Slippage

input group "=== Profit Lock / Trailing ==="
input bool     InpEnableTrail    = true;     // Enable Trailing Stop
input int      InpTrailStart     = 300;      // Trail Start Distance (points)
input int      InpTrailStep      = 100;      // Trail Step (points)
input int      InpTrailDistance  = 150;      // Distance behind price (points)

input group "=== Pyramiding / Scaling ==="
input bool     InpEnablePyramid  = true;     // Enable Pyramiding
input int      InpMaxPositions   = 3;        // Max Open Positions
input int      InpMinProfitPoints= 250;      // Min Profit (points) to Add Next

//--- Handles
int    hATR;

//--- Global Buffers
double bufATR[];

//--- Hardening Globals
int      g_gmtOffset       = 3;
int      g_tradesToday     = 0;
datetime g_dayStartTime    = 0;
double   g_initialBalance  = 0.0;
datetime g_cooldownUntil   = 0;
int      g_consecLosses    = 0;
double   g_realizedToday   = 0.0;
double   g_realizedWeek    = 0.0;
datetime g_weekStartTime   = 0;

Full source code available on download

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

Tags:ex02022breakoutpipsgrowthfreemt5xauusd

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