P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18110 TrendFollow

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

Pipsgrowth.com EX18110 Donchian_Channel — Classic Turtle breakout, full 12-layer stack.

Overview

EX18110 is a Donchian Channel breakout EA — the so-called Turtle Trading pattern, reduced to a single pair of horizontal lines and a simple rule: long when a bar's high pierces the highest high of the last 20 bars, short when the low breaks the lowest low. The channel is recomputed every tick by CalculateDonchianChannel(), which walks the previous DonchianPeriod bars (default 20) and stores the result in g_upperChannel and g_lowerChannel. The actual breakout comparison in CheckForSignals() uses bar 1 (the just-closed bar), which prevents repaint and aligns the decision with the close, not the in-progress tick.

The default period of 20 is the original Turtle S1 system. With M5 bars, that is 100 minutes of high/low range — a tight enough window that London morning breakouts (07:00–09:00 GMT) reliably fire, but a wide enough window that intraday noise rarely triggers a false break. The period is fully tunable: drop it to 10 for a faster, more reactive channel, push it to 55 for the slower Turtle S2 system that catches multi-day swings. The bounds check in OnInit() rejects anything below 5 or above 200.

Risk is fixed at 1% of balance per trade by default. CalculateLotSize() computes the right lot from the SL distance: riskAmount = balance * RiskPercent / 100, then lotSize = riskAmount / (slDistance / tickSize * tickValue). NormalizeLot() snaps the result to the broker's volume step and clamps to SYMBOL_VOLUME_MIN / SYMBOL_VOLUME_MAX. Set RiskPercent = 0 and the EA falls back to FixedLotSize = 0.01 for micro-lot testing. The MaxPositions = 1 cap means the EA holds a single position at a time; any breakout in the opposite direction closes the existing position first via CloseAllPositions() and only then opens the new one.

Protective stop and target are ATR-driven by default. The g_atrHandle is created in OnInit() against ATRPeriod = 14 and g_atrValue is refreshed each tick. The SL sits at ATR * ATRMultiplierSL = ATR * 2.0 and the TP at ATR * ATRMultiplierTP = ATR * 3.0 — a 1.5 R:R that assumes the trend leg will outrun the stop. For traders who want fixed-pip stops, UseATRStops = false engages FixedStopLossPips = 50 and FixedTakeProfitPips = 100. The SL/TP are placed server-side at entry so the broker enforces them even if the EA disconnects.

Once in a trade, two protection layers step in. ApplyBreakeven() runs on every new bar; once price moves 20 pips in profit (BreakevenTriggerPips), the SL is ratcheted to entry + 2 pips (BreakevenOffsetPips), with a per-ticket array (g_breakevenTickets[]) tracking which positions have already been moved so the EA does not repeatedly modify the same order. ApplyTrailingStop() then takes over: after 30 pips of profit (TrailingStartPips), the SL rides 15 pips behind price (TrailingStepPips), stepping up only when price moves at least one point beyond the prior SL. The combined effect is a trade that is risk-free after 20 pips, then locked progressively as it runs.

The session and weekend gates are the EA's defensive layer. IsInSession() uses TimeGMT() to test against SessionStartHour = 7 and SessionEndHour = 16 — the London-only window in the default config. With UseSessionFilter = false, the EA trades around the clock. IsWeekendApproaching() returns true on Friday after 20:00 GMT, at which point OnTick() calls CloseAllPositions(0) and returns for the bar — no positions are carried into the weekend gap. IsMaxDailyLossReached() tracks g_dailyProfit against 5% of balance (MaxDailyLossPct); once tripped, the EA stops opening new trades until CheckDayChange() resets the counter at the next GMT midnight. Spread is also gated: IsSpreadOK() blocks entries when the live spread exceeds MaxSpreadPips = 3.

