P
PipsGrowth
BreakoutOpen Source – Free

Pipsgrowth EX02019 Breakout

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX02019 Donchian_XAUUSD_5M — Donchian channel breakout with multi-indicator confirmation, full 12-layer stack.

Overview

Pipsgrowth EX02019 Breakout is a configuration-driven Donchian channel breakout EA for XAUUSD on the M5 chart, built around a four-mode Donchian engine and a five-indicator confirmation vote. Rather than committing to one rigid breakout flavor, the EA exposes a InpDonchianStrategy enum that lets the trader pick between DONCHIAN_BREAKOUT (the default — trigger as soon as the live ask crosses above the 20-bar high or the previous close finishes below the 20-bar low), DONCHIAN_RETEST (mark a breakout on the previous bar, then re-enter on a return to the broken level within a 5-point tolerance), DONCHIAN_MIDLINE (trade the cross of the 20-bar midpoint) and DONCHIAN_HYBRID (require at least four of the five confirmations AND satisfy a breakout OR a retest condition). The Donchian high, low, and midpoint are computed on the fly from iHighest/iLowest over InpDonchianPeriod = 20 bars, shifted by InpDonchianShift = 1 so the channel is always built on closed bars, never on the still-forming current bar.

The signal decision lives in GetEntrySignal(). Every tick the EA pulls a snapshot of the closed bar (shift = 1) and caches the values of all five confirmation indicators in static doubles so the per-tick cost stays flat regardless of how many indicators are enabled. The five confirmation votes are: ATR(14) direction (rising = buy vote, falling = sell vote), MACD main vs signal line on the 12/26/9 setup, ADX(14) above InpADXMin = 20 with +DI vs -DI dominance, Bollinger Band position (close above upper = buy, close below lower = sell) on 20 bars / 2.0 deviations, and RSI(14) above/below the 50 midline. Each enabled indicator that agrees with the direction adds one to buyConfirm or sellConfirm; the trade only fires when the count meets or exceeds InpDonchianConfirmations = 3. So with the defaults — all five indicators on, threshold 3 — the EA demands at least three of the five to agree before it will consider a Donchian breakout valid. A sixth, optional gate is the MA filter (InpMAFilter): a single value, all on closed-bar data, drawn from MA_NONE (default — gate skipped), MA_EMA, MA_TEMA (computed inline as 3*EMA1 − 3*EMA2 + EMA3 so no extra handle is required), MA_HAMA (LWMA), or MA_GAUSSIAN (SMMA). With any non-NONE setting, the close must also be on the correct side of the filter MA. Signal printing and debug logging are routed through Log() which honours the InpLogTradeEvents and InpLogTickEvents toggles.

Order placement goes through OpenTradeWithSignal()OpenMarketOrder(). The EA calls OrderCalcMargin first to verify free margin, validates that SL and TP are at least StopsLevel + InpMaxSlippage + 1 points away from the requested price (and snaps them outward if they're inside the broker's freeze zone), then submits a CTrade deal with up to three retries at 200 ms on TRADE_RETCODE_REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED. Filling mode is read from the symbol via SymbolInfoInteger(_Symbol, SYMBOL_FILLING_MODE), and the magic number is fixed at InpMagicNumber = 22202019 so any other EAs running on the same account can be told apart. If InpAllowOnlyProfitableAdditions is on (default), the EA also refuses to add a position in the same direction unless every existing EA position of that direction is in net profit of at least InpMinProfitPerTradeToAdd = 5.0 points per lot — a deliberate anti-martingale filter. InpOrderType lets the trader lock the EA to buys, sells, or both (default: both).

Stop and target calculation is intentionally a two-tier cascade. CalculateStopLossPrice() first calls GetIndicatorStopLoss() (a stub that returns 0 unless the trader implements it) and, if that returns 0, falls back to a hard SL of InpHardSL_Points = 50 points when InpUseHardSL is true. An ATR-based SL with InpATR_SL_Period = 14 and InpATR_SL_Multiplier = 2.0 is also available as an input but is not wired into the cascade by default — it is a hook for trader extension. CalculateTakeProfitPrice() follows the same pattern: tries GetIndicatorTakeProfit() first, then falls back to the fixed InpFixedTP_Points = 100 points. The InpUseTrailingStop, InpMoveSLToBreakEven, InpUseTimeBasedSL and InpUseProfitLock inputs are present and configurable, but the ManagePosition() body in this build only reads the position's entry price — the trailing / breakeven / profit-lock wiring is left as a trader-implementation step. Time-based exits are honoured via InpTimeBasedSLMinutes = 120 and via the end-of-session force-close and end-of-day (default 23:50 server time) paths in HandleSessionAndEndOfDayClosures().

