P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18082 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18082 AlphaTrend_XAUUSD_5M — EMA+RSI+Donchian trend EA with pyramiding, full 12-layer stack.

Overview

EX18082 AlphaTrend is a single-instrument trend-following EA tuned for XAUUSD on the M5 timeframe. Its signal engine stacks three independent decision layers — fast/slow EMA crossover, a 7-period RSI pullback trigger, and a 30-bar Donchian breakout — on top of an internal Heiken Ashi slope filter that determines which direction is even allowed to fire. The result is a system that can either buy pullbacks inside an established trend or buy the breakout when price escapes a 30-bar range, all from the same code path.

The trend filter is computed in the CalculateHASlope() function. It builds the Heiken Ashi close for the most recent closed bar ((O+H+L+C)/4) and for a bar lookback periods earlier (default 10), then takes the difference in points. The sign of that slope gives trend_dir: positive when HA is rising, negative when falling, and zero on a flat or near-flat slope. The InpMinSlopePoints input is set to 0.0 by default, which effectively lets the slope confirm any non-zero directional bias; raising it tightens the gate. No pullback or breakout entry can fire against trend_dir.

The pullback branch (toggled by InpEnablePullback, true by default) is the most common entry. It requires three things to align on the most recent closed bar: the fast EMA(21) above the slow EMA(55), RSI(7) below the bullish pullback level (default 40), and trend_dir > 0 for a long entry. A short is the mirror: fast below slow, RSI above 60, trend_dir < 0. The RSI pullback levels are deliberately inside the neutral zone, so the system is not buying oversold/overbought extremes — it is buying dips in an uptrend and rips in a downtrend.

The breakout branch (toggled by InpEnableBreakout, true by default) only fires when the pullback branch did not. GetDonchian() uses iHighest/iLowest over the previous 30 bars (skipping bar 0) to return the prior high and low. A close above the prior 30-bar high with trend_dir > 0 is a long entry; the mirror is a short. Because the breakout check runs on the closed bar, the system does not chase the new high; it waits for the next bar to confirm and then enters with an ATR-derived stop and target.

Volatility is gated by ATR(14) and its normalized position inside a 0-1 range, controlled by InpMinAtrNorm (0.15) and InpMaxAtrNorm (0.85). When the current ATR percentile is outside this band, the EA skips entries — the goal is to avoid both compression (whipsaw) and expansion (post-news chaos). A current_atr <= 0 check returns early. Spread is also hard-capped: any tick where the symbol spread exceeds 200 points is dropped on the floor before management runs.

Each new trade is sized by GetLotSize() using a 1% balance risk budget by default, with 0.01 fixed-lot fallback when InpRiskPercent is zero. The stop distance in points is calculated as ATR(14) * InpSlAtrMult (1.4 by default), so the SL is dynamic and breathes with the market. The TP is ATR(14) * InpTpAtrMult (2.2 by default), which works out to roughly a 1:1.57 reward-to-risk ratio. The maximum lot per trade is capped at 10 via InpMaxLotSize, and the result is floored to the symbol's lot step, then clamped to the symbol's min/max.

Safe pyramiding (InpUsePyramid = true by default) allows up to 3 positions on the same symbol with the same magic. The CheckPyramidSafety() function refuses to add if a position in the opposite direction is already open, refuses to add if the current open trade's SL has not yet been pushed into profit by at least InpPyramidMinProfit (100 points), and refuses to add if the count has hit InpMaxPyramidTrades. This is a 'secured profit' pyramid, not a martingale — every additional entry is gated by a position that is already green by a defined amount.

Position management runs on every tick through ManageProfitLock(). When a position is at least InpLockTrigger (300) points in profit, the SL is rewritten to current price ± InpLockDistance (100 points), but only if the new SL is at least InpLockStep (50) points better than the current SL. This produces a stepwise ratchet: the SL never loosens, only tightens, and it advances in 50-point increments once the trade is 300 points up. The TP is left untouched by the modifier.

Time filtering is on by default. IsTradingTime() parses InpStartTime ("08:00") and InpEndTime ("20:00") and only permits entries between those server hours. Outside the window, the EA still manages open positions but blocks new entries; with InpCloseAtEnd, it will force-close the basket at the end time. The new-bar gate (iTime shift 0) prevents multiple entries per candle — a new signal is processed exactly once per M5 bar.