The visuals are unusually rich for an EA in this class. DrawInitialChannel() lays three horizontal lines (upper, middle, lower) on the current bar; DrawChannelHistory() then walks back ChannelBarsToShow = 50 bars and renders each segment of the channel as a hidden OBJ_TREND line, with object reuse so the rendering is fast even after chart refreshes. CreateDashboard() paints a 280x220 dark panel in the top-left showing live upper/lower channel values, current ATR, spread (red when above the cap), session status, signal zone (BUY ZONE / SELL ZONE / NEUTRAL), current position, and lifetime win-rate P/L. UpdateDashboard() is throttled to once every 2 seconds so it does not slow the tick path.

Persistent statistics are written to a binary file in the MQL5/Files directory via SaveStatistics() and reloaded by LoadStatistics() on next OnInit(). The file holds total trades, win count, and total profit — enough to resume a session's win-rate display without a journal import.

The header of the file claims a 12-layer architecture including regime detection, scaling, and OnTester fitness optimization. In practice the implementation covers roughly seven: signal (Donchian breakout), entry (long/short dispatch with reverse-close), confirm (channel break), no-trade (session/spread/daily-loss/weekend gates), capital (max 1 position, 1% risk), risk (ATR-based stops, breakeven, trail), and manage (server-side SL/TP plus bar-by-bar BE/trail ratchets). The remaining layers (regime, scaling, OnTester, news filter, info panel scoring, multi-symbol) are not present in the code — the dashboard exists but is not wired into a strategy layer. Treat the 12-layer claim as a roadmap, not a delivery.

In backtest, expect the EA to fire 1–3 breakouts per session on M5 EURUSD, with an estimated 35–45% win rate at the 1.5 R:R default — the typical Turtle profile. Most exits will be on the trailing stop, not the TP. The trade that pays for the month is usually a 4–6 hour London breakout that runs 80+ pips before reversing; the 5–10 small stops in between are the cost of being in the game.

Strategy Deep Dive

On each tick, CheckDayChange() resets g_dailyProfit at the GMT midnight rollover. IsWeekendApproaching() then force-closes all positions on Friday after 20:00 GMT. IsMaxDailyLossReached() halts the EA when realised session P/L drops below -5% of balance. CalculateDonchianChannel() and CalculateATR() refresh the upper/lower bounds and the 14-period ATR using cached indicator handles. On a new bar, ApplyBreakeven() and ApplyTrailingStop() sweep open positions, then CheckForSignals() compares the just-closed bar to the prior 20-bar channel and calls OpenPosition() on a break. CalculateLotSize() derives the lot from RiskPercent = 1% and the SL distance, snapping the result to the broker's lot step.

Entry Signal

LONG when the previous bar's high exceeds the Donchian upper channel (highest high of the last DonchianPeriod bars, default 20). SHORT when the previous bar's low breaks the lower channel. CheckForSignals() runs on every new bar and only fires when the EA is flat or holding the opposite direction. Entry is gated by session (GMT 7–16 default), spread (≤3 pips), and the daily loss limit (5% of balance).

Exit Signal

Exits in three ways: opposite-channel break triggers CloseAllPositions() then opens a new trade in the other direction; the breakeven-then-trailing ladder ratchets the SL forward (20-pip BE trigger, 30-pip trail start, 15-pip trail step); or the broker-side TP at 3.0× ATR (default 100 pips) closes the trade. Friday after 20:00 GMT and a 5% daily drawdown also force a flat close.

Stop Loss

Default SL is ATR(14) * 2.0 placed server-side at entry, scaled to the broker's minimum stop distance. With UseATRStops = false, the SL falls back to 50 pips fixed. After 20 pips in profit, ApplyBreakeven() moves the SL to entry + 2 pips (tracked per-ticket to avoid re-modification). After 30 pips, ApplyTrailingStop() begins ratcheting 15 pips behind price.

Take Profit

Default TP is ATR(14) * 3.0, a 1.5 R:R against the 2.0× ATR stop, sent server-side at entry. With UseATRStops = false, TP falls back to 100 pips fixed. Most profitable trades close on the trailing-stop ratchet (after breakeven at 20 pips, trail at 30 pips / 15 pips) rather than on the TP itself, which is what gives the system its Turtle-style trend capture.

Best For

