P
PipsGrowth
BreakoutOpen Source – Free

Pipsgrowth EX02025 Breakout

MT5 Expert Advisor (Open Source) · EURUSD · M5

Pipsgrowth.com EX02025 Donchian_Channel_EA — classic Donchian channel breakout with trailing, full 12-layer stack.

Overview

Pipsgrowth EX02025 is a classic Donchian channel breakout EA built on the original Turtle Trading rules: it goes long when price breaks above the N-bar highest high and short when it breaks below the N-bar lowest low. The implementation is intentionally minimal — there is no regime classifier, no multi-indicator confirmation stack, no higher-timeframe filter, no pyramiding. The edge comes from one well-tested concept executed cleanly on a single 5-minute chart.

The channel is calculated manually inside CalculateDonchianChannel(). For each bar i, the EA scans bars i+1 through i+DonchianPeriod (default 20) using iHigh() and iLow(), takes the running maximum as the upper rail, the running minimum as the lower rail, and the midpoint (upper+lower)/2 as the middle line. All three are stored in series arrays g_upperBuffer, g_lowerBuffer, and g_middleBuffer. Because the breakout is evaluated on the previous completed bar (shift = 1) rather than the still-forming bar, signals are stable and reproducible on backtests.

The breakout trigger is the high or low of the closed bar, not the close. A long signal fires when iHigh(_Symbol, PERIOD_M5, 1) > g_upperBuffer[1]. A short signal fires when iLow(_Symbol, PERIOD_M5, 1) < g_lowerBuffer[1]. The EA reads its current exposure through GetCurrentPositionType() and, if the new signal is the opposite of the held position, it first calls CloseAllPositions() to flatten the existing trade before opening the new one. With MaxPositions set to 1 by default, only one position exists at a time, so the flip is clean and atomic.

Risk management is straightforward but well-parameterized. The default stop is 50 pips, the default target is 100 pips — a fixed 1:2 risk-to-reward ratio. Lots are sized by CalculateLotSize() against RiskPercent (default 1% of balance) using the standard riskAmount / (stopLossPips × pipValue) formula, with pipValue derived from SYMBOL_TRADE_TICK_VALUE × (point / tickSize). When RiskPercent is set to 0, the EA falls back to a flat FixedLotSize of 0.01 lots. NormalizeLot() clamps the result to the broker's min/max/step and rounds to two decimals. A pre-flight OrderCalcMargin() check refuses to send orders that would exceed ACCOUNT_MARGIN_FREE.

The trailing stop is one of the EA's distinguishing features. With UseTrailingStop = true (default), ApplyTrailingStop() runs on every new M5 bar and, for each open position, measures the favorable move against the open price. Once profit reaches TrailingStartPips (30 pips by default), the stop is ratcheted to TrailingStepPips (15 pips) behind current price. For a long, the new stop is bid − 15 pips; for a short, ask + 15 pips. The ratchet only moves forward — it never retreats, and it only modifies when the new level beats the old one by at least one point. The original TP at 100 pips remains in place unless the trailing stop is triggered first, so the EA can either take the full 2R target or lock in open profits depending on how price behaves after the breakout.

The visual layer is the most elaborate part of the codebase. DrawDonchianChannel() rebuilds the upper, lower, and middle lines on every tick using OBJ_TREND segments for the last 100 bars, colored lime (upper) and red (lower) by default with a dotted gray midline of width 1. CreateDashboard() builds a 280×260 panel in the upper-left corner showing symbol, timeframe, channel period, live channel values, session status, current signal, position state, total trades, and cumulative profit. Every label is recreated with CreateLabel() and updated on every tick by UpdateDashboard(), which reads the latest channel buffer values and the current IsInSession() state. OnDeinit() walks the chart's object list and removes any object whose name contains "Donchian_" so the chart is left clean when the EA is removed.