On the trade-execution side, the EA uses CTrade with ORDER_FILLING_FOK and a 10-point slippage tolerance. TryModify_EX18082() retries up to 3 times with a 100ms sleep on requote/timeout; TryClose_EX18082() and TryClosePartial_EX18082() retry up to 3 times with 200ms sleeps on the same transient retcodes. There is no on-chart info panel and no OnTester custom fitness function — the EA relies on the standard MT5 optimization metrics.

In a backtest, the practical operating envelope is: $100 minimum deposit, 0.01 micro-lot, ATR-derived stops that widen in trending conditions and tighten in ranging conditions, a stepwise profit-lock that turns break-even trades into risk-free runners, and a pyramiding cap that prevents basket blow-ups. Run it on M5 XAUUSD, give it a 1% balance risk, and expect a steady but selective trade frequency — most M5 bars will not produce both a pullback and a Donchian breakout on the same candle, so signals will arrive in clusters around London and New York opens rather than as a constant stream.

Strategy Deep Dive

The OnTick handler drops spread > 200 points first, runs ManageProfitLock() on every existing position, then applies the time filter (08:00-20:00 server, on by default). On the new M5 bar it reads one cell of each indicator (EMA21, EMA55, RSI7, ATR14), calculates the HA slope over a 10-bar lookback internally, and lets trend_dir gate the signal. The pullback branch fires when fast EMA is on the right side of slow EMA and RSI(7) has crossed into the 40/60 pullback zone; the breakout branch fires when close is on the right side of the 30-bar Donchian range. The new bar is skipped if the ATR percentile sits outside 0.15-0.85. Sizing is 1% balance risk divided by the ATR-derived SL distance in points, floored to lot step and clamped to InpMaxLotSize. Pyramid adds are gated by CheckPyramidSafety: any open position must have its SL already in profit by at least 100 points, and the count must stay at or below 3. The 300/50/100 profit-lock ratchets the SL forward in 50-point steps once profit crosses 300 points, leaving a 100-point distance to current price.

Entry Signal

Entries are generated on the close of each M5 bar by one of two togglable branches. Pullback (default ON): fast EMA(21) above slow EMA(55), RSI(7) below the bullish level (40) for longs, with HA-slope trend_dir > 0 as the gate. Breakout (default ON): close of the prior bar above the 30-bar Donchian high (or below the low for shorts) with the same HA-slope gate. ATR(14) must be inside the 0.15-0.85 normalized band and spread must be under 200 points.

Exit Signal

Three exit paths: (1) the ATR-scaled TP (2.2x) is hit, (2) the SL is hit, (3) ManageProfitLock ratchets the SL forward in 50-point steps once the trade is 300+ points in profit, leaving a 100-point lock distance, so an extended trend never gives back more than 100 points of open profit. With InpCloseAtEnd, all positions are force-closed at the end of the trading window (20:00 server).

Stop Loss

Stop loss is dynamic: ATR(14) * 1.4 (default 1.4x) computed on each new bar from the indicator handle. The HA slope filter and the ATR-normalized band gate the trade but do not move the SL. The 50-point profit-lock ratchet can tighten the SL up to 100 points behind current price once the trade is 300+ points in profit.

Take Profit

Take profit is ATR(14) * 2.2 (default 2.2x) measured from entry on the new-bar snapshot, giving a fixed reward-to-risk ratio of about 1:1.57 against the 1.4x ATR stop. TP is not trailed — the profit-lock only moves the SL.

Best For

Minimum recommended balance: $100. Best fit is XAUUSD on M5 with a 1% balance risk per trade. Run during the active 08:00-20:00 server window so the HA-slope and Donchian triggers have both London and New York volume behind them; the EA is built for medium-volatility gold regimes and will refuse to enter when ATR normalizes above 0.85 (post-news chaos) or below 0.15 (compression). ECN or low-spread account is preferred so the 200-point spread cap does not start rejecting valid 5-minute setups.

Strategy Logic

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

Family: TrendFollow Magic: 22218082 Version: 2.00

