P
PipsGrowth
BreakoutOpen Source – Free

Pipsgrowth EX02021 Breakout

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX02021 Donchian_XAUUSD_5M — Donchian breakout with ATR/RSI/MACD filters, full 12-layer stack.

Overview

EX02021 is a Donchian-channel breakout system aimed squarely at XAUUSD on the 5-minute chart. The core idea is to wait for a 20-bar high/low range to be broken on the closed candle, then let a three-stage confirmation filter decide whether that breakout is tradable. The 20-period Donchian envelope is computed from bars InpDonchianShift to InpDonchianShift + InpDonchianPeriod (default shift=1, period=20) so the EA reads the band off confirmed bars — never the still-forming candle. A long signal requires close[1] > upper and close[2] <= upper; a short signal is the mirror. That double-bar requirement is the most important gate in the EA: a candle can sit above the band for three bars in a row and EX02021 will only fire on the first bar that punched through. After three bars above, the breakout is stale and the EA ignores it until price re-enters and breaks again.

Three filter stages run on every confirmed bar. First the ATR floor: if ATR(14) divided by _Point is below InpMinAtr (0.5 default), the trade is skipped — this is a de-facto no-trade filter against ultra-quiet candles. Second, an RSI(14) directional check: longs require RSI > 50, shorts require RSI < 50, but only when InpUseRsi is true. Third, MACD(12,26,9) on PRICE_CLOSE: longs need the MACD line above the signal line, shorts need it below — both filters can be disabled independently via InpUseMacd. A signal that fails any of these is zeroed out before the order manager ever sees it. The result is a tighter pipeline than a raw Donchian: most candles that touch the band never become trades.

Risk math lives in GetLotSize(). With InpRiskPercent (1.0% default) the EA sizes the position to risk 1% of AccountInfoDouble(ACCOUNT_BALANCE) over the SL distance using m_symbol.TickValue() and m_symbol.TickSize(). Set InpRiskPercent to 0 and the EA falls back to a flat InpFixedLot (0.01). The output is rounded to the symbol's lot step, clamped to LotsMin()/LotsMax(), and then capped at InpMaxLotSize (10.0). That 10-lot ceiling is a guard for prop-firm accounts where a runaway money-management module would otherwise exceed the broker's lot limit.

SL and TP are ATR-anchored, not fixed-pips. Stop loss = ATR(14) × InpSL_ATR_Mult (1.5) divided by _Point and rounded to int points, with a 50-point minimum. Take profit = ATR(14) × InpTP_ATR_Mult (2.0). The ratio is 1.5 : 2.0 = 1 : 1.33, which is tighter than the 1:2 many breakout EAs run. The trade-off: more trades hit TP because the target is closer, but the winner-to-loser ratio is also lower. Both prices are normalized through NormalizePrice_EX02021 so they survive the digit transformation on ECN quotes with nonstandard ticks.

EX02021 does not use a classic trailing stop. Instead it runs ManageProfitLock() on every tick. The function walks PositionsTotal() and, for any position that has moved at least InpLockTrigger (300) points into profit, it ratchets the stop loss in InpLockStep (50) point increments toward a target of InpLockDistance (100) points behind current price. The SL only ever moves in the favorable direction (it is a one-way ratchet), and the TP is left untouched. This is sometimes called a 'profit lock' or 'chandelier' style trailing — the position's stop loss does not catch up to a fast move until 300 points of profit are already on the table, then it advances slowly enough that a normal pullback won't tag it.

Pyramiding is on by default. CheckPyramidSafety() enforces a 'secured profit' rule: an additional position in the same direction is only allowed if the existing position's stop loss is already in front of its open price by at least InpPyramidMinProfit (100) points. That is, the previous position must be in a 'locked-in' state where even a worst-case stop-out produces a profit. The cap is InpMaxPyramidTrades (3). If InpUsePyramid is off, only one position can be open at a time. The function also blocks adding against existing opposite-side positions, so the EA cannot be net-long and net-short simultaneously.