The hardening stack mirrors the other EX02-series EAs. IsSafeToTrade_EX02025() gates every new-bar decision. It first checks IsMarketOpen_EX02025() — the function returns false before Monday 22:00 GMT and after Friday 22:00 GMT, so weekend candles never trigger entries. It then calls InActiveSession_EX02025() which, when InpUseGMTSessions is true (off by default), restricts trading to the union of London (7–16 GMT) and New York (12–21 GMT); the simpler UseSessionFilter + SessionStartHour/SessionEndHour pair (7–16 UTC by default) governs session gating in its place. The news filter calls IsNewsTime_EX02025(), which queries CalendarValueHistory for high-importance events within ±30 minutes and blocks if any are present (default on). Equity-side safety: if InpCapAmount is set, the effective capital is clamped to min(cap, equity) and the EA refuses to trade if the result falls below InpCapFloor (default 1000). A drawdown guard refuses to trade when equity drops below 70% of the initial balance. A daily loss limit of 5% of the initial balance and a g_cooldownUntil timer set by OnTradeTransaction after 5 consecutive losses (4-hour cooldown) provide a third layer of protection.

OnTradeTransaction() is also where the trade counter and P&L accumulators live. It filters to deals whose DEAL_MAGIC matches MagicNumber (22202025) and whose symbol matches the current chart, then adds the deal's profit + swap + commission to g_realizedToday and g_realizedWeek, increments g_tradesToday, and either resets or increments g_consecLosses depending on whether the deal was a loss. The UpdateDailyCounters_EX02025() function rotates these counters at the day and week boundaries.

Execution is hardened against the usual transient errors. OpenPosition(), ClosePosition(), and ModifyPosition() each loop up to three times on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, TRADE_RETCODE_PRICE_OFF, and TRADE_RETCODE_PRICE_CHANGED, refreshing the price after a 200 ms sleep and recomputing SL/TP from the new price. Filling mode is ORDER_FILLING_IOC, slippage tolerance is the Slippage input (10 points default), and the trade comment is the configurable InpTradeComment string "Psgrowth.com Expert_02025".

OnTester() returns profit × profitFactor / maxDD, gated by a minimum of 10 trades. This favors strategies that combine profitability with shallow drawdowns, not raw net profit alone.

The bottom line: EX02025 is a faithful, minimal implementation of the classic Turtle Donchian breakout. If you want the original 20-bar channel with a 1:2 risk-to-reward and a pips-based trailing stop on EURUSD M5, this is it. If you want regime filtering, multi-confirm entries, or partial close behavior, look at the other EX02-series EAs in the family.

Strategy Deep Dive

OnTick() runs the safety gate IsSafeToTrade_EX02025() first, then the optional London session check IsInSession(), then evaluates the breakout on the closed bar (shift = 1). The Donchian channel is recomputed every tick in CalculateDonchianChannel() by walking the past DonchianPeriod bars and storing the upper, lower, and middle rails in series buffers. DrawDonchianChannel() rebuilds the three visual lines and UpdateDashboard() refreshes the live status panel, so the trader sees the channel and signal state change in real time. New-bar logic (lastBarTime guard) ensures signals and trailing-stop checks fire once per M5 bar, not on every tick. OpenPosition() performs the margin pre-check via OrderCalcMargin() and retries up to three times on requote or price-changed errors before giving up.

Entry Signal

The EA buys when the high of the previous M5 bar breaks above the 20-bar Donchian upper channel and sells when the low breaks below the 20-bar lower channel. The channel is calculated manually in CalculateDonchianChannel() as the rolling max of iHigh and rolling min of iLow over DonchianPeriod bars. If a position is held in the opposite direction, the EA closes it first via CloseAllPositions() before opening the new trade. Entry is also gated by IsSafeToTrade_EX02025() which checks market hours, optional session windows, news, and account-level safety conditions.

Exit Signal

Exits are driven by the fixed 100-pip take-profit, the trailing stop ratcheted 15 pips behind price after 30 pips of favorable move, and the opposite-direction breakout signal that flips the position. The TP and SL are set in OpenPosition() and stored on the position. ApplyTrailingStop() runs on each new bar and only moves the stop forward, never back. There is no time-based exit — the position stays open until SL, TP, or a reverse breakout is hit.

Stop Loss

