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.
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.
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 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 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.
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
MT5indicators
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 // FastEMAPeriod - [=== Signal Settings ===]
InpEmaSlow= 55 // SlowEMAPeriod - [=== Signal Settings ===]
InpRsiPeriod= 7 //RSIPeriod - [=== Signal Settings ===]
InpRsiBullPB= 40 //RSIBull Pullback Level - [=== Signal Settings ===]
InpRsiBearPB= 60 //RSIBear Pullback Level - [=== Signal Settings ===]
InpDonchianPeriod= 30 // Donchian Period - [=== Signal Settings ===]
InpAtrPeriod= 14 //ATRPeriod - [=== Signal Settings ===]
InpMinAtrNorm=0.15// MinATRNormalized(0-1) - [=== Signal Settings ===]
InpMaxAtrNorm=0.85// MaxATRNormalized(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// MinimumSlope(Points) - [=== Money Management ===]
InpRiskPercent=1.0// Risk per trade (% of Balance) - [=== Money Management ===]
InpFixedLot=0.01// FixedLot(if Risk=0) - [=== Money Management ===]
InpMaxLotSize=10.0// Max Lot Size per trade - [=== Trade Management ===]
InpSlAtrMult=1.4// Stop LossATRMultiplier - [=== Trade Management ===]
InpTpAtrMult=2.2// Take ProfitATRMultiplier - [=== Trade Management ===]
InpTrailAtrMult=1.0// TrailingATRMultiplier - [=== Trade Management ===]
InpSlippage= 10 // MaxSlippage(Points) - [=== Trade Management ===]
InpMaxSpread= 200 // MaxSpread(Points) - [=== Pyramid / Scaling ===]
InpUsePyramid=true// Enable Safe Pyramiding - [=== Pyramid / Scaling ===]
InpMaxPyramidTrades= 3 // Max Open Positions - [=== Pyramid / Scaling ===]
InpPyramidMinProfit= 100 // Min SecuredProfit(Points) for Next Add - [=== Profit Lock & Trail ===]
InpUseProfitLock=true// Enable Profit Lock / Trailing - [=== Profit Lock & Trail ===]
InpLockTrigger= 300 // TriggerDistance(Points in Profit) - [=== Profit Lock & Trail ===]
InpLockStep= 50 // Step to advanceSL(Points) - [=== Profit Lock & Trail ===]
InpLockDistance= 100 // Distance to keep SL fromPrice(Points) - [=== Time Management ===]
InpUseTimeFilter=true// Enable Time Filter - [=== Time Management ===]
InpStartTime= "08:00" // Start TradingTime(Server) - [=== Time Management ===]
InpEndTime= "20:00" // End TradingTime(Server) - [=== Time Management ===]
InpCloseAtEnd=false// Close all at end time
// 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
How to Install This EA on MT5
- 1Download the .mq5 file using the button above
- 2Open MetaTrader 5 on your computer
- 3Click File → Open Data Folder in the top menu
- 4Navigate to MQL5 → Experts and paste the .mq5 file there
- 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
- 6Drag the EA onto an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the dialog
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpMagicNumber | 22218082 | Magic Number |
| InpEmaFast | 21 | Fast EMA Period |
| InpEmaSlow | 55 | Slow EMA Period |
| InpRsiPeriod | 7 | RSI Period |
| InpRsiBullPB | 40 | RSI Bull Pullback Level |
| InpRsiBearPB | 60 | RSI Bear Pullback Level |
| InpDonchianPeriod | 30 | Donchian Period |
| InpAtrPeriod | 14 | ATR Period |
| InpMinAtrNorm | 0.15 | Min ATR Normalized (0-1) |
| InpMaxAtrNorm | 0.85 | Max ATR Normalized (0-1) |
| InpEnablePullback | true | Enable Pullback Entry |
| InpEnableBreakout | true | Enable Breakout Entry |
| InpHaSlopeLookback | 10 | HA Slope Lookback |
| InpMinSlopePoints | 0.0 | Minimum Slope (Points) |
| InpRiskPercent | 1.0 | Risk per trade (% of Balance) |
| InpFixedLot | 0.01 | Fixed Lot (if Risk=0) |
| InpMaxLotSize | 10.0 | Max Lot Size per trade |
| InpSlAtrMult | 1.4 | Stop Loss ATR Multiplier |
| InpTpAtrMult | 2.2 | Take Profit ATR Multiplier |
| InpTrailAtrMult | 1.0 | Trailing ATR Multiplier |
| InpSlippage | 10 | Max Slippage (Points) |
| InpMaxSpread | 200 | Max Spread (Points) |
| InpUsePyramid | true | Enable Safe Pyramiding |
| InpMaxPyramidTrades | 3 | Max Open Positions |
| InpPyramidMinProfit | 100 | Min Secured Profit (Points) for Next Add |
| InpUseProfitLock | true | Enable Profit Lock / Trailing |
| InpLockTrigger | 300 | Trigger Distance (Points in Profit) |
| InpLockStep | 50 | Step to advance SL (Points) |
| InpLockDistance | 100 | Distance to keep SL from Price (Points) |
| InpUseTimeFilter | true | Enable Time Filter |
| InpStartTime | "08:00" | Start Trading Time (Server) |
| InpEndTime | "20:00" | End Trading Time (Server) |
| InpCloseAtEnd | false | Close all at end time |
#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.
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
Markets.com
Exness
IC Markets
Similar Expert Advisors
View All Expert AdvisorsMore Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.