P
PipsGrowth
BreakoutOpen Source – Free

Pipsgrowth EX02034 Breakout

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

Pipsgrowth.com EX02034 DonchianExpert — Donchian channel breakout with toggleable ADX/MACD/RSI filters, trailing, break-even, profit lock, pyramid gate.

Overview

Pipsgrowth EX02034 DonchianExpert is a classic turtle-style breakout EA built on a manually-computed Donchian channel. The default channel period is 20 bars on H1 — the same lookback the original 1980s Turtle Trading system used for its short-term breakout, and the same lookback most breakout retests start with. The channel itself is not pulled from a custom indicator: ComputeDonchian() walks the bar buffer from i+1 to period, finds the highest high and the lowest low, and writes the result into two-element arrays dcs_up[] and dcs_low[] (one value for the just-formed bar, one for the bar before it). The Extremes enum gives five ways to define the channel: pure high/low, with open or close blended in, or capped by open. The default HIGH_LOW_CLOSE mode uses the regular high and the lower of low and close — a slight tightening that tends to reduce false breakouts versus raw high/low. The user can pick which timeframe the channel reads from via InpTimeframe (1-9 mapped to M1/M3/M5/M10/M15/M30/H1/H4/D1), letting the EA run an H1 channel on an M5 chart for faster signals or an H4 channel on H1 for slower, larger-range breakouts.

The signal logic in BuySignal() and SellSignal() is one strict test plus up to three optional filters. The core test is close[0] > dcs_up[0] (long) or close[0] < dcs_low[0] (short). The current-bar close is compared against the channel computed from the previous DonchianPeriod bars. With InpSignalOnBarClose=true (the default), the new-bar gate in OnTick() waits for the candle to actually close before evaluating, so the breakout is judged on a confirmed close, not a wick. If you set it false, the EA fires on the first tick that crosses the level — more reactive, but more prone to spike reversals. All three optional filters ship disabled by default, which keeps the EA close to a vanilla Donchian breakout out of the box; you turn them on to tighten entries in choppy regimes.

The three filters are independent. The ADX filter, when enabled, requires adx[0] >= ADX_level (default 20) and that +DI > -DI for longs, -DI > +DI for shorts. The MACD filter requires the main line above the signal line and above zero for longs (mirror for shorts), with default periods 12/26/9. The RSI/speed filter is a four-RSI confluence: four RSIs with periods 7, 12, 18, and 32 are computed on the weighted applied price, and at least two of the four must agree with the trade direction (above the lower trigger for longs, below the upper trigger for shorts). It also requires MathAbs(close[0] - close[Inp_Bars]) / Inp_Bars >= Trend_lev, a bar-speed gate. The four-RSI design avoids the brittleness of a single-period RSI and is a soft proxy for the multi-timeframe momentum alignment the indicator stack is trying to approximate.

Risk management defaults to a 400-point stop and 600-point target — a 1:1.5 risk-reward — measured in raw price points. OpenBuy() subtracts Inp_StopLoss * _Point from the ask for SL and adds Inp_TakeProfit * _Point for TP. The EA carries no ATR-based sizing and no percentage-of-balance sizing; the lot comes from CalcLot() which respects a basic Inp_Lot (0.01 default) or, if Inp_MMode is set to FREEMARGIN or BALANCE, sizes off the account equity or free margin divided by marginInitial * InpLeverage. That leverage input is a sizing knob, not a real leverage request: the EA will compute equity / (margin * InpLeverage) to figure out how many lots to send, so a 1000 leverage setting produces much smaller positions than a 100 setting. The result is clamped to the broker's min/max/step lot constraints via MathFloor(lots/step) * step in TryBuy_EX02034 and TrySell_EX02034. Each order is preceded by an OrderCalcMargin() check; if the required margin exceeds free margin, the order is rejected with a logged message rather than blowing through and triggering a margin call.