Stop loss is fixed at 50 pips on entry (StopLossPips × 10 × point on 5-digit brokers), set inside OpenPosition() and held on the position. Once the trade moves 30 pips in favor, ApplyTrailingStop() replaces the static stop with a 15-pip trailing stop that ratchets forward. The SL is the static level if the trailing hasn't kicked in yet, otherwise it is the most recent trailing level.

Take Profit

Take profit is fixed at 100 pips on entry — 2× the SL, a hard 1:2 risk-to-reward ratio. The TP is sent to the broker on the open and stays on the position regardless of trailing stop activity. If the trailing stop hits before the 100-pip target, the position closes on the trailing stop instead of the TP.

Best For

EX02025 is built for EURUSD M5 with a MEDIUM risk profile and a $100 minimum deposit. The default 1% risk-per-trade with a 50-pip stop targets roughly 50-pip stop distance, so a $100 account running minimum lot will produce the smallest meaningful trades; $500–$1,000 is the practical comfort zone. The 7–16 UTC default session means London hours, and the optional InpUseGMTSessions flag can add New York 12–21 GMT for the combined London and New York window. A low-spread ECN broker is recommended because the 1:2 risk-to-reward leaves little margin for spread inflation on 50-pip stops.

Strategy Logic

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

Family: Breakout Magic: 22202025 Version: 2.00