The hardening layer is more lenient than the more recent breakout EAs in the family. There is no regime classifier and no ADX threshold. The trade filter instead relies on: InpMaxSpread (200 points — generous for XAUUSD on most brokers), InpUseTimeFilter with InpStartTime/InpEndTime (08:00–20:00 server time by default), and an InpCloseAtEnd switch that flattens everything at end-time if true. On top of that, the EA runs the full safety stack: IsMarketOpen_EX02021() blocks weekends plus the Sunday 22:00 GMT open and Friday 22:00 GMT close, InActiveSession_EX02021() gates London (7-16 GMT) and New York (12-21 GMT) but is off by default (InpUseGMTSessions = false), IsNewsTime_EX02021() calls CalendarValueHistory for ±30 min around high-impact events, and a 5% daily realized-loss limit (InpDailyLossLimitPct) plus a 5-consecutive-loss → 4-hour cooldown via OnTradeTransaction. A capital cap (InpCapAmount) and minimum equity guard (InpMinEquityPct = 70%) are present but disabled by default; enable them by setting InpCapAmount above zero and the EA treats the lesser of cap and equity as the effective balance.

Order execution goes through three retry passes with 200 ms Sleep() on TRADE_RETCODE_REQUOTE, _TIMEOUT, _PRICE_OFF, and _PRICE_CHANGED. A pre-trade OrderCalcMargin check rejects entries that would exceed free margin. Lot clamping normalizes the result to the symbol's step, minimum, maximum, and InpMaxLotSize. The OnTester formula is profit * profitFactor / maxDD with a 10-trade gate — lighter than the 30-trade gate used elsewhere in the family, which means short out-of-sample windows can still produce a non-zero custom criterion.

For deployment, the EA assumes a broker with reliable price feeds on XAUUSD M5: spreads up to 200 points (2.0 pips on a 5-digit gold quote) and slippage tolerance up to 30 points will pass. Because the strategy is purely bar-driven with no indicator state across symbols, the chart can be detached and the EA will run. The minimum deposit on the listing is $100, but with a 1% risk default and 0.01-lot minimum the practical floor is closer to $500–$1,000 for the EA to function at its full sizing — accounts under $200 will see most orders clamped to the minimum lot and the profit-lock ratchet doing most of the work.

Strategy Deep Dive

On every tick OnTick() calls RefreshRates(), rejects the tick if the spread exceeds InpMaxSpread (200 points), resets daily counters via UpdateDailyCounters_EX02021(), and runs ManageProfitLock() on the open positions before doing anything else. It then checks IsTradingTime() against InpStartTime/InpEndTime (08:00–20:00 server by default) and, if outside the window, optionally flattens with CloseAllPositions(). The full safety gate IsSafeToTrade_EX02021() runs next, fusing weekend checks, the optional London/NY GMT session window, the CalendarValueHistory news filter (±30 min around high-impact events), the optional capital cap, the 70% minimum equity guard, the daily trade count cap, the consecutive-loss cooldown, and the 5% daily realized loss limit.

Once a new bar opens, the EA reads ATR(14) and skips the trade if ATR is below InpMinAtr (0.5 points). It then walks InpDonchianPeriod (20) bars from InpDonchianShift (1) backwards to compute the upper and lower band using iHigh/iLow, requires close[1] > upper with close[2] <= upper (or the mirror for shorts) to declare a breakout, and gates that with InpUseRsi (RSI 14 above/below 50) and InpUseMacd (MACD 12/26/9 line vs signal). The order manager then calls CheckPyramidSafety() which enforces the 'secured profit' rule for the next add-on. GetLotSize() sizes the trade to InpRiskPercent (1.0% of balance by default) or falls back to InpFixedLot (0.01) when risk is off. A pre-trade OrderCalcMargin check rejects entries that would exceed free margin, then m_trade.Buy or m_trade.Sell is called with up to 3 retries on requote/timeout/price-off/price-changed errors, sleeping 200 ms between attempts.