Trailing stop is on by default and uses the simple InpTrailingStep (50 points) behind price, but only after the position has moved at least InpTrailingStart (100 points) into profit. The TrailingStop() function only ever ratchets the SL forward — it never widens it — and only ratchets when the new SL is strictly better than the current one. The break-even module is off by default. When you turn it on, ApplyBreakEven() waits for InpBreakEvenTrigger (100 points) of profit, then moves the SL to openPrice + InpBreakEvenOffset * _Point, which puts the stop two points into profit by default. The profit lock module is also off by default and is mutually dependent on break-even: InpProfitLockStep must be strictly less than InpProfitLockIncrement, otherwise OnInit refuses to start the EA. When profit lock is enabled, it ratchets the SL upward in InpProfitLockIncrement (50-point) chunks as the trade moves in your favor, always keeping InpProfitLockStep (20 points) of distance from the most recent profit floor — a stepped trailing that locks incremental gains rather than a smooth trail.

The pyramid gate is the more interesting position-management feature. Default mode is PyramidGate_ProfitAndSL, which means adding to a position is only allowed if every existing position on the symbol is in profit by at least InpProfitGatePoints (10 points) and the SL of each existing position is already secured in profit (above entry for longs, below for shorts). The PyramidGate_Off mode disables the gate entirely, and PyramidGate_ProfitOnly requires profit but ignores whether the SL is locked. Combined with InpMaxOpenPositions=0 (unlimited by default), the EA will scale into a winning breakout as long as existing positions are net positive and trailing has already pulled the SL into profit. That makes it a true breakout trend-following pyramider rather than a single-entry one.

Order execution is wrapped in a 3-retry loop in TryBuy_EX02034 and TrySell_EX02034, sleeping 200ms between attempts on REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED retcodes. Other retcodes (insufficient margin, invalid stops, etc.) break out of the loop and return false, logging the failure with the retcode and description. Modify orders go through TryModify_EX02034 with 100ms sleeps and the same 3-retry ceiling. Inp_Deviation=20 sets the trade object's SetDeviationInPoints for the initial order — the maximum slippage the trade object will tolerate on a market order.

Filling mode is auto-detected in OnInit: the EA reads SYMBOL_FILLING_MODE from the symbol and picks FOK if supported, then IOC, falling back to RETURN. This is the right pattern for ECN/STP/Raw-spread brokers where FOK isn't always allowed. The InpMaxSpread=30 points filter blocks entries when the current spread exceeds the threshold, default 30 points (3.0 pips on a 5-digit broker). Setting it to 0 disables the filter. The InpSignalOnBarClose=true default plus the spread filter plus the optional ADX/MACD/RSI confirmation layers make the EA usable on H1, M5, or anything in between, and the channel can be sourced from a different timeframe than the chart via InpTimeframe, which lets you run, for example, an H4 channel on an M15 chart for medium-frequency breakout trading.

The OnTester() function returns a multi-component fitness score: 30× recovery factor + 15× profit factor + 0.5× min(trades, 200) + 10× sharpe + 25× ROI, then penalties — a 50% haircut if maxDD% > 20, another 70% haircut if maxDD% > 30, and a 50% haircut if balanceDD% > 25. The function returns 0 (and discards the run) if trades < 10, profit ≤ 0, or profit factor < 1.0. There are two bonus multipliers: 1.5× if recovery > 3, profit factor > 2, maxDD% < 15, and trades > 50; 1.3× if ROI > 0.5, profit factor > 1.5, and maxDD% < 20. The composite favors runs that are profitable and low-drawdown, with trade count as a soft tiebreaker — useful for the Strategy Tester genetic optimizer when you want the EA to be punished for over-fitting to a few lucky trades.

Strategy Deep Dive

Donchian channel breakout with a 20-bar lookback (the original Turtle short-term entry) computed manually inside the EA rather than via a custom indicator, so the channel is fully visible in the source. BuySignal and SellSignal compare the current bar close to the channel — close[0] > dcs_up[0] for longs, close[0] < dcs_low[0] for shorts — and exit is by fixed TP plus the optional trailing stop and profit-lock modules. Three optional filters (ADX 10/20, MACD 12/26/9, and a four-RSI confluence with periods 7/12/18/32) all default OFF, so the EA behaves as a vanilla Donchian breakout out of the box and tightens up only when the user enables them. The pyramid gate is the more interesting feature: in its default ProfitAndSL mode, adding to a position is only allowed if existing positions are in profit by at least InpProfitGatePoints (10 points) AND have their SL already secured in profit. That makes it a true breakout trend-following pyramider, not a single-entry strategy.