BRIEF: Classic Donchian Channel breakout (Turtle Trading) EA with session filter, risk-based sizing, trailing stop, and visual dashboard. WFO-validated strategy

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CalculateDonchianChannel()
  • DrawDonchianChannel()
  • IsInSession()
  • CountPositions()
  • GetCurrentPositionType()
  • CalculateLotSize()
  • NormalizeLot()
  • OpenPosition()
  • CloseAllPositions()
  • ClosePosition()
  • ApplyTrailingStop()
  • ModifyPosition()
  • ...and 13 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (24 total across 8 groups):

  • [=== DONCHIAN CHANNEL SETTINGS ===] DonchianPeriod = 20 // Donchian Channel Period
  • [=== DONCHIAN CHANNEL SETTINGS ===] UseSessionFilter = true // Use Session Filter
  • [=== DONCHIAN CHANNEL SETTINGS ===] SessionStartHour = 7 // Session Start Hour (UTC)
  • [=== DONCHIAN CHANNEL SETTINGS ===] SessionEndHour = 16 // Session End Hour (UTC)
  • [=== RISK MANAGEMENT ===] RiskPercent = 1.0 // Risk Per Trade (%)
  • [=== RISK MANAGEMENT ===] FixedLotSize = 0.01 // Fixed Lot Size (if Risk=0)
  • [=== RISK MANAGEMENT ===] MaxPositions = 1 // Max Open Positions
  • [=== RISK MANAGEMENT ===] StopLossPips = 50 // Stop Loss (pips)
  • [=== RISK MANAGEMENT ===] TakeProfitPips = 100 // Take Profit (pips)
  • [=== TRAILING STOP ===] UseTrailingStop = true // Enable Trailing Stop
  • [=== TRAILING STOP ===] TrailingStartPips = 30 // Trailing Start (pips)
  • [=== TRAILING STOP ===] TrailingStepPips = 15 // Trailing Step (pips)
  • [=== VISUAL SETTINGS ===] ShowDashboard = true // Show Dashboard
  • [=== VISUAL SETTINGS ===] ShowChannel = true // Show Donchian Channel
  • [=== VISUAL SETTINGS ===] UpperChannelColor = clrLime // Upper Channel Color
  • [=== VISUAL SETTINGS ===] LowerChannelColor = clrRed // Lower Channel Color
  • [=== VISUAL SETTINGS ===] ChannelWidth = 2 // Channel Line Width
  • [=== EA SETTINGS ===] MagicNumber = 22202025 // Magic Number
  • [=== EA SETTINGS ===] Slippage = 10 // Max Slippage (points)
  • [=== EA SETTINGS ===] InpTradeComment = "Psgrowth.com Expert_02025" // Trade Comment
  • [=== 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 EX02025 Breakout — Execution Flow (from source analysis)
// Family: Breakout
// Classic Donchian Channel breakout (Turtle Trading) EA with session filter, risk-based sizing, trailing stop, and visual dashboard. WFO-validated strategy

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:
EURUSD
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
DonchianPeriod20Donchian Channel Period
UseSessionFiltertrueUse Session Filter
SessionStartHour7Session Start Hour (UTC)
SessionEndHour16Session End Hour (UTC)
RiskPercent1.0Risk Per Trade (%)
FixedLotSize0.01Fixed Lot Size (if Risk=0)
MaxPositions1Max Open Positions
StopLossPips50Stop Loss (pips)
TakeProfitPips100Take Profit (pips)
UseTrailingStoptrueEnable Trailing Stop
TrailingStartPips30Trailing Start (pips)
TrailingStepPips15Trailing Step (pips)
ShowDashboardtrueShow Dashboard
ShowChanneltrueShow Donchian Channel
UpperChannelColorclrLimeUpper Channel Color
LowerChannelColorclrRedLower Channel Color
ChannelWidth2Channel Line Width
MagicNumber22202025Magic Number
Slippage10Max Slippage (points)
InpTradeComment"Psgrowth.com Expert_02025"Trade Comment
InpNewYorkEndGMT21--- Hardening: Capital Protection ---
InpCapAmount0.0Capital cap amount (0=disabled)
InpDailyLossLimitPct5.0--- Hardening: Trade Safety ---
InpNewsBufferMinutes30+------------------------------------------------------------------+
Source Code (.mq5)Open Source
Pipsgrowth_com_EX02025.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX02025 Donchian_Channel_EA — classic Donchian channel breakout with trailing, full 12-layer stack."

//+------------------------------------------------------------------+
//| INPUT PARAMETERS                                                  |
//+------------------------------------------------------------------+
input group "=== DONCHIAN CHANNEL SETTINGS ==="
input int      DonchianPeriod     = 20;           // Donchian Channel Period
input bool     UseSessionFilter   = true;         // Use Session Filter
input int      SessionStartHour   = 7;            // Session Start Hour (UTC)
input int      SessionEndHour     = 16;           // Session End Hour (UTC)

input group "=== RISK MANAGEMENT ==="
input double   RiskPercent        = 1.0;          // Risk Per Trade (%)
input double   FixedLotSize       = 0.01;         // Fixed Lot Size (if Risk=0)
input int      MaxPositions       = 1;            // Max Open Positions
input int      StopLossPips       = 50;           // Stop Loss (pips)
input int      TakeProfitPips     = 100;          // Take Profit (pips)

input group "=== TRAILING STOP ==="
input bool     UseTrailingStop    = true;         // Enable Trailing Stop
input int      TrailingStartPips  = 30;           // Trailing Start (pips)
input int      TrailingStepPips   = 15;           // Trailing Step (pips)

input group "=== VISUAL SETTINGS ==="
input bool     ShowDashboard      = true;         // Show Dashboard
input bool     ShowChannel        = true;         // Show Donchian Channel
input color    UpperChannelColor  = clrLime;      // Upper Channel Color
input color    LowerChannelColor  = clrRed;       // Lower Channel Color
input int      ChannelWidth       = 2;            // Channel Line Width

input group "=== EA SETTINGS ==="
input int      MagicNumber        = 22202025;     // Magic Number
input int      Slippage           = 10;           // Max Slippage (points)
input string   InpTradeComment    = "Psgrowth.com Expert_02025"; // Trade Comment

//+------------------------------------------------------------------+
//| GLOBAL VARIABLES                                                  |
//+------------------------------------------------------------------+
int g_donchianHandle;
double g_upperBuffer[];
double g_lowerBuffer[];
double g_middleBuffer[];

// Dashboard label names
string g_dashLabels[];
int g_dashLabelCount = 0;

// Statistics
int g_totalTrades = 0;
int g_winTrades = 0;
double g_totalProfit = 0;

// Channel object names
string g_upperLineName = "DonchianUpper";
string g_lowerLineName = "DonchianLower";
string g_middleLineName = "DonchianMiddle";

Full source code available on download

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

Tags:ex02025breakoutpipsgrowthfreemt5eurusd

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