BRIEF: AlphaTrend EA for XAUUSD M5 using EMA fast/slow crossover with RSI pullback/breakout confirmation, Donchian channel, and ATR-normalized volatility filter. Includes Heiken Ashi slope filter, safe pyramiding, profit lock/trailing, and time filter. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CalculateHASlope()
  • GetDonchian()
  • CheckPyramidSafety()
  • ManageProfitLock()
  • GetLotSize()
  • RefreshRates()
  • IsTradingTime()
  • StrToTime()
  • CloseAllPositions()
  • TryClose_EX18082()
  • TryClosePartial_EX18082()
  • TryModify_EX18082()

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (33 total across 8 groups):

  • [=== Identity ===] InpMagicNumber = 22218082 // Magic Number
  • [=== Signal Settings ===] InpEmaFast = 21 // Fast EMA Period
  • [=== Signal Settings ===] InpEmaSlow = 55 // Slow EMA Period
  • [=== Signal Settings ===] InpRsiPeriod = 7 // RSI Period
  • [=== Signal Settings ===] InpRsiBullPB = 40 // RSI Bull Pullback Level
  • [=== Signal Settings ===] InpRsiBearPB = 60 // RSI Bear Pullback Level
  • [=== Signal Settings ===] InpDonchianPeriod = 30 // Donchian Period
  • [=== Signal Settings ===] InpAtrPeriod = 14 // ATR Period
  • [=== Signal Settings ===] InpMinAtrNorm = 0.15 // Min ATR Normalized (0-1)
  • [=== Signal Settings ===] InpMaxAtrNorm = 0.85 // Max ATR Normalized (0-1)
  • [=== Signal Settings ===] InpEnablePullback = true // Enable Pullback Entry
  • [=== Signal Settings ===] InpEnableBreakout = true // Enable Breakout Entry
  • [=== Heiken Ashi Slope Filter ===] InpHaSlopeLookback = 10 // HA Slope Lookback
  • [=== Heiken Ashi Slope Filter ===] InpMinSlopePoints = 0.0 // Minimum Slope (Points)
  • [=== Money Management ===] InpRiskPercent = 1.0 // Risk per trade (% of Balance)
  • [=== Money Management ===] InpFixedLot = 0.01 // Fixed Lot (if Risk=0)
  • [=== Money Management ===] InpMaxLotSize = 10.0 // Max Lot Size per trade
  • [=== Trade Management ===] InpSlAtrMult = 1.4 // Stop Loss ATR Multiplier
  • [=== Trade Management ===] InpTpAtrMult = 2.2 // Take Profit ATR Multiplier
  • [=== Trade Management ===] InpTrailAtrMult = 1.0 // Trailing ATR Multiplier
  • [=== Trade Management ===] InpSlippage = 10 // Max Slippage (Points)
  • [=== Trade Management ===] InpMaxSpread = 200 // Max Spread (Points)
  • [=== Pyramid / Scaling ===] InpUsePyramid = true // Enable Safe Pyramiding
  • [=== Pyramid / Scaling ===] InpMaxPyramidTrades = 3 // Max Open Positions
  • [=== Pyramid / Scaling ===] InpPyramidMinProfit = 100 // Min Secured Profit (Points) for Next Add
  • [=== Profit Lock & Trail ===] InpUseProfitLock = true // Enable Profit Lock / Trailing
  • [=== Profit Lock & Trail ===] InpLockTrigger = 300 // Trigger Distance (Points in Profit)
  • [=== Profit Lock & Trail ===] InpLockStep = 50 // Step to advance SL (Points)
  • [=== Profit Lock & Trail ===] InpLockDistance = 100 // Distance to keep SL from Price (Points)
  • [=== Time Management ===] InpUseTimeFilter = true // Enable Time Filter
  • [=== Time Management ===] InpStartTime = "08:00" // Start Trading Time (Server)
  • [=== Time Management ===] InpEndTime = "20:00" // End Trading Time (Server)
  • [=== Time Management ===] InpCloseAtEnd = false // Close all at end time