Entry Signal

Long entry fires when the close of the current bar exceeds the upper Donchian channel — close[0] > dcs_up[0] — with the channel computed from the previous DonchianPeriod (default 20) bars. Short entry is the mirror: close[0] < dcs_low[0]. When InpSignalOnBarClose is true (default), the signal is only evaluated on a closed bar, so the breakout is judged on a confirmed close rather than an intrabar spike.

Exit Signal

Two exit paths are wired: the fixed take-profit at Inp_TakeProfit (600 points by default) plus the optional trailing stop and profit lock. The trailing stop engages after InpTrailingStart (100 points) of profit, then ratchets the SL to InpTrailingStep (50 points) behind price on every tick. The profit-lock module, when enabled, ratchets the SL upward in InpProfitLockIncrement (50-point) steps, keeping InpProfitLockStep (20 points) of buffer behind the locked profit floor.

Stop Loss

Stop-loss defaults to 400 points, set in raw price points via Inp_StopLoss (ask - Inp_StopLoss * _Point for longs, bid + Inp_StopLoss * _Point for shorts). The optional break-even module moves the SL to entry plus InpBreakEvenOffset (2 points) once profit reaches InpBreakEvenTrigger (100 points). The optional profit-lock module then takes over and ratchets the SL in 50-point chunks. The trailing stop also acts as a hard loss cap after InpTrailingStart is reached.

Take Profit

Take-profit defaults to 600 points (1:1.5 RR versus the 400-point SL), set as a fixed price distance from the entry ask/bid. The TP is set once on entry and not trailed upward by the TP line itself; the profit-lock module does the trailing by moving the SL upward instead. There is no partial close at TP1 — the position is held to the full 600-point target or the trailing/profit-lock exit.

Best For