Session control has two parallel systems. The first is InpEnableSessionControl = false by default with up to three server-time windows defined by InpSession1Start/End (default 08:00–16:00), InpSession2Start/End (default 18:00–22:00), and InpSession3Start/End. With this on, the EA will pause new entries InpPauseMinutesBeforeEndOfSession = 30 minutes before the window closes, optionally force-close everything InpForceCloseMinutesBeforeSessionEnd = 5 minutes before close, and optionally flatten the book at InpEndOfDayCloseTime. The second is the hardening layer: InpUseGMTSessions = false by default, with the broker server time converted to GMT via DetectGMTOffset_EX02019() (a best-of--12..+12 heuristic that scores weekday and hour plausibility) and then tested against InpLondonStartGMT = 7 to InpLondonEndGMT = 16 and InpNewYorkStartGMT = 12 to InpNewYorkEndGMT = 21. Both layers can be enabled together; an entry must clear both to be eligible.

Risk management runs in two layers. The classic drawdown guard: InpMaxDrawdownPercent = 20.0 (or InpMaxDrawdownAmount in account currency) is checked by IsDrawdownLimitOk() on every tick — when the live drawdown from balance hits the cap, no new entries fire. The hardening capital guard: with InpCapAmount > 0 the EA treats min(InpCapAmount, equity) as its effective capital and refuses to trade if that effective cap falls below InpCapFloor = 1000. InpMinEquityPct = 70.0 blocks entries if equity drops to less than 70% of the initial balance captured in OnInit. InpDailyLossLimitPct = 5.0 compares the realized P&L tracked in OnTradeTransaction() against 5% of the initial balance and freezes entries for the rest of the day if the threshold is breached. The same OnTradeTransaction handler increments g_consecutive_losses on every loss deal; once it reaches InpMaxConsecutiveLosingTrades = 3, g_pause_until_time is set to now + 60 minutes and CanOpenNewTrade() blocks all new entries until the pause expires. Day-of-week control defaults to Monday-to-Friday via InpTradingDays = TRADING_DAYS_MON_TO_FRI, with seven per-day toggles for the TRADING_DAYS_CUSTOM option.

Lot sizing is the same pair the rest of the family uses. InpLotSizingMethod = LOT_FIXED with InpLotSize = 0.01 is the default; the LOT_AUTO_SCALED mode sizes on account balance or equity (depending on InpAutoLotBaseType, default equity) using the InpAutoLot_Increment / InpAutoLot_CapitalPerIncrement = 0.01 / 1000 ratio, clamped to InpAutoLot_MinAllowedLot = 0.01 and InpAutoLot_MaxAllowedLot = 10.0, then snapped to the broker's LotsStep and bounded by LotsMin / LotsMax. InpMaxOpenTrades = 1 and InpOneTradeOnly = true keep the default profile to a single position at a time, with InpMinBarsBetweenTrades = 1 as the spacing rule and InpMaxTradesPerDay = 5 as the daily ceiling.

The news filter is off by default (InpAvoidTradingDuringNews = false). When enabled, IsForexFactoryNewsEventActive() pulls the weekly XML from https://nfs.faireconomy.media/ff_calendar_thisweek.xml via WebRequest (with a 5000 ms timeout), caches the response for g_news_cache_minutes = 10, parses it with ParseFFNews(), then matches each event's currency against the symbol's base and quote (or ALL). For USD-affecting events the EA blocks entries within InpNewsBufferMinutes = 30 on either side of the release. Impact filter defaults to high only (InpAvoidTradingDuringHighImpactNews = true); medium and low can be added individually. The InpNewsTimeZoneOffsetHours input lets traders who run a non-UTC calendar compensate for the offset.

The strategy tester custom criterion in OnTester() is (profit * profitFactor) / maxDD with profitFactor clamped to 1.0 if it goes non-positive or above 1000, maxDD clamped to 1.0 if non-positive, and a hard gate returning 0 if fewer than 10 trades were taken — the same shape used elsewhere in the family. The parameters JSON for the page exposes every input exactly as the EA exposes it (group, type, default, comment), so what you see in the table is what gets compiled. With riskLevel = MEDIUM and minDeposit = 100 in the listing, the intended deployment is a small live account on a low-spread XAUUSD ECN, with the trader expected to back-test the four Donchian modes and the five MA filters separately before committing capital — they really are four different strategies sharing one parameter shell.

Strategy Deep Dive