Pseudocode
// Pipsgrowth EX18082 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// AlphaTrend EA for XAUUSD M5 using EMA fast/slow crossover with RSI pullback/breakout confirmation, Donchian channel, and ATR-normalized volatility filter. Includes Heiken Ashi slope filter, safe pyramiding, profit lock/trailing, and time filter. 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 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
InpMagicNumber22218082Magic Number
InpEmaFast21Fast EMA Period
InpEmaSlow55Slow EMA Period
InpRsiPeriod7RSI Period
InpRsiBullPB40RSI Bull Pullback Level
InpRsiBearPB60RSI Bear Pullback Level
InpDonchianPeriod30Donchian Period
InpAtrPeriod14ATR Period
InpMinAtrNorm0.15Min ATR Normalized (0-1)
InpMaxAtrNorm0.85Max ATR Normalized (0-1)
InpEnablePullbacktrueEnable Pullback Entry
InpEnableBreakouttrueEnable Breakout Entry
InpHaSlopeLookback10HA Slope Lookback
InpMinSlopePoints0.0Minimum Slope (Points)
InpRiskPercent1.0Risk per trade (% of Balance)
InpFixedLot0.01Fixed Lot (if Risk=0)
InpMaxLotSize10.0Max Lot Size per trade
InpSlAtrMult1.4Stop Loss ATR Multiplier
InpTpAtrMult2.2Take Profit ATR Multiplier
InpTrailAtrMult1.0Trailing ATR Multiplier
InpSlippage10Max Slippage (Points)
InpMaxSpread200Max Spread (Points)
InpUsePyramidtrueEnable Safe Pyramiding
InpMaxPyramidTrades3Max Open Positions
InpPyramidMinProfit100Min Secured Profit (Points) for Next Add
InpUseProfitLocktrueEnable Profit Lock / Trailing
InpLockTrigger300Trigger Distance (Points in Profit)
InpLockStep50Step to advance SL (Points)
InpLockDistance100Distance to keep SL from Price (Points)
InpUseTimeFiltertrueEnable Time Filter
InpStartTime"08:00"Start Trading Time (Server)
InpEndTime"20:00"End Trading Time (Server)
InpCloseAtEndfalseClose all at end time
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18082.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18082 AlphaTrend_XAUUSD_5M — EMA+RSI+Donchian trend EA with pyramiding, full 12-layer stack."

#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>

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

// --- Inputs ---

input group "=== Identity ==="
input ulong    InpMagicNumber       = 22218082;    // Magic Number
input string   InpTradeComment      = "Psgrowth.com Expert_18082";

input group "=== Signal Settings ==="
input int      InpEmaFast           = 21;          // Fast EMA Period
input int      InpEmaSlow           = 55;          // Slow EMA Period
input int      InpRsiPeriod         = 7;           // RSI Period
input int      InpRsiBullPB         = 40;          // RSI Bull Pullback Level
input int      InpRsiBearPB         = 60;          // RSI Bear Pullback Level
input int      InpDonchianPeriod    = 30;          // Donchian Period
input int      InpAtrPeriod         = 14;          // ATR Period
input double   InpMinAtrNorm        = 0.15;        // Min ATR Normalized (0-1)
input double   InpMaxAtrNorm        = 0.85;        // Max ATR Normalized (0-1)
input bool     InpEnablePullback    = true;        // Enable Pullback Entry
input bool     InpEnableBreakout    = true;        // Enable Breakout Entry

input group "=== Heiken Ashi Slope Filter ==="
input int      InpHaSlopeLookback   = 10;          // HA Slope Lookback
input double   InpMinSlopePoints    = 0.0;         // Minimum Slope (Points)

input group "=== Money Management ==="
input double   InpRiskPercent       = 1.0;         // Risk per trade (% of Balance)
input double   InpFixedLot          = 0.01;        // Fixed Lot (if Risk=0)
input double   InpMaxLotSize        = 10.0;        // Max Lot Size per trade

input group "=== Trade Management ==="
input double   InpSlAtrMult         = 1.4;         // Stop Loss ATR Multiplier
input double   InpTpAtrMult         = 2.2;         // Take Profit ATR Multiplier
input double   InpTrailAtrMult      = 1.0;         // Trailing ATR Multiplier
input int      InpSlippage          = 10;          // Max Slippage (Points)
input int      InpMaxSpread         = 200;         // Max Spread (Points)

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

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

Full source code available on download

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

Tags:ex18082trendfollowpipsgrowthfreemt5xauusd

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_EX18082.mq5
File Size17.8 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100