Donchian breakouts on H1 and M5 are the sweet spot for this EA: H1 is the default InpTimeframe, M5 is the fastest practical timeframe. The minimum recommended balance is $100 (matching the EA's minDeposit setting) — the EA will trade from there with the default 0.01 lot and 1000 leverage sizing. ECN or RAW-spread brokers are strongly preferred: the 30-point spread filter assumes low-spread execution, and the FOK filling-mode auto-detection works best on ECN. Best run during London and New York sessions when XAUUSD volatility is highest and channel breaks tend to be real. The default filters are all OFF — turn on ADX (level 20, period 10) for chop filtering, MACD (12/26/9) for direction confirmation, or the four-RSI confluence for the strictest entries.

Strategy Logic

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

Family: Breakout Magic: 22202034 Version: 3.00

BRIEF: Donchian channel breakout EA with individually toggleable ADX/MACD/RSI filters. Trailing, break-even, profit lock, pyramid gate. Breakout above/below channel

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • BuySignal()
  • SellSignal()
  • ComputeDonchian()
  • GetIndValue()
  • GetIndHandle()
  • CountSymbolPositions()
  • PyramidGateAllows()
  • OpenBuy()
  • OpenSell()
  • ModifySLWithRetry()
  • CalcLot()
  • TrailingStop()
  • ...and 5 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (43 total across 10 groups):

  • [=== Identity ===] Inp_EaComment = "Psgrowth.com Expert_02034" // EA comment
  • [=== Identity ===] Inp_MagicNum = 22202034 // Magic
  • [=== Identity ===] Inp_Lot = 0.01 // Basic lot
  • [=== Identity ===] Inp_MMode = LOT // Money Management
  • [=== Identity ===] Inp_Deviation = 20 // Slippage
  • [=== Identity ===] InpLeverage = 1000 // Account leverage (e.g. 100, 500, 1000)
  • [=== Risk Management ===] Inp_StopLoss = 400 // Stop Loss (in points)
  • [=== Risk Management ===] Inp_TakeProfit = 600 // Take Profit (in points)
  • [=== Risk Management ===] InpSignalOnBarClose = true // Evaluate signals only on bar close
  • [=== Risk Management ===] InpMaxSpread = 30 // Max allowed spread in points (0=disable)
  • [=== Trailing Stop ===] InpEnableTrailingStop = true // Enable trailing stop
  • [=== Trailing Stop ===] InpTrailingStep = 50 // Trailing step (in points)
  • [=== Trailing Stop ===] InpTrailingStart = 100 // Minimum profit to start trailing (in points)
  • [=== Break-Even ===] InpEnableBreakEven = false // Move SL to break-even
  • [=== Break-Even ===] InpBreakEvenTrigger = 100 // Profit trigger to activate BE (in points)
  • [=== Break-Even ===] InpBreakEvenOffset = 2 // Offset from entry to lock (in points)
  • [=== Profit Lock ===] InpEnableProfitLock = false // Lock profits in incremental steps
  • [=== Profit Lock ===] InpProfitLockIncrement = 50 // Lock every X points of profit
  • [=== Profit Lock ===] InpProfitLockStep = 20 // Distance behind current price (in points)
  • [=== Additional Trade Controls ===] InpPyramidGateMode = PyramidGate_ProfitAndSL // Pyramid gate mode
  • [=== Additional Trade Controls ===] InpProfitGatePoints = 10.0 // Minimum profit (points) per trade
  • [=== Additional Trade Controls ===] InpMaxOpenPositions = 0 // Maximum open positions (0=unlimited)
  • [=== Donchian Channel ===] InpTimeframe = 7 // Timeframe: 1=M1,2=M3,3=M5,4=M10,5=M15,6=M30,7=H1,8=H4,9=D1
  • [=== Donchian Channel ===] DonchianPeriod = 20 // Channel period
  • [=== Donchian Channel ===] Extremes = HIGH_LOW_CLOSE // Type of extrema
  • [=== ADX Filter ===] InpEnableADXFilter = false // Enable ADX filter
  • [=== ADX Filter ===] ADX_period = 10 // ADX period
  • [=== ADX Filter ===] ADX_level = 20 // ADX level
  • [=== MACD Filter ===] InpEnableMACDFilter = false // Enable MACD filter
  • [=== MACD Filter ===] InpFastEMA = 12 // Fast EMA period
  • [=== MACD Filter ===] InpSlowEMA = 26 // Slow EMA period
  • [=== MACD Filter ===] InpSignalSMA = 9 // Signal SMA period
  • [=== MACD Filter ===] InpAppliedPrice = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
  • [=== Average Speed + RSI Filter ===] InpEnableRSIFilter = false // Enable Average Speed + RSI filter
  • [=== Average Speed + RSI Filter ===] Inp_Bars = 1 // Number of bars
  • [=== Average Speed + RSI Filter ===] Trend_lev = 1 // Trend level
  • [=== Average Speed + RSI Filter ===] RSIperiod1 = 7 // Period of RSI_1
  • [=== Average Speed + RSI Filter ===] RSIperiod2 = 12 // Period of RSI_2
  • [=== Average Speed + RSI Filter ===] RSIperiod3 = 18 // Period of RSI_3
  • [=== Average Speed + RSI Filter ===] RSIperiod4 = 32 // Period of RSI_4
  • [=== Average Speed + RSI Filter ===] Applied_price = 7 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
  • [=== Average Speed + RSI Filter ===] rsiUpperTrigger = 62 // Overbought level
  • [=== Average Speed + RSI Filter ===] rsiLowerTrigger = 38 // Oversold level
Pseudocode
// Pipsgrowth EX02034 Breakout — Execution Flow (from source analysis)
// Family: Breakout
// Donchian channel breakout EA with individually toggleable ADX/MACD/RSI filters. Trailing, break-even, profit lock, pyramid gate. Breakout above/below channel

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:
H1M5

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
Inp_EaComment"Psgrowth.com Expert_02034"EA comment
Inp_MagicNum22202034Magic
Inp_Lot0.01Basic lot
Inp_MModeLOTMoney Management
Inp_Deviation20Slippage
InpLeverage1000Account leverage (e.g. 100, 500, 1000)
Inp_StopLoss400Stop Loss (in points)
Inp_TakeProfit600Take Profit (in points)
InpSignalOnBarClosetrueEvaluate signals only on bar close
InpMaxSpread30Max allowed spread in points (0=disable)
InpEnableTrailingStoptrueEnable trailing stop
InpTrailingStep50Trailing step (in points)
InpTrailingStart100Minimum profit to start trailing (in points)
InpEnableBreakEvenfalseMove SL to break-even
InpBreakEvenTrigger100Profit trigger to activate BE (in points)
InpBreakEvenOffset2Offset from entry to lock (in points)
InpEnableProfitLockfalseLock profits in incremental steps
InpProfitLockIncrement50Lock every X points of profit
InpProfitLockStep20Distance behind current price (in points)
InpPyramidGateModePyramidGate_ProfitAndSLPyramid gate mode
InpProfitGatePoints10.0Minimum profit (points) per trade
InpMaxOpenPositions0Maximum open positions (0=unlimited)
InpTimeframe7Timeframe: 1=M1,2=M3,3=M5,4=M10,5=M15,6=M30,7=H1,8=H4,9=D1
DonchianPeriod20Channel period
ExtremesHIGH_LOW_CLOSEType of extrema
InpEnableADXFilterfalseEnable ADX filter
ADX_period10ADX period
ADX_level20ADX level
InpEnableMACDFilterfalseEnable MACD filter
InpFastEMA12Fast EMA period
InpSlowEMA26Slow EMA period
InpSignalSMA9Signal SMA period
InpAppliedPrice1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
InpEnableRSIFilterfalseEnable Average Speed + RSI filter
Inp_Bars1Number of bars
Trend_lev1Trend level
RSIperiod17Period of RSI_1
RSIperiod212Period of RSI_2
RSIperiod318Period of RSI_3
RSIperiod432Period of RSI_4
Applied_price7Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
rsiUpperTrigger62Overbought level
rsiLowerTrigger38Oversold level
Source Code (.mq5)Open Source
Pipsgrowth_com_EX02034.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "3.00"
#property strict
#property description "Pipsgrowth.com EX02034 DonchianExpert — Donchian channel breakout with toggleable ADX/MACD/RSI filters, trailing, break-even, profit lock, pyramid gate."
#include <Trade/Trade.mqh>

CTrade trade;

//--- enums
enum Applied_Extrem
{
   HIGH_LOW,
   HIGH_LOW_OPEN,
   HIGH_LOW_CLOSE,
   OPEN_HIGH_LOW,
   CLOSE_HIGH_LOW
};

enum MarginMode
{
   LOT,
   FREEMARGIN,
   BALANCE
};

enum PyramidGateMode
{
   PyramidGate_Off=0,        // No pyramid gate
   PyramidGate_ProfitOnly,   // Require existing trades be in profit
   PyramidGate_ProfitAndSL   // Require profit + SL secured in profit
};

//--- Timeframe mapping: 1=M1, 2=M3, 3=M5, 4=M10, 5=M15, 6=M30, 7=H1, 8=H4, 9=D1
ENUM_TIMEFRAMES MapTimeframe(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M3;
      case 3: return PERIOD_M5;
      case 4: return PERIOD_M10;
      case 5: return PERIOD_M15;
      case 6: return PERIOD_M30;
      case 7: return PERIOD_H1;
      case 8: return PERIOD_H4;
      case 9: return PERIOD_D1;
      default: return PERIOD_M5;
   }
}

ENUM_APPLIED_PRICE MapAppliedPrice(int ap)
{
   switch(ap)
   {
      case 1: return PRICE_CLOSE;
      case 2: return PRICE_OPEN;
      case 3: return PRICE_HIGH;
      case 4: return PRICE_LOW;
      case 5: return PRICE_MEDIAN;

Full source code available on download

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

Tags:ex02034breakoutpipsgrowthfreemt5xauusd

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_EX02034.mq5
File Size34.6 KB
Versionv3.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyBreakout
Risk LevelMedium Risk
Timeframes
H1M5
Currency Pairs
XAUUSD
Min. Deposit$100