Pipsgrowth EX02019 reads the previous closed M5 bar once per tick through GetEntrySignal() and caches the five confirmation indicators in static doubles so the per-tick cost stays flat. The Donchian channel is built from iHighest / iLowest over 20 bars on closed data, then evaluated under whichever of the four modes InpDonchianStrategy selects — strict breakout, retest, midline cross, or the hybrid that needs four confirmations. OpenMarketOrder() runs a margin pre-check via OrderCalcMargin, validates the SL and TP against the broker's StopsLevel, then submits a CTrade deal with up to three retries at 200 ms on requote/timeout/price-changed/price-off. The hardening layer runs in parallel: DetectGMTOffset_EX02019() finds a plausible broker GMT offset, InActiveSession_EX02019() gates entries on the union of London 07–16 GMT and New York 12–21 GMT, and OnTradeTransaction() updates realised P&L plus the consecutive-loss counter that triggers the 60-minute cooldown.

Entry Signal

Long entry fires when the live ask crosses above the 20-bar Donchian high (or, in DONCHIAN_RETEST mode, when the previous close broke the high and price returns to it within 5 points), AND at least 3 of 5 confirmation indicators agree (ATR rising, MACD main>signal, ADX>=20 with +DI>-DI, close>BB upper, RSI>50). Short entry is the mirror image against the 20-bar low. An optional MA filter (EMA / TEMA / HAMA / Gaussian) can require the close to be on the correct side of the filter before the entry is allowed through.

Exit Signal

Exit is anchored to the fixed take-profit at 100 points by default, or to the indicator-based TP if GetIndicatorTakeProfit() is implemented by the trader. End-of-session force close fires 5 minutes before the session window closes when enabled, and the 23:50 server-time EOD flat is honoured if InpCloseAllTradesAtEndOfDay is on. The ManagePosition() body in this build is a stub — trailing-stop, breakeven, profit-lock, and time-based SL inputs are present in the parameter list but are not wired into the per-tick management loop.

Stop Loss

Stop loss defaults to a hard 50 points (InpHardSL_Points) on each side of entry, or 0 (no SL) if InpUseHardSL is off. An ATR-based stop using ATR(14)*2.0 is available as InpATR_SL_Multiplier and is exposed through the GetIndicatorStopLoss() hook for trader extension, but the cascade falls through to the hard SL unless the hook is implemented. A StopsLevel + MaxSlippage + 1 points guard in OpenMarketOrder() snaps the SL outward if it lands inside the broker freeze zone.

Take Profit

Take profit defaults to a fixed 100 points (InpFixedTP_Points), with 0 (no TP) if the input is set to 0. The GetIndicatorTakeProfit() hook is available for traders who want a swing-high / swing-low based exit, but is not implemented in the base build, so all live trades take the fixed 100-point target unless that hook is overridden.

Best For

Built for $100+ accounts trading XAUUSD on M5 via a low-spread ECN/RAW broker (the high spread tolerance default of 0 means the spread filter is effectively off and any spread is allowed — preferable on ECNs where spread is consistently under 30 points). Best in the London and New York session overlap (12:00–16:00 GMT) where XAUUSD typically trends, with GMT session hardening on to keep the EA out of the dead 21:00–07:00 GMT window. Recommended for traders who want to back-test all four Donchian modes (Breakout / Retest / Midline / Hybrid) and all five MA filters (None / EMA / TEMA / HAMA / Gaussian) before committing live capital, since they really are four different strategies in one parameter shell. Risk level is MEDIUM with the default 50/100 point SL/TP and 0.01 lot.

Strategy Logic

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

Family: Breakout Magic: 22202019 Version: 2.00

