Pipsgrowth EX18028 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX18028 TrendRider XAUUSD 5M — HA+Hull adaptive trend follow, full 12-layer stack.
Overview
TrendRider XAUUSD 5M is built around a deliberate two-vote signal: a Heikin-Ashi closed-bar color vote and an inline Hull moving-average slope vote. Both votes are computed on the most recently closed M5 bar (index 1), and the EA only fires when they agree, when the regime engine tags the market as tradeable, and when the higher-timeframe EMA pair confirms direction. The HA reconstruction is done in EA — CalcHAAt() walks bar-by-bar from a seed ((open+close)/2 for the prior HA_Open, OHLC4 for HA_Close) and propagates (prev_open+prev_close)/2 forward — so there is no dependency on the Heikin-Ashi indicator. The Hull is also hand-rolled: CalcHullSeries() reads two iMA(..., MODE_LWMA) buffers (half period = InpHullPeriod/2 = 25, full = 50), takes 2 * WMA_half - WMA_full, then smooths that difference with a final ManualLWMA() over sqrt(50) ≈ 7 bars. The resulting hull series is queried at index 1 (current closed bar) and index 2 (prior closed bar) — a positive slope (hull1 > hull2) is the bullish vote, a negative slope the bearish vote.
The signal confidence is graded. When both HA and Hull vote the same direction (both +1 or both -1), GetClosedBarSignal() returns signal = ±1, confidence = 80. When only HA has a clean color and the Hull is flat (no slope), confidence drops to 50 — the entry is taken but with a lighter conviction flag. When the two votes disagree the function returns signal = 0 and no trade is considered; this is the primary guard against HA-flip chop with a lagging Hull. The vote result is then handed to ConsiderEntry() which runs the full filter stack before any order is sent.
The regime engine is a six-state classifier that runs on every tick. UpdateRegime() reads ADX(14), ATR(14), and Bollinger Bands(20, 2.0) and computes two rolling percentiles over a 100-bar lookback: the ATR percentile (g_atr_pctl) and the Bollinger-width percentile (bw_pctl). The classification is: ADX >= 40 → REGIME_STRONG_TREND; ADX >= 25 → REGIME_WEAK_TREND; bw_pctl >= 80 or g_atr_pctl >= 75 → REGIME_EXPANDING; bw_pctl <= 20 → REGIME_COMPRESSING; g_atr_pctl <= 25 → REGIME_CHOPPY; otherwise REGIME_RANGE. Only three of these six — STRONG_TREND, WEAK_TREND, EXPANDING — are tradeable per RegimeTradeable(). CHOPPY, RANGE, and COMPRESSING all block new entries, and a flip into any non-tradeable state force-closes open positions via the (j) regime-change exit branch in ManageOpenPositions().
The higher-timeframe confirmation is an EMA(20)/EMA(50) pair on the timeframe set by InpHTFTF (the documented 1–7 range maps to M1..D1; an out-of-range value — including the default 8 — falls through to PERIOD_H1 in MapTimeframeInt()). HTFTrendAgrees() returns true when the HTF fast EMA is on the correct side of the slow EMA relative to the signal. A long signal needs EMA_20_H1 > EMA_50_H1; a short needs the opposite. This filter is what makes the EA's M5 entries ride H1 trends rather than fade them.
Position risk is sized off effective capital — the minimum of account equity and the InpCapitalCapAmount capital-allocation cap (set to 0 by default, which disables the cap and uses the full equity). A 0.5% per-trade risk (InpRiskPercent = 0.5) is translated into lots via CalcLotByRisk(), which uses the symbol's tick value and tick size. A $50 floor (InpCapitalCapFloor) blocks trading when effective capital drops below it, so a small account cannot be ground down by repeated micro-lot losses. The lot is then normalized to the symbol's lot step and capped by LotsMin/LotsMax, and a margin pre-check via OrderCalcMargin confirms free margin covers the order.
The exit model is multi-stage. On entry, a single stop is set at 2.5 × ATR(14) below the ask (longs) or above the bid (shorts) — InpATRMult = 2.5 is also the ATR trailing-stop multiple, so the initial risk distance and the trail distance are identical. The take-profit is 1.5 × risk_distance (the InpMinRR = 1.5 minimum reward:risk filter), giving a 1:1.5 R:R structure. The broker's stops-level is used as a floor if the ATR-derived distance is too small. While the trade is open, ManageOpenPositions() runs on every tick and applies: (a) a one-shot break-even at 1R, raising the stop to entry plus a five-point buffer; (b) a 50% partial close at 1.5R (tracked per ticket via g_partial_done[] so it fires exactly once); (c) an ATR-trailing ratchet that only moves the stop forward, never backwards; (d) a momentum-decay exit where RSI(14) on the closed bar drops below 45 (longs) or rises above 55 (shorts); (e) an opposite-signal exit when the closed-bar vote flips; (f) a 60-bar time exit (5 hours on M5) via InpMaxBarsInTrade = 60; and (g) the regime-change force-close. The seven exit conditions are checked in this fixed order each tick.
Risk guards beyond position sizing include a 3% daily loss limit on effective capital (the EA scans the deal history and trips g_trading_disabled for the rest of the day once realized PnL hits -3%); a cooldown that arms after 3 consecutive losing trades and blocks new entries for 30 minutes (COOLDOWN_LOSSES = 3, COOLDOWN_MIN = 30); a 50-point spread cap (InpMaxSpreadPoints); a configurable session window (InpSession = "08:00-20:00" server time) that blocks entries outside the window; a 120-minute pre-Friday-close flatten (InpFridayCloseMinutes = 120); a 5-minute news blackout around high-impact events pulled from the MQL economic calendar via CalendarValueHistory(); a duplicate-bar guard so the same closed bar cannot trigger two entries; and InpKillSwitch to flatten and stop. InpDryRun defaults to true — the EA logs every would-be trade without sending orders until you flip it off.
The OnTester() function customizes the optimization criterion: (net * profit_factor) / (1 + balance_dd) with a 10-deal floor, which means the strategy tester will reject parameter sets with fewer than 10 closed trades during optimization. The default pyramid setting (InpPyramidMaxLevels = 0) hard-caps scaling to OFF, so this EA is a strict single-position system per magic on the symbol — concurrent trades in the opposite direction are explicitly blocked.
For live deployment: this EA is built for XAUUSD on M5 with a $100 minimum deposit and a MEDIUM risk profile. Use a broker that quotes tight gold spreads (the 50-point filter is generous, but a 15–25 point spread gives the entries headroom) and a server whose clock matches the configured InpSession window — many brokers run GMT+2 or GMT+3 server time, and the 08:00–20:00 default captures the full London–New York overlap. The EA has no martingale, no grid, and no averaging-in. The Hull(50) period is large for M5 and produces a deliberate lag that the regime filter is designed to compensate for; if you drop the period much below 30, expect more whipsaws and lower confidence votes.
Strategy Deep Dive
Every tick, the EA refreshes an inlined Hull(50) built from two LWMA buffers (half-period 25 and full-period 50, differenced and re-smoothed over sqrt(50) ≈ 7 bars via a hand-rolled ManualLWMA()), reconstructs the prior Heikin-Ashi candle from raw OHLC via CalcHAAt(), and grades the two votes into a ±1 signal with confidence 80 on agreement or 50 on HA-only. The signal is then passed through a six-state regime classifier — STRONG_TREND (ADX≥40) / WEAK_TREND (ADX≥25) / EXPANDING (BB-width or ATR percentile ≥80/75) / COMPRESSING / CHOPPY / RANGE — of which only three permit entries, and a higher-timeframe EMA(20)/EMA(50) directional filter, before any order is sized at 0.5% risk off effective capital. After entry, ManageOpenPositions() runs the exit stack in fixed order each tick: regime-change → 60-bar time exit → opposite-signal → RSI(14) momentum decay → 1R break-even → 50% partial at 1.5R → ATR trailing ratchet. The OnTester formula is (net × profit_factor) / (1 + balance_dd) with a 10-deal floor, and InpDryRun = true by default — the EA logs every would-be trade without sending orders until you flip the input off.
Long entries fire when the closed-bar Heikin-Ashi candle is green (HA_Close > HA_Open) AND the inlined Hull(50) slope is positive (hull[1] > hull[2]) — both votes must agree. Shorts require the mirror. The two-vote combination is graded: agreement returns confidence 80, HA-only returns 50. The entry is then gated by a 6-state regime classifier (only STRONG_TREND / WEAK_TREND / EXPANDING pass), an HTF EMA(20)/EMA(50) directional filter, a 1:1.5 R:R feasibility check, a 50-point spread cap, an 08:00–20:00 server-time session window, a 5-minute news blackout, a daily loss limit, a 3-loss / 30-minute cooldown, and a $50 effective-capital floor.
Exits run every tick via ManageOpenPositions() in this fixed order: (1) regime-change force-close if the 6-state classifier flips non-tradeable; (2) 60-bar time exit (5 hours on M5); (3) opposite-signal close when the closed-bar HA/Hull vote flips direction; (4) RSI(14) momentum-decay close — below 45 for longs, above 55 for shorts; (5) one-shot break-even at 1R (stop raised to entry + 5-point buffer); (6) one-shot 50% partial close at 1.5R (tracked per ticket so it never re-fires); (7) ATR(14) × 2.5 forward-only trailing ratchet. The fixed 1:1.5 R:R take-profit is set on entry via InpMinRR.
Stop-loss = 2.5 × ATR(14) from the entry price, floored by the broker's stops-level. ATR(14) is the fixed standard period; the 2.5 multiplier is also the trailing distance so initial risk and trail width are identical. The EA does not use martingale, grid, or averaging-in.
Take-profit = 1.5 × SL_distance for a fixed 1:1.5 R:R structure, set on entry via the InpMinRR = 1.5 feasibility filter. A 50% partial close fires once at 1.5R (tracked per ticket via g_partial_done[]) — the residual 50% then runs under the ATR trailing stop. The fixed 1:1.5 R:R is also the pre-trade gate: an entry is rejected if the TP can't clear 1.5× the SL distance at the current spread.
Built for XAUUSD on M5 with a $100 minimum deposit and MEDIUM risk profile. Use a broker quoting tight gold spreads (15–25 points typical); the 50-point InpMaxSpreadPoints cap gives entry headroom but tighter is better. The default InpSession = "08:00-20:00" server time covers the London–New York overlap on most GMT+2/GMT+3 broker clocks, and the 120-minute pre-Friday-close flatten protects weekend gap exposure. Disable InpDryRun only after you have validated the regime classifier, news-blackout calendar, and HTF EMA filter in the strategy tester against your broker's tick stream.
Strategy Logic
Pipsgrowth EX18028 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218028
Version: 2.00
BRIEF:
Heikin-Ashi closed-bar color + inline Hull-MA slope vote as core trend signal. Entries fire only when the adaptive regime engine (ADX + ATR percentile + Bollinger width) flags a trending/expanding market, HTF EMA filter agrees, and the full no-trade suite passes. Risk sized off EFFECTIVE CAPITAL (capital allocation cap) with daily-loss, cooldown and kill- switch guards. Exits: ATR trailing, break-even, scaled partial TP, momentum-decay, opposite-signal, time and regime-change. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
EffectiveCapital()TodayRealizedPnLForMagic()ConsecutiveLossesToday()CheckDayRollover()UpdateRegime()RegimeTradeable()RegimeName()ManualLWMA()CalcHullSeries()CalcHAAt()GetClosedBarSignal()InSession()- ...and 27 more
INTERNAL CONSTANTS (10 total):
ATR_PERIOD= 14 //ATRperiod (fixed standard)ADX_PERIOD= 14 //ADXperiod (regime)BB_PERIOD= 20 // Bollinger period (regime width)BB_DEV=2.0// Bollinger deviationRSI_PERIOD= 14 //RSIperiod (momentum-decay exit)HTF_FAST= 20 //HTFfastEMAperiodHTF_SLOW= 50 //HTFslowEMAperiodREGIME_LOOKBACK= 100 // bars forATR/BB-width percentileCOOLDOWN_LOSSES= 3 // consecutive losses that trigger cooldownCOOLDOWN_MIN= 30 // cooldown length (minutes)
INPUT PARAMETERS (21 total across 9 groups):
- [=== Identity ===]
InpMagic=22218028// Magic number (isolates thisEA's trades) - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18028" // Order comment - [=== Risk &
Sizing(incl. Capital Allocation Cap) ===]InpRiskPercent=0.5// Risk per trade (% ofEFFECTIVEcapital) - [=== Risk &
Sizing(incl. Capital Allocation Cap) ===]InpCapitalCapAmount=0.0// MaxREALMONEY(equity $, NOT leveraged notional) thisEAcommands - [=== Risk &
Sizing(incl. Capital Allocation Cap) ===]InpCapitalCapFloor=50.0// Min effective capital required to trade ($) - [=== Risk &
Sizing(incl. Capital Allocation Cap) ===]InpDailyLossLimitPercent=3.0// Daily loss limit (% ofEFFECTIVEcapital) - [=== Risk &
Sizing(incl. Capital Allocation Cap) ===]InpMaxOpenTrades= 1 // Max concurrent open trades (this magic) - [=== Risk &
Sizing(incl. Capital Allocation Cap) ===]InpKillSwitch=false// Kill switch — flatten all & stop trading - [=== Signal ===]
InpHullPeriod= 50 // Hull MA period (signal slope vote) - [=== Entry / Confirmation ===]
InpHTFTF= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //HTFtrend timeframe - [=== Entry / Confirmation ===]
InpMinRR=1.5// Minimum reward:risk ratio - [=== No-Trade Filters ===]
InpMaxSpreadPoints= 50 // Max spread (points) - [=== No-Trade Filters ===]
InpNewsBlackoutMin= 5 // News blackout window (minutes before/afterHIGH-impact event) - [=== Trade Management & Exits ===]
InpATRMult=2.5//ATRmultiplier (SL distance & trailing) - [=== Trade Management & Exits ===]
InpBreakEvenR=1.0// Break-even trigger (R-multiple, one-shot) - [=== Trade Management & Exits ===]
InpPartialTP_R=1.5// Partial TP 50% trigger (R-multiple) - [=== Trade Management & Exits ===]
InpMaxBarsInTrade= 60 // Max bars in trade (time-based exit) - [=== Scaling
Policy(defaultOFF) ===]InpPyramidMaxLevels= 0 // Max pyramid levels (0 =OFF, hard-capped) - [=== 8. Session / Timing ===]
InpSession= "08:00-20:00" // Trading session window (server time HH:MM-HH:MM) - [=== 8. Session / Timing ===]
InpFridayCloseMinutes= 120 // Flatten before Friday session close (minutes) - [=== 9. Dry-Run ===]
InpDryRun=true// Dry-run: log signals/exits, send NO orders
// Pipsgrowth EX18028 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Heikin-Ashi closed-bar color + inline Hull-MA slope vote as core trend signal. Entries fire only when the adaptive regime engine (ADX + ATR percentile + Bollinger width) flags a trending/expanding market, HTF EMA filter agrees, and the full no-trade suite passes. Risk sized off EFFECTIVE CAPITAL (capital allocation cap) with daily-loss, cooldown and kill- switch guards. Exits: ATR trailing, break-even, scaled partial TP, momentum-decay, opposite-signal, time and regime-change. 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 |
|---|---|---|
| InpMagic | 22218028 | Magic number (isolates this EA's trades) |
| InpTradeComment | "Psgrowth.com Expert_18028" | Order comment |
| InpRiskPercent | 0.5 | Risk per trade (% of EFFECTIVE capital) |
| InpCapitalCapAmount | 0.0 | Max REAL MONEY (equity $, NOT leveraged notional) this EA commands |
| InpCapitalCapFloor | 50.0 | Min effective capital required to trade ($) |
| InpDailyLossLimitPercent | 3.0 | Daily loss limit (% of EFFECTIVE capital) |
| InpMaxOpenTrades | 1 | Max concurrent open trades (this magic) |
| InpKillSwitch | false | Kill switch — flatten all & stop trading |
| InpHullPeriod | 50 | Hull MA period (signal slope vote) |
| InpHTFTF | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend timeframe |
| InpMinRR | 1.5 | Minimum reward:risk ratio |
| InpMaxSpreadPoints | 50 | Max spread (points) |
| InpNewsBlackoutMin | 5 | News blackout window (minutes before/after HIGH-impact event) |
| InpATRMult | 2.5 | ATR multiplier (SL distance & trailing) |
| InpBreakEvenR | 1.0 | Break-even trigger (R-multiple, one-shot) |
| InpPartialTP_R | 1.5 | Partial TP 50% trigger (R-multiple) |
| InpMaxBarsInTrade | 60 | Max bars in trade (time-based exit) |
| InpPyramidMaxLevels | 0 | Max pyramid levels (0 = OFF, hard-capped) |
| InpSession | "08:00-20:00" | Trading session window (server time HH:MM-HH:MM) |
| InpFridayCloseMinutes | 120 | Flatten before Friday session close (minutes) |
| InpDryRun | true | Dry-run: log signals/exits, send NO orders |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18028 TrendRider XAUUSD 5M — HA+Hull adaptive trend follow, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
//============================ CONSTANTS =============================
#define ATR_PERIOD 14 // ATR period (fixed standard)
#define ADX_PERIOD 14 // ADX period (regime)
#define BB_PERIOD 20 // Bollinger period (regime width)
#define BB_DEV 2.0 // Bollinger deviation
#define RSI_PERIOD 14 // RSI period (momentum-decay exit)
#define HTF_FAST 20 // HTF fast EMA period
#define HTF_SLOW 50 // HTF slow EMA period
#define REGIME_LOOKBACK 100 // bars for ATR/BB-width percentile
#define COOLDOWN_LOSSES 3 // consecutive losses that trigger cooldown
#define COOLDOWN_MIN 30 // cooldown length (minutes)
//============================ INPUTS ================================
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
switch(tf)
{
case 1: return PERIOD_M1;
case 2: return PERIOD_M5;
case 3: return PERIOD_M15;
case 4: return PERIOD_M30;
case 5: return PERIOD_H1;
case 6: return PERIOD_H4;
case 7: return PERIOD_D1;
default: return PERIOD_H1;
}
}
ENUM_APPLIED_PRICE MapAppliedPriceInt(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;
case 6: return PRICE_TYPICAL;
case 7: return PRICE_WEIGHTED;
default: return PRICE_CLOSE;
}
}
ENUM_TIMEFRAMES g_InpHTFTF = PERIOD_H1;
input group "=== Identity ==="
input int InpMagic = 22218028; // Magic number (isolates this EA's trades)
input string InpTradeComment = "Psgrowth.com Expert_18028"; // Order comment
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{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.