Entry Signal

EX02021 enters a long when the closed bar (shift=1) closes above the 20-period Donchian upper band and the prior bar (shift=2) closed at or below that band, then passes the ATR floor (>0.5 points), RSI(14) > 50, and MACD(12,26,9) line above signal filters. Short entries mirror that: closed bar below the lower band, prior bar at or above, RSI < 50, MACD line below signal. Each filter can be disabled independently. The first bar to punch through the band is the only one that fires — subsequent bars above the band do not re-arm until price dips back inside.

Exit Signal

EX02021 exits via two paths. The default is TP at ATR(14) × InpTP_ATR_Mult (2.0) for a 1:1.33 risk-to-reward against the ATR(14) × 1.5 stop. The secondary exit is ManageProfitLock() running every tick: once a position is 300 points in profit (InpLockTrigger), the stop is ratcheted forward in 50-point steps (InpLockStep) toward 100 points behind price (InpLockDistance). Optionally, InpCloseAtEnd can flatten all positions when the configured end-time (20:00 server by default) is reached.

Stop Loss

Stop loss is anchored to ATR(14) × InpSL_ATR_Mult (1.5), converted to points and rounded, with a 50-point minimum. The SL is then managed by the profit-lock ratchet once 300 points of profit are banked — it advances only in the favorable direction in 50-point steps, and never moves backward.

Take Profit

Take profit is ATR(14) × InpTP_ATR_Mult (2.0) for a 1.5 : 2.0 = 1 : 1.33 risk-to-reward. The TP is fixed at entry; it is not modified by the profit-lock routine. In practice, the trailing ratchet frequently closes the position before the TP is hit because the stop advances to 100 points behind price once profit exceeds 300 points.

Best For