BRIEF: Universal Donchian channel breakout EA for XAUUSD M5 with multi-indicator confirmation, comprehensive money management, session control, and smart exit timing. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • StringToTime()
  • Log()
  • ParseFFDateTime()
  • ExtractTag()
  • ParseFFNews()
  • InitIndicators()
  • ReleaseIndicators()
  • InitializeTradeObjects()
  • ResetStateVariables()
  • ValidateInputParameters()
  • ValidateLotSettings()
  • ValidateRiskSettings()
  • ...and 34 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (110 total across 11 groups):

  • [=== GMT Session Filter (Hardening) ===] InpNewYorkEndGMT = 21 // --- Hardening: Capital Protection ---
  • [=== Capital Protection (Hardening) ===] InpCapAmount = 0.0 // Capital cap amount (0=disabled)
  • [=== Trade Settings ===] InpLotSize = 0.01 // Fixed Lot Size (if LotSizingMethod is LOT_FIXED)
  • [=== Trade Settings ===] InpMagicNumber = 22202019 // Magic Number for orders (unique identifier for this EA)
  • [=== Trade Settings ===] InpTradeComment = "Psgrowth.com Expert_02019" // Trade Comment
  • [=== Trade Settings ===] InpMaxSlippage = 5 // Slippage in points (max allowed price deviation)
  • [=== Trade Settings ===] InpMaxSpreadPoints = 0 // Maximum allowed spread in points (0 for no check)
  • [=== Trade Settings ===] InpOneTradeOnly = true // Allow only one trade at a time (per symbol for this EA)
  • [=== Trade Settings ===] InpMaxOpenTrades = 1 // Maximum allowed open trades at the same time
  • [=== Trade Settings ===] InpAllowOnlyProfitableAdditions = true // Only open new trades if all existing (by this EA) are in profit
  • [=== Trade Settings ===] InpMinProfitPerTradeToAdd = 5.0 // Min. profit in points for each existing trade to open new one
  • [=== Trade Settings ===] InpMaxDrawdownPercent = 20.0 // Max drawdown % allowed (0 to disable)
  • [=== Trade Settings ===] InpMaxDrawdownAmount = 0.0 // Max drawdown amount in account currency (0 to disable)
  • [=== Trade Settings ===] InpMaxTradesPerDay = 5 // Max trades per day (0 for unlimited)
  • [=== Trade Settings ===] InpMinBarsBetweenTrades = 1 // Min bars between opening new trades
  • [=== Trade Settings ===] InpMaxConsecutiveLosingTrades = 3 // Pause trading after this many consecutive losses (0 to disable)
  • [=== Trade Settings ===] InpPauseMinutesAfterLosingStreak = 60 // Minutes to pause after reaching losing streak
  • [=== Trade Settings ===] InpAvoidTradingDuringNews = false // Avoid trading during news events
  • [=== Trade Settings ===] InpNewsBufferMinutes = 30 // Minutes before and after news to avoid trading
  • [=== Trade Settings ===] InpAvoidTradingDuringHighImpactNews = true // Avoid high impact news
  • [=== Trade Settings ===] InpAvoidTradingDuringMediumImpactNews = false // Avoid medium impact news
  • [=== Trade Settings ===] InpAvoidTradingDuringLowImpactNews = false // Avoid low impact news
  • [=== Trade Settings ===] InpNewsTimeZoneOffsetHours = 0 // Offset in hours from UTC (e.g., 2 for UTC+2, -5 for UTC-5)
  • [=== Trade Settings ===] InpNewsSource = NEWS_SOURCE_FOREX_FACTORY // News source for news filtering
  • [=== Money Management & Lot Sizing ===] InpLotSizingMethod = LOT_FIXED // Lot Sizing Method
  • [=== Money Management & Lot Sizing ===] InpAutoLotBaseType = BASE_ACCOUNT_EQUITY // Capital base for auto lot calculation
  • [=== Money Management & Lot Sizing ===] InpAutoLot_Increment = 0.01 // Lot size to add (e.g., 0.01)
  • [=== Money Management & Lot Sizing ===] InpAutoLot_CapitalPerIncrement = 1000 // For every X amount of capital
  • [=== Money Management & Lot Sizing ===] InpAutoLot_MaxAllowedLot = 10.0 // Maximum lot size allowed by auto calculation
  • [=== Money Management & Lot Sizing ===] InpAutoLot_MinAllowedLot = 0.01 // Minimum lot size allowed by auto calculation
  • [=== Money Management & Lot Sizing ===] InpOrderType = ORDER_TYPE_BUY_SELL // Order type
  • [=== Stop Loss Management ===] InpUseHardSL = true // Enable Hard Stop Loss
  • [=== Stop Loss Management ===] InpHardSL_Points = 50 // Fixed Stop Loss in points (0 to disable)
  • [=== Stop Loss Management ===] InpUseTrailingStop = true // Enable Trailing Stop
  • [=== Stop Loss Management ===] InpTrailingStop_Points = 20 // Trailing Stop activation in points of profit
  • [=== Stop Loss Management ===] InpTrailingStep_Points = 5 // Trailing Stop step in points
  • [=== Stop Loss Management ===] InpUseATRStop = false // Use ATR-based stop loss (Placeholder for indicator logic)
  • [=== Stop Loss Management ===] InpATR_SL_Period = 14 // ATR period for SL calculation
  • [=== Stop Loss Management ===] InpATR_SL_Multiplier = 2.0 // ATR multiplier for SL
  • [=== Stop Loss Management ===] InpMoveSLToBreakEven = true // Move SL to breakeven after X points
  • [=== Stop Loss Management ===] InpBreakEvenTriggerPoints = 30 // Points in profit to trigger breakeven move
  • [=== Stop Loss Management ===] InpBreakEvenLockPoints = 2 // Lock X points profit at breakeven (e.g., entry + 2 points)
  • [=== Stop Loss Management ===] InpUseTimeBasedSL = false // Close trade after X minutes
  • [=== Stop Loss Management ===] InpTimeBasedSLMinutes = 120 // Minutes before time-based SL triggers
  • [=== Take Profit & Profit Management ===] InpFixedTP_Points = 100 // Fixed Take Profit in points (0 to disable)
  • [=== Take Profit & Profit Management ===] InpUseProfitLock = false // Enable dynamic profit locking
  • [=== Take Profit & Profit Management ===] InpProfitLockTriggerPoints = 50 // Start locking profit after this many points in profit
  • [=== Take Profit & Profit Management ===] InpProfitLockStepPoints = 20 // Move SL every X points further in profit (after trigger)
  • [=== Take Profit & Profit Management ===] InpProfitLockSecurePoints = 10 // How many points behind current price to lock (e.g., if price moves 20, SL moves to current - 10)
  • [=== Take Profit & Profit Management ===] InpProfitLockOnlyAfterBE = true // Only start profit lock after breakeven is reached
  • [=== Sessions Control Settings ===] InpEnableSessionControl = false // Enable sessions control
  • [=== Sessions Control Settings ===] InpEnableSession1 = true // Enable session 1
  • [=== Sessions Control Settings ===] InpSession1Start = "08:00" // Session 1 start time (HH:MM server time)
  • [=== Sessions Control Settings ===] InpSession1End = "16:00" // Session 1 end time (HH:MM server time)
  • [=== Sessions Control Settings ===] InpEnableSession2 = false // Enable session 2
  • [=== Sessions Control Settings ===] InpSession2Start = "18:00" // Session 2 start time (HH:MM server time)
  • [=== Sessions Control Settings ===] InpSession2End = "22:00" // Session 2 end time (HH:MM server time)
  • [=== Sessions Control Settings ===] InpEnableSession3 = false // Enable session 3
  • [=== Sessions Control Settings ===] InpSession3Start = "00:00" // Session 3 start time (HH:MM server time)
  • [=== Sessions Control Settings ===] InpSession3End = "00:00" // Session 3 end time (HH:MM server time)
  • [=== Sessions Control Settings ===] InpPauseBeforeEndOfSession = true // Stop opening new trades before end of active session
  • [=== Sessions Control Settings ===] InpPauseMinutesBeforeEndOfSession = 30 // Minutes before end of session to pause new trades
  • [=== Sessions Control Settings ===] InpForceCloseAllTradesAtSessionEnd = false // Force close all trades at the end of an active session
  • [=== Sessions Control Settings ===] InpForceCloseMinutesBeforeSessionEnd = 5 // Minutes before session end to force close
  • [=== Sessions Control Settings ===] InpCloseAllTradesAtEndOfDay = false // Close all trades at specific EOD time
  • [=== Sessions Control Settings ===] InpEndOfDayCloseTime = "23:50" // EOD time to close all trades (HH:MM server time)
  • [=== Smart Exit Timing Settings ===] InpEnableSmartExitManagement = false // Enable Smart Exit Management (currently simplified)
  • [=== Smart Exit Timing Settings ===] InpSmartExitStartMinutesBeforeSessionEnd = 60 // When to start "smartly" managing (e.g., no new trades, check for early profitable close)
  • [=== Notifications & Logging ===] InpEnableAlerts = true // Enable Terminal Alerts for important events
  • [=== Notifications & Logging ===] InpEnableEmailNotify = false // Enable Email Notifications
  • [=== Notifications & Logging ===] InpEnablePushNotify = false // Enable Push Notifications
  • [=== Notifications & Logging ===] InpLogTradeEvents = true // Log trade open/close/modify events
  • [=== Notifications & Logging ===] InpLogTickEvents = false // Log detailed tick processing (for debugging, can be verbose)
  • [=== Trading Days Settings ===] InpTradingDays = TRADING_DAYS_MON_TO_FRI // Days to allow trading
  • [=== Trading Days Settings ===] InpTradeMonday = true // Trade on Monday
  • [=== Trading Days Settings ===] InpTradeTuesday = true // Trade on Tuesday
  • [=== Trading Days Settings ===] InpTradeWednesday = true // Trade on Wednesday
  • [=== Trading Days Settings ===] InpTradeThursday = true // Trade on Thursday
  • [=== Trading Days Settings ===] InpTradeFriday = true // Trade on Friday
  • [=== Trading Days Settings ===] InpTradeSaturday = false // Trade on Saturday
  • [=== Trading Days Settings ===] InpTradeSunday = false // Trade on Sunday
  • [=== Donchian & Multi-Indicator Strategy ===] InpEnableDonchian = true // Enable Donchian Channel filter
  • [=== Donchian & Multi-Indicator Strategy ===] InpDonchianPeriod = 20 // Donchian Channel period
  • [=== Donchian & Multi-Indicator Strategy ===] InpDonchianShift = 1 // Donchian shift (bar offset)
  • [=== Donchian & Multi-Indicator Strategy ===] InpEnableATR = true // Enable ATR filter
  • [=== Donchian & Multi-Indicator Strategy ===] InpATRPeriod = 14 // ATR period
  • [=== Donchian & Multi-Indicator Strategy ===] InpATRShift = 1 // ATR shift (bar offset)
  • [=== Donchian & Multi-Indicator Strategy ===] InpATRMultiplier = 2.0 // ATR multiplier for filter/SL
  • [=== Donchian & Multi-Indicator Strategy ===] InpATRFilterSensitivity = 0.1 // Sensitivity for ATR filter in Donchian confirmation
  • [=== Donchian & Multi-Indicator Strategy ===] InpEnableMACD = true // Enable MACD filter
  • [=== Donchian & Multi-Indicator Strategy ===] InpMACDFast = 12 // MACD fast EMA period
  • [=== Donchian & Multi-Indicator Strategy ===] InpMACDSlow = 26 // MACD slow EMA period
  • [=== Donchian & Multi-Indicator Strategy ===] InpMACDSignal = 9 // MACD signal period
  • [=== Donchian & Multi-Indicator Strategy ===] InpMACDShift = 1 // MACD shift (bar offset)
  • [=== Donchian & Multi-Indicator Strategy ===] InpEnableADX = true // Enable ADX filter
  • [=== Donchian & Multi-Indicator Strategy ===] InpADXPeriod = 14 // ADX period
  • [=== Donchian & Multi-Indicator Strategy ===] InpADXShift = 1 // ADX shift (bar offset)
  • [=== Donchian & Multi-Indicator Strategy ===] InpADXMin = 20.0 // Minimum ADX for trend filter
  • [=== Donchian & Multi-Indicator Strategy ===] InpEnableBB = true // Enable Bollinger Bands filter
  • [=== Donchian & Multi-Indicator Strategy ===] InpBBPeriod = 20 // Bollinger Bands period
  • [=== Donchian & Multi-Indicator Strategy ===] InpBBDeviation = 2.0 // Bollinger Bands deviation
  • [=== Donchian & Multi-Indicator Strategy ===] InpBBShift = 1 // BB shift (bar offset)
  • [=== Donchian & Multi-Indicator Strategy ===] InpEnableRSI = true // Enable RSI filter
  • [=== Donchian & Multi-Indicator Strategy ===] InpRSIPeriod = 14 // RSI period
  • [=== Donchian & Multi-Indicator Strategy ===] InpRSIShift = 1 // RSI shift (bar offset)
  • [=== Donchian & Multi-Indicator Strategy ===] InpRSIOverbought = 70.0 // RSI overbought
  • [=== Donchian & Multi-Indicator Strategy ===] InpRSIOversold = 30.0 // RSI oversold
  • [=== Donchian & Multi-Indicator Strategy ===] InpDonchianConfirmations = 3 // Minimum confirmations for Donchian breakout
  • [=== Donchian & Multi-Indicator Strategy ===] InpDonchianStrategy = DONCHIAN_BREAKOUT // Select Donchian logic
  • [=== Donchian & Multi-Indicator Strategy ===] InpMAPeriod = 20 // +------------------------------------------------------------------+