EURUSD on M5 or H1, with the default 20-bar channel tuned to the London session (GMT 07:00–16:00). Minimum recommended balance: $100 with the default 0.01-lot fallback, scaling to $500+ when running 1% risk. Best on ECN or low-spread RAW accounts — the 3-pip spread filter assumes sub-pip execution costs. Friday-evening close-out and 5% daily kill-switch make it appropriate for traders who cannot babysit the chart; not appropriate for news-driven breakouts (no event filter) or for users wanting multi-symbol or multi-position scaling.

Strategy Logic

Pipsgrowth EX18110 TrendFollow — Strategy Logic Analysis (from .mq5 source)

Family: TrendFollow Magic: 22218110 Version: 2.00

BRIEF: Classic Donchian Channel (Turtle Trading) breakout EA. LONG when price breaks above N-period highest high, SHORT when price breaks below N-period lowest low. Includes ATR-based SL/TP, trailing stop, breakeven, GMT session filter, weekend close protection, and max daily loss kill switch. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CalculateDonchianChannel()
  • CalculateATR()
  • PipsToPrice()
  • GetSpreadPips()
  • IsSpreadOK()
  • IsInSession()
  • IsWeekendApproaching()
  • CheckDayChange()
  • IsMaxDailyLossReached()
  • DrawInitialChannel()
  • UpdateChannel()
  • DrawChannelHistory()
  • ...and 24 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (31 total across 6 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 (GMT/UTC)
  • [=== Donchian Channel Settings ===] SessionEndHour = 16 // Session End Hour (GMT/UTC)
  • [=== Donchian Channel Settings ===] AvoidWeekends = true // Close before weekend
  • [=== 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 ===] MaxDailyLossPct = 5.0 // Max Daily Loss % (0=off)
  • [=== Risk Management ===] MaxSpreadPips = 3 // Max Spread (pips, 0=off)
  • [=== Stop Loss / Take Profit ===] UseATRStops = true // Use ATR-based SL/TP
  • [=== Stop Loss / Take Profit ===] ATRPeriod = 14 // ATR Period
  • [=== Stop Loss / Take Profit ===] ATRMultiplierSL = 2.0 // ATR Multiplier for SL
  • [=== Stop Loss / Take Profit ===] ATRMultiplierTP = 3.0 // ATR Multiplier for TP
  • [=== Stop Loss / Take Profit ===] FixedStopLossPips = 50 // Fixed SL (pips) if ATR off
  • [=== Stop Loss / Take Profit ===] FixedTakeProfitPips = 100 // Fixed TP (pips) if ATR off
  • [=== Trailing & Breakeven ===] UseTrailingStop = true // Enable Trailing Stop
  • [=== Trailing & Breakeven ===] TrailingStartPips = 30 // Trailing Start (pips)
  • [=== Trailing & Breakeven ===] TrailingStepPips = 15 // Trailing Step (pips)
  • [=== Trailing & Breakeven ===] UseBreakeven = true // Enable Breakeven
  • [=== Trailing & Breakeven ===] BreakevenTriggerPips = 20 // BE Trigger (pips in profit)
  • [=== Trailing & Breakeven ===] BreakevenOffsetPips = 2 // BE Offset (pips above entry)
  • [=== 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
  • [=== Visual Settings ===] ChannelBarsToShow = 50 // Bars to Show (less = faster)
  • [=== EA Settings ===] MagicNumber = 22218110 // Magic number
  • [=== EA Settings ===] Slippage = 10 // Max Slippage (points)
  • [=== EA Settings ===] InpTradeComment = "Psgrowth.com Expert_18110" // +------------------------------------------------------------------+
Pseudocode
// Pipsgrowth EX18110 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Classic Donchian Channel (Turtle Trading) breakout EA. LONG when price breaks above N-period highest high, SHORT when price breaks below N-period lowest low. Includes ATR-based SL/TP, trailing stop, breakeven, GMT session filter, weekend close protection, and max daily loss kill switch. 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:
EURUSD
Optimized Timeframes:
M5H1

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 H4 or Daily chart for best results
  7. 7Configure EMA periods, ADX threshold, and lot size in the dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
DonchianPeriod20Donchian Channel Period
UseSessionFiltertrueUse Session Filter
SessionStartHour7Session Start Hour (GMT/UTC)
SessionEndHour16Session End Hour (GMT/UTC)
AvoidWeekendstrueClose before weekend
RiskPercent1.0Risk Per Trade (%)
FixedLotSize0.01Fixed Lot Size (if Risk=0)
MaxPositions1Max Open Positions
MaxDailyLossPct5.0Max Daily Loss % (0=off)
MaxSpreadPips3Max Spread (pips, 0=off)
UseATRStopstrueUse ATR-based SL/TP
ATRPeriod14ATR Period
ATRMultiplierSL2.0ATR Multiplier for SL
ATRMultiplierTP3.0ATR Multiplier for TP
FixedStopLossPips50Fixed SL (pips) if ATR off
FixedTakeProfitPips100Fixed TP (pips) if ATR off
UseTrailingStoptrueEnable Trailing Stop
TrailingStartPips30Trailing Start (pips)
TrailingStepPips15Trailing Step (pips)
UseBreakeventrueEnable Breakeven
BreakevenTriggerPips20BE Trigger (pips in profit)
BreakevenOffsetPips2BE Offset (pips above entry)
ShowDashboardtrueShow Dashboard
ShowChanneltrueShow Donchian Channel
UpperChannelColorclrLimeUpper Channel Color
LowerChannelColorclrRedLower Channel Color
ChannelWidth2Channel Line Width
ChannelBarsToShow50Bars to Show (less = faster)
MagicNumber22218110Magic number
Slippage10Max Slippage (points)
InpTradeComment"Psgrowth.com Expert_18110"+------------------------------------------------------------------+
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18110.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18110 Donchian_Channel — Classic Turtle breakout, full 12-layer stack."
#include <Trade\Trade.mqh>

//+------------------------------------------------------------------+
//| 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 (GMT/UTC)
input int      SessionEndHour     = 16;           // Session End Hour (GMT/UTC)
input bool     AvoidWeekends      = true;         // Close before weekend

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 double   MaxDailyLossPct    = 5.0;          // Max Daily Loss % (0=off)
input int      MaxSpreadPips      = 3;            // Max Spread (pips, 0=off)

input group "=== Stop Loss / Take Profit ==="
input bool     UseATRStops        = true;         // Use ATR-based SL/TP
input int      ATRPeriod          = 14;           // ATR Period
input double   ATRMultiplierSL    = 2.0;          // ATR Multiplier for SL
input double   ATRMultiplierTP    = 3.0;          // ATR Multiplier for TP
input int      FixedStopLossPips  = 50;           // Fixed SL (pips) if ATR off
input int      FixedTakeProfitPips= 100;          // Fixed TP (pips) if ATR off

input group "=== Trailing & Breakeven ==="
input bool     UseTrailingStop    = true;         // Enable Trailing Stop
input int      TrailingStartPips  = 30;           // Trailing Start (pips)
input int      TrailingStepPips   = 15;           // Trailing Step (pips)
input bool     UseBreakeven       = true;         // Enable Breakeven
input int      BreakevenTriggerPips = 20;         // BE Trigger (pips in profit)
input int      BreakevenOffsetPips  = 2;          // BE Offset (pips above entry)

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 int      ChannelBarsToShow  = 50;           // Bars to Show (less = faster)

input group "=== EA Settings ==="
input int      MagicNumber        = 22218110;                // Magic number
input int      Slippage           = 10;                    // Max Slippage (points)
input string   InpTradeComment    = "Psgrowth.com Expert_18110";

//+------------------------------------------------------------------+
//| GLOBAL VARIABLES                                                  |
//+------------------------------------------------------------------+
double g_upperChannel = 0;
double g_lowerChannel = 0;
double g_middleChannel = 0;
double g_atrValue = 0;

Full source code available on download

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

Tags:ex18110trendfollowpipsgrowthfreemt5eurusd

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_EX18110.mq5
File Size41.8 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5H1
Currency Pairs
EURUSD
Min. Deposit$100