Best deployed on XAUUSD M5 with a low-spread ECN or RAW-spread broker (the EA's 200-point max-spread filter gives a lot of headroom, but 30+ point slippage tolerance suggests deep liquidity). Recommended minimum balance is $500–$1,000 to let the 1% risk default express itself before lot-size clamping kicks in; the listing's $100 floor is a hard minimum but most small accounts will see orders clamped to 0.01 lot. The time filter is set to 08:00–20:00 server time by default, which on most GMT+2/GMT+3 servers maps to roughly London + New York overlap and the early Asian close — flip InpUseGMTSessions to true if you want the gate to be in GMT instead. Suitable for traders who want a clean Donchian breakout with two independent confirmation filters and a one-way profit-lock ratchet, and who are comfortable with a tighter 1:1.33 RR than the typical 1:2 breakout EAs in this family.

Strategy Logic

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

Family: Breakout Magic: 22202021 Version: 2.00

BRIEF: Donchian Channel Breakout strategy for XAUUSD M5 with ATR/RSI/MACD filters, safe pyramiding, profit lock trailing, and time management. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CheckPyramidSafety()
  • ManageProfitLock()
  • GetLotSize()
  • RefreshRates()
  • IsTradingTime()
  • StrToTime()
  • CloseAllPositions()
  • DetectGMTOffset_EX02021()
  • ServerToGMT_EX02021()
  • IsMarketOpen_EX02021()
  • InActiveSession_EX02021()
  • IsNewsTime_EX02021()
  • ...and 7 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (36 total across 12 groups):

  • [=== Donchian Channel ===] InpDonchianPeriod = 20 // Donchian Channel Period
  • [=== Donchian Channel ===] InpDonchianShift = 1 // Shift (bars)
  • [=== ATR Settings ===] InpAtrPeriod = 14 // ATR Period
  • [=== ATR Settings ===] InpMinAtr = 0.5 // Min ATR (Points) for trading
  • [=== RSI Filter ===] InpUseRsi = true // Use RSI Filter
  • [=== RSI Filter ===] InpRsiPeriod = 14 // RSI Period
  • [=== RSI Filter ===] InpRsiBullLevel = 50 // RSI Bullish Above
  • [=== RSI Filter ===] InpRsiBearLevel = 50 // RSI Bearish Below
  • [=== MACD Filter ===] InpUseMacd = true // Use MACD Filter
  • [=== MACD Filter ===] InpMacdFast = 12 // MACD Fast
  • [=== MACD Filter ===] InpMacdSlow = 26 // MACD Slow
  • [=== MACD Filter ===] InpMacdSignal = 9 // MACD Signal
  • [=== Money Management ===] InpRiskPercent = 1.0 // Risk per trade (% of Balance)
  • [=== Money Management ===] InpFixedLot = 0.01 // Fixed Lot (if Risk=0)
  • [=== Money Management ===] InpMaxLotSize = 10.0 // Max Lot Size per trade
  • [=== Money Management ===] InpSL_ATR_Mult = 1.5 // Stop Loss ATR Multiplier
  • [=== Money Management ===] InpTP_ATR_Mult = 2.0 // Take Profit ATR Multiplier
  • [=== Trade Management ===] InpSlippage = 30 // Max Slippage (Points)
  • [=== Trade Management ===] InpMaxSpread = 200 // Max Spread (Points)
  • [=== Trade Management ===] InpMagicNumber = 22202021 // Magic Number
  • [=== Trade Management ===] InpTradeComment = "Psgrowth.com Expert_02021" // Trade Comment
  • [=== Pyramid / Scaling ===] InpUsePyramid = true // Enable Safe Pyramiding
  • [=== Pyramid / Scaling ===] InpMaxPyramidTrades = 3 // Max Open Positions
  • [=== Pyramid / Scaling ===] InpPyramidMinProfit = 100 // Min Secured Profit (Points) for Next Add
  • [=== Profit Lock & Trail ===] InpUseProfitLock = true // Enable Profit Lock / Trailing
  • [=== Profit Lock & Trail ===] InpLockTrigger = 300 // Trigger Distance (Points in Profit)
  • [=== Profit Lock & Trail ===] InpLockStep = 50 // Step to advance SL (Points)
  • [=== Profit Lock & Trail ===] InpLockDistance = 100 // Distance to keep SL from Price (Points)
  • [=== Time Management ===] InpUseTimeFilter = true // Enable Time Filter
  • [=== Time Management ===] InpStartTime = "08:00" // Start Trading Time (Server)
  • [=== Time Management ===] InpEndTime = "20:00" // End Trading Time (Server)
  • [=== Time Management ===] InpCloseAtEnd = false // Close all at end time
  • [=== 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 EX02021 Breakout — Execution Flow (from source analysis)
// Family: Breakout
// Donchian Channel Breakout strategy for XAUUSD M5 with ATR/RSI/MACD filters, safe pyramiding, profit lock trailing, and time management. 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
InpDonchianPeriod20Donchian Channel Period
InpDonchianShift1Shift (bars)
InpAtrPeriod14ATR Period
InpMinAtr0.5Min ATR (Points) for trading
InpUseRsitrueUse RSI Filter
InpRsiPeriod14RSI Period
InpRsiBullLevel50RSI Bullish Above
InpRsiBearLevel50RSI Bearish Below
InpUseMacdtrueUse MACD Filter
InpMacdFast12MACD Fast
InpMacdSlow26MACD Slow
InpMacdSignal9MACD Signal
InpRiskPercent1.0Risk per trade (% of Balance)
InpFixedLot0.01Fixed Lot (if Risk=0)
InpMaxLotSize10.0Max Lot Size per trade
InpSL_ATR_Mult1.5Stop Loss ATR Multiplier
InpTP_ATR_Mult2.0Take Profit ATR Multiplier
InpSlippage30Max Slippage (Points)
InpMaxSpread200Max Spread (Points)
InpMagicNumber22202021Magic Number
InpTradeComment"Psgrowth.com Expert_02021"Trade Comment
InpUsePyramidtrueEnable Safe Pyramiding
InpMaxPyramidTrades3Max Open Positions
InpPyramidMinProfit100Min Secured Profit (Points) for Next Add
InpUseProfitLocktrueEnable Profit Lock / Trailing
InpLockTrigger300Trigger Distance (Points in Profit)
InpLockStep50Step to advance SL (Points)
InpLockDistance100Distance to keep SL from Price (Points)
InpUseTimeFiltertrueEnable Time Filter
InpStartTime"08:00"Start Trading Time (Server)
InpEndTime"20:00"End Trading Time (Server)
InpCloseAtEndfalseClose all at end time
InpNewYorkEndGMT21--- Hardening: Capital Protection ---
InpCapAmount0.0Capital cap amount (0=disabled)
InpDailyLossLimitPct5.0--- Hardening: Trade Safety ---
InpNewsBufferMinutes30+------------------------------------------------------------------+
Source Code (.mq5)Open Source
Pipsgrowth_com_EX02021.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX02021 Donchian_XAUUSD_5M — Donchian breakout with ATR/RSI/MACD filters, full 12-layer stack."
#include <Trade/Trade.mqh>
#include <Trade/SymbolInfo.mqh>
#include <Trade/PositionInfo.mqh>
#include <Trade/AccountInfo.mqh>

// --- Global Objects ---
CTrade         m_trade;
CSymbolInfo    m_symbol;
CPositionInfo  m_position;
CAccountInfo   m_account;

// --- Inputs ---

input group "=== Donchian Channel ==="
input int      InpDonchianPeriod    = 20;          // Donchian Channel Period
input int      InpDonchianShift     = 1;           // Shift (bars)

input group "=== ATR Settings ==="
input int      InpAtrPeriod         = 14;          // ATR Period
input double   InpMinAtr            = 0.5;         // Min ATR (Points) for trading

input group "=== RSI Filter ==="
input bool     InpUseRsi            = true;        // Use RSI Filter
input int      InpRsiPeriod         = 14;          // RSI Period
input int      InpRsiBullLevel      = 50;          // RSI Bullish Above
input int      InpRsiBearLevel      = 50;          // RSI Bearish Below

input group "=== MACD Filter ==="
input bool     InpUseMacd           = true;        // Use MACD Filter
input int      InpMacdFast          = 12;          // MACD Fast
input int      InpMacdSlow          = 26;          // MACD Slow
input int      InpMacdSignal        = 9;           // MACD Signal

input group "=== Money Management ==="
input double   InpRiskPercent       = 1.0;         // Risk per trade (% of Balance)
input double   InpFixedLot          = 0.01;        // Fixed Lot (if Risk=0)
input double   InpMaxLotSize        = 10.0;        // Max Lot Size per trade
input double   InpSL_ATR_Mult       = 1.5;         // Stop Loss ATR Multiplier
input double   InpTP_ATR_Mult       = 2.0;         // Take Profit ATR Multiplier

input group "=== Trade Management ==="
input int      InpSlippage          = 30;          // Max Slippage (Points)
input int      InpMaxSpread         = 200;         // Max Spread (Points)
input ulong    InpMagicNumber       = 22202021;    // Magic Number
input string   InpTradeComment      = "Psgrowth.com Expert_02021"; // Trade Comment

input group "=== Pyramid / Scaling ==="
input bool     InpUsePyramid        = true;        // Enable Safe Pyramiding
input int      InpMaxPyramidTrades  = 3;           // Max Open Positions
input int      InpPyramidMinProfit  = 100;         // Min Secured Profit (Points) for Next Add

input group "=== Profit Lock & Trail ==="
input bool     InpUseProfitLock     = true;        // Enable Profit Lock / Trailing
input int      InpLockTrigger       = 300;         // Trigger Distance (Points in Profit)
input int      InpLockStep          = 50;          // Step to advance SL (Points)

Full source code available on download

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

Tags:ex02021breakoutpipsgrowthfreemt5xauusd

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