Pseudocode
// Pipsgrowth EX02019 Breakout — Execution Flow (from source analysis)
// Family: Breakout
// Universal Donchian channel breakout EA for XAUUSD M5 with multi-indicator confirmation, comprehensive money management, session control, and smart exit timing. 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
InpNewYorkEndGMT21--- Hardening: Capital Protection ---
InpCapAmount0.0Capital cap amount (0=disabled)
InpLotSize0.01Fixed Lot Size (if LotSizingMethod is LOT_FIXED)
InpMagicNumber22202019Magic Number for orders (unique identifier for this EA)
InpTradeComment"Psgrowth.com Expert_02019"Trade Comment
InpMaxSlippage5Slippage in points (max allowed price deviation)
InpMaxSpreadPoints0Maximum allowed spread in points (0 for no check)
InpOneTradeOnlytrueAllow only one trade at a time (per symbol for this EA)
InpMaxOpenTrades1Maximum allowed open trades at the same time
InpAllowOnlyProfitableAdditionstrueOnly open new trades if all existing (by this EA) are in profit
InpMinProfitPerTradeToAdd5.0Min. profit in points for each existing trade to open new one
InpMaxDrawdownPercent20.0Max drawdown % allowed (0 to disable)
InpMaxDrawdownAmount0.0Max drawdown amount in account currency (0 to disable)
InpMaxTradesPerDay5Max trades per day (0 for unlimited)
InpMinBarsBetweenTrades1Min bars between opening new trades
InpMaxConsecutiveLosingTrades3Pause trading after this many consecutive losses (0 to disable)
InpPauseMinutesAfterLosingStreak60Minutes to pause after reaching losing streak
InpAvoidTradingDuringNewsfalseAvoid trading during news events
InpNewsBufferMinutes30Minutes before and after news to avoid trading
InpAvoidTradingDuringHighImpactNewstrueAvoid high impact news
InpAvoidTradingDuringMediumImpactNewsfalseAvoid medium impact news
InpAvoidTradingDuringLowImpactNewsfalseAvoid low impact news
InpNewsTimeZoneOffsetHours0Offset in hours from UTC (e.g., 2 for UTC+2, -5 for UTC-5)
InpNewsSourceNEWS_SOURCE_FOREX_FACTORYNews source for news filtering
InpLotSizingMethodLOT_FIXEDLot Sizing Method
InpAutoLotBaseTypeBASE_ACCOUNT_EQUITYCapital base for auto lot calculation
InpAutoLot_Increment0.01Lot size to add (e.g., 0.01)
InpAutoLot_CapitalPerIncrement1000For every X amount of capital
InpAutoLot_MaxAllowedLot10.0Maximum lot size allowed by auto calculation
InpAutoLot_MinAllowedLot0.01Minimum lot size allowed by auto calculation
InpOrderTypeORDER_TYPE_BUY_SELLOrder type
InpUseHardSLtrueEnable Hard Stop Loss
InpHardSL_Points50Fixed Stop Loss in points (0 to disable)
InpUseTrailingStoptrueEnable Trailing Stop
InpTrailingStop_Points20Trailing Stop activation in points of profit
InpTrailingStep_Points5Trailing Stop step in points
InpUseATRStopfalseUse ATR-based stop loss (Placeholder for indicator logic)
InpATR_SL_Period14ATR period for SL calculation
InpATR_SL_Multiplier2.0ATR multiplier for SL
InpMoveSLToBreakEventrueMove SL to breakeven after X points
InpBreakEvenTriggerPoints30Points in profit to trigger breakeven move
InpBreakEvenLockPoints2Lock X points profit at breakeven (e.g., entry + 2 points)
InpUseTimeBasedSLfalseClose trade after X minutes
InpTimeBasedSLMinutes120Minutes before time-based SL triggers
InpFixedTP_Points100Fixed Take Profit in points (0 to disable)
InpUseProfitLockfalseEnable dynamic profit locking
InpProfitLockTriggerPoints50Start locking profit after this many points in profit
InpProfitLockStepPoints20Move SL every X points further in profit (after trigger)
InpProfitLockSecurePoints10How many points behind current price to lock (e.g., if price moves 20, SL moves to current - 10)
InpProfitLockOnlyAfterBEtrueOnly start profit lock after breakeven is reached
InpEnableSessionControlfalseEnable sessions control
InpEnableSession1trueEnable session 1
InpSession1Start"08:00"Session 1 start time (HH:MM server time)
InpSession1End"16:00"Session 1 end time (HH:MM server time)
InpEnableSession2falseEnable session 2
InpSession2Start"18:00"Session 2 start time (HH:MM server time)
InpSession2End"22:00"Session 2 end time (HH:MM server time)
InpEnableSession3falseEnable session 3
InpSession3Start"00:00"Session 3 start time (HH:MM server time)
InpSession3End"00:00"Session 3 end time (HH:MM server time)
InpPauseBeforeEndOfSessiontrueStop opening new trades before end of active session
InpPauseMinutesBeforeEndOfSession30Minutes before end of session to pause new trades
InpForceCloseAllTradesAtSessionEndfalseForce close all trades at the end of an active session
InpForceCloseMinutesBeforeSessionEnd5Minutes before session end to force close
InpCloseAllTradesAtEndOfDayfalseClose all trades at specific EOD time
InpEndOfDayCloseTime"23:50"EOD time to close all trades (HH:MM server time)
InpEnableSmartExitManagementfalseEnable Smart Exit Management (currently simplified)
InpSmartExitStartMinutesBeforeSessionEnd60When to start "smartly" managing (e.g., no new trades, check for early profitable close)
InpEnableAlertstrueEnable Terminal Alerts for important events
InpEnableEmailNotifyfalseEnable Email Notifications
InpEnablePushNotifyfalseEnable Push Notifications
InpLogTradeEventstrueLog trade open/close/modify events
InpLogTickEventsfalseLog detailed tick processing (for debugging, can be verbose)
InpTradingDaysTRADING_DAYS_MON_TO_FRIDays to allow trading
InpTradeMondaytrueTrade on Monday
InpTradeTuesdaytrueTrade on Tuesday
InpTradeWednesdaytrueTrade on Wednesday
InpTradeThursdaytrueTrade on Thursday
InpTradeFridaytrueTrade on Friday
InpTradeSaturdayfalseTrade on Saturday
InpTradeSundayfalseTrade on Sunday
InpEnableDonchiantrueEnable Donchian Channel filter
InpDonchianPeriod20Donchian Channel period
InpDonchianShift1Donchian shift (bar offset)
InpEnableATRtrueEnable ATR filter
InpATRPeriod14ATR period
InpATRShift1ATR shift (bar offset)
InpATRMultiplier2.0ATR multiplier for filter/SL
InpATRFilterSensitivity0.1Sensitivity for ATR filter in Donchian confirmation
InpEnableMACDtrueEnable MACD filter
InpMACDFast12MACD fast EMA period
InpMACDSlow26MACD slow EMA period
InpMACDSignal9MACD signal period
InpMACDShift1MACD shift (bar offset)
InpEnableADXtrueEnable ADX filter
InpADXPeriod14ADX period
InpADXShift1ADX shift (bar offset)
InpADXMin20.0Minimum ADX for trend filter
InpEnableBBtrueEnable Bollinger Bands filter
InpBBPeriod20Bollinger Bands period
InpBBDeviation2.0Bollinger Bands deviation
InpBBShift1BB shift (bar offset)
InpEnableRSItrueEnable RSI filter
InpRSIPeriod14RSI period
InpRSIShift1RSI shift (bar offset)
InpRSIOverbought70.0RSI overbought
InpRSIOversold30.0RSI oversold
InpDonchianConfirmations3Minimum confirmations for Donchian breakout
InpDonchianStrategyDONCHIAN_BREAKOUTSelect Donchian logic
InpMAPeriod20+------------------------------------------------------------------+
Source Code (.mq5)Open Source
Pipsgrowth_com_EX02019.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX02019 Donchian_XAUUSD_5M — Donchian channel breakout with multi-indicator confirmation, full 12-layer stack."
#include <Trade/Trade.mqh>
#include <Trade/AccountInfo.mqh>
#include <Trade/SymbolInfo.mqh>

// --- Global Variables ---
CTrade        trade;           // Trade object for order execution
CAccountInfo  account;         // Account info object for balance, equity, etc.
CSymbolInfo   mySymbol;        // Symbol info object for spread, lot size, etc.

// EA State Variables
long          g_last_trade_bar_time = 0;      // Time of last trade (for min bars between trades)
int           g_consecutive_losses = 0;       // Counter for consecutive losing trades
datetime      g_pause_until_time = 0;         // Time until which trading is paused after loss streak
int           g_daily_trades_count = 0;       // Number of trades opened today
datetime      g_last_daily_trades_reset_time = 0; // Last reset time for daily trades count

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

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

// --- Hardening: Capital Protection ---
input group "=== Capital Protection (Hardening) ===";
// InpCapEnabled removed — use InpCapAmount=0 to disable
input double  InpCapAmount            = 0.0;      // Capital cap amount (0=disabled)
input double  InpCapFloor             = 1000.0;
input double  InpMinEquityPct         = 70.0;
input double  InpDailyLossLimitPct    = 5.0;

string g_cached_news_xml = "";
datetime g_last_news_fetch_time = 0;
int g_news_cache_minutes = 10; // Cache for 10 minutes

// --- Input Parameters ---

//--- Trade Settings
input group "=== Trade Settings ==="
input double InpLotSize = 0.01;                   // Fixed Lot Size (if LotSizingMethod is LOT_FIXED)
input ulong  InpMagicNumber = 22202019;             // Magic Number for orders (unique identifier for this EA)
input string InpTradeComment = "Psgrowth.com Expert_02019"; // Trade Comment
input int    InpMaxSlippage = 5;                  // Slippage in points (max allowed price deviation)
input int    InpMaxSpreadPoints = 0;             // Maximum allowed spread in points (0 for no check)
input bool   InpOneTradeOnly = true;              // Allow only one trade at a time (per symbol for this EA)
input int    InpMaxOpenTrades = 1;                // Maximum allowed open trades at the same time

Full source code available on download

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

Tags:ex02019breakoutpipsgrowthfreemt5xauusd

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