Pipsgrowth EX18026 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX18026 XAUUSD TrendRider v2 — KAMA adaptive trend follow, full 12-layer stack.
Overview
Pipsgrowth EX18026 TrendRider is a per-bar trend-following EA that decides direction from a self-built Kaufman Adaptive Moving Average (KAMA), not from a stock MQL indicator. The KAMA is reconstructed inside RefreshKAMA() over a 200-bar history window using the canonical Kaufman recurrence: an efficiency ratio over a 14-bar change-vs-total-path window drives a smoothing constant that morphs between a fast EMA equivalent (fast SC = 2 → α = 2/3) and a slow EMA equivalent (slow SC = 30 → α = 2/31), and the output is squared before being applied to the running KAMA value. The smoothing constant squared (α²) is what gives KAMA its character — it stays almost frozen in chop and snaps toward price in trends. Once the KAMA series is in hand, the EA does not look at the line directly. Instead it computes a per-bar signed score in RefreshKAMA() from three primitives: the KAMA slope across the last 3 bars (SLOPE_BARS=3), the difference between the most recent close and the KAMA on that bar, and the bar-over-bar change in close. Those three primitives are combined into a 4-quadrant scoring table. When the KAMA is rising and the close is above it and the close is also rising, the score is +1.0 × trendStrength × posStrength. When the KAMA is rising and the close is above it but the close is falling, the score drops to +0.5 × trendStrength. The opposite side is symmetric with negative values. The resulting per-bar signal is then clamped to [-1, +1] and stored in g_kamaSignal[].
That per-bar signal is aggregated by AggregateSignal() using a decay-weighted mean across the most recent 3 closed bars (SIGNAL_PERSISTENCE=3, SIGNAL_DECAY=0.8). The weights are 1.0 for the most recent bar, 0.8 for the bar before that, and 0.64 for the bar before that, then scaled into a -100..+100 percentage. A long fires when the aggregated score is at or above +70% and a short when it is at or below -70%; the InpSignalThreshold input exposes that 70% dial. The persistence+decay structure is what separates TrendRider from a raw KAMA crossover: a single noisy bar that just touches +100 cannot cross the threshold on its own, and a one-bar flip in the underlying KAMA direction has to persist for two more closed bars to drive the aggregate across the line. That gives the system natural whipsaw filtering without a separate confirmation indicator.
Regime gating happens before the signal is even consulted. UpdateRegime() runs each new bar and classifies the current state into one of seven buckets based on the ADX(14) reading, the ATR(14) percentile over a 100-bar lookback, and the Bollinger Bands(20, 2) width ratio on the prior closed bar. A Strong Trend needs ADX ≥ 30; a Weak Trend needs ADX ≥ 20. Breakout is reserved for ATR-percentile ≥ 0.85 paired with the Bollinger width growing at least 15% bar-over-bar. Expand is ATR-percentile ≥ 0.70 without the breakout-width growth. Compress is ATR-percentile ≤ 0.25 with a Bollinger-width-to-midline ratio below 0.03. Range is ATR-percentile ≤ 0.40. Everything else is Choppy. Choppy and Range are both hard-blocks inside NoTrade() — NoTrade() returns true and the EA refuses to open anything, with the reason string printed to the log. That is a deliberate design choice for a trend-follower: if the market is not trending, do not trade it.
Confirmation in ConfirmEntry() is a two-factor check. The first factor is the higher-timeframe EMA side: TrendRider builds an HTF EMA(50) and an HTF EMA(200) on whatever timeframe InpHTF resolves to through MapTimeframeInt(). With the default InpHTF=8, the input falls through the switch statement and the EA uses PERIOD_H1 by default — same default-fallback pattern as the rest of this family. A long is only permitted when the HTF EMA(50) is above the HTF EMA(200); a short is only permitted when the fast HTF EMA is below the slow. The second factor is the close of the most recent completed bar against the inlined KAMA on that same bar: a long requires close > KAMA, a short requires close < KAMA. If either factor fails, the entry is skipped and a [CONFIRM] ... line is printed.
The 22 inputs are organised into five groups. IDENTITY holds InpMagic=22218026, the trade comment string, the master enable switch InpEnableTrading=true, InpDryRun=true (default-on paper mode — positions are logged but not sent), and InpKillSwitch=false which forces the EA into close-only mode when flipped. SIGNAL (KAMA) exposes the ER period (14), the fast smoothing constant base (2), the slow smoothing constant base (30), and the threshold (70.0). RISK & SIZING holds the per-trade risk percent (0.5% of effective capital), the per-side max-open-trades (5), the daily loss limit percent (3.0%), the capital cap amount (0 = off, falling back to account equity), and the capital cap floor ($50). EXIT / MANAGE sets the ATR period (14), SL multiplier (2.0), TP multiplier (3.0), and trail multiplier (2.5). REGIME / CONFIRM holds the ADX period (14) and the HTF integer (8 → H1 by default). EXEC holds the spread cap (50 points) and the slippage tolerance (10 points).
Risk and exits are sized off ATR(14) and clamped through ClampMinStop() so SL and TP always respect the broker's stops-level floor plus the 2pt minimum-stop offset. The pre-trade tpDist/slDist ratio is checked against MIN_RR=1.5 — if the geometry cannot deliver at least 1:1.5, the entry is rejected. Position sizing is a clean effective-capital formula in CalcLots(): risk$ = effCap × 0.5%, perLotLoss = (slDist / tickSize) × tickValue, lots = risk$ / perLotLoss, normalised to the broker's volume step and clipped to the volume min/max, then verified against free margin via OrderCalcMargin() before any ticket is sent. ManageExits() runs every tick on each open position. The first thing it does is compute R-multiple from the recovered initial risk distance. If R ≥ 1.0, the stop is ratcheted to the open price (break-even, one-shot). If R ≥ 1.5, 50% of the position is partially closed via TryClosePartial_EX18026() (also one-shot). On every tick, a 2.5×ATR(14) forward-only trail is ratcheted up beyond the open. The trail only ever moves in the profitable direction. A 120-bar time exit (MAX_BARS_IN_TRADE=120) force-closes any position that has been held for 120 closed bars on the current timeframe. An opposite-signal exit closes the position if the aggregated signal crosses to the opposite threshold while the trade is open. A regime-change exit closes the position if the regime flips to Choppy while the trade is open. All three of those exit helpers retry up to three times on requote/timeout/price-off, sleeping 200ms between attempts.
The book-keeping layer is what makes the system safe in continuous use. UpdateRealized() runs every tick and walks the deal history from the start of the current day to compute g_todayRealized and from seven days back to compute g_weekRealized. UpdateLossStreak() walks the last 30 deals in chronological order and counts how many consecutive losses end the current streak, storing the bar time of the most recent loss in g_lastLossBar. NoTrade() checks those four numbers on every new bar: if daily loss ≤ -3% of effective capital, the EA goes quiet for the rest of the day; if weekly loss ≤ -9% of effective capital, the EA goes quiet for the rest of the week; if there was a recent loss and the elapsed bars since the last loss bar are fewer than 5 (COOLDOWN_BARS_AFTER_LOSS=5), the EA skips entries; if the current bar matches g_lastEntryBar, the EA refuses to double-enter on the same bar; if buy or sell count has reached InpMaxOpenTrades=5, the EA refuses additional same-side entries. The session window is hard-coded to 7–21 server time, and Saturday/Sunday is always blocked. Filling mode is auto-detected (FOK → IOC → RETURN). Trade retry on initial send is single-attempt on requote/timeout/price-off with a slippage tolerance of 10 points. The OnTester formula is (netProfit × profitFactor) / (1 + balanceMaxDD) with a 30-trade floor, so the strategy optimiser scores on net profit and profit factor while penalising drawdown.
In backtest the EA behaves like a slow-burn KAMA trend follower: it sits out Choppy and Range regimes almost entirely, lets the regime classifier wait for a clear Breakout or Expand, then lets the decayed aggregate cross the 70% threshold and the HTF EMA side confirm. Once in, the position is held through the 1R break-even ratchet, the 1.5R partial close, and a 2.5×ATR forward trail — so the typical trade either exits quickly on a stop out, gets partially banked at 1.5R, or runs to a 3×ATR TP and a continued trail. The 120-bar time exit and weekly 9% loss cap are the final safety net if the trend fails to materialise. The 22 functions cleanly separate regime, signal, sizing, entry, and management, so any failure surfaces as a tagged log line ([NOTRADE], [CONFIRM], [SIZING], [EXEC], [MANAGE]) rather than as a silent miss.
Strategy Deep Dive
TrendRider rebuilds the Kaufman Adaptive Moving Average directly from raw closes inside RefreshKAMA() rather than attaching the built-in KAMA indicator, computing the efficiency ratio over a 14-bar window and applying the squared smoothing constant between fast SC=2 and slow SC=30. The per-bar signed score combines KAMA slope, price-vs-KAMA position, and bar-over-bar close change into a 4-quadrant table clamped to [-1, +1]. AggregateSignal() then decay-weights the last 3 closed bars at weights 1.0 / 0.8 / 0.64 and scales the result to a -100..+100 percentage, which the threshold (default 70%) compares against. Each new bar UpdateRegime() classifies the market as StrongTrend / WeakTrend / Range / Breakout / Compress / Expand / Choppy from ADX(14), ATR(14) percentile, and Bollinger(20, 2) width; Choppy and Range refuse entries outright. NoTrade() additionally gates on spread, session window (7-21 server time), weekend, capital floor, daily 3% loss, weekly 9% loss, 5-bar cooldown after a loss, single-entry-per-bar, and the per-side 5-trade cap. Sizing follows risk$ = effCap × 0.5% divided by per-lot stop-loss value, with OrderCalcMargin() verifying free margin before any ticket is sent. ManageExits() runs every tick, applying 1R break-even, 1.5R 50% partial, the 2.5×ATR(14) forward trail, opposite-signal close, regime-flip close, and the 120-bar time exit; each helper retries up to three times on requote/timeout/price-off.
TrendRider opens a long when the decayed KAMA aggregate reaches +70% (or above) and the HTF EMA(50) is above the HTF EMA(200) and the most recent closed bar finished above the inlined KAMA. A short opens when the aggregate reaches -70% (or below) with the HTF EMA(50) below the HTF EMA(200) and the close below the KAMA. Choppy and Range regimes are hard-blocked, so entries only fire inside StrongTrend, WeakTrend, Breakout, Expand, or Compress states.
Positions are closed by one of four mechanisms: an opposite-signal close when the aggregate crosses to the negative side, a 120-bar time exit on the current timeframe, a regime-change close if the system flips to Choppy, or a stop/target hit at the broker. While the trade is open, a 2.5×ATR(14) forward-only trail ratchets the stop up beyond the entry once the price moves in favour, and a one-shot 50% partial close fires at 1.5R.
Initial stop is set at 2.0×ATR(14) from the entry, clamped through ClampMinStop() to respect the broker's stops level plus a 2-point minimum offset. The stop is also ratcheted to break-even (entry price) once the trade reaches +1R, and from there a 2.5×ATR(14) forward-only trail takes over. A pre-trade 1:1.5 R:R feasibility check rejects entries that cannot deliver the minimum reward:risk at the current ATR.
Initial take-profit is set at 3.0×ATR(14) from the entry, which works out to a 1:1.5 risk-to-reward ratio against the 2.0×ATR(14) stop. A one-shot 50% partial close at +1.5R banks half the position; the remaining half is then managed by the forward trail toward the 3×ATR TP or until an opposite signal, regime flip, or 120-bar time exit fires.
Best suited to traders running Pipsgrowth EX18026 TrendRider on XAUUSD M5 with a starting balance in the $100–$300 range (the EA's documented minimum is $100, with the capital cap floor at $50 so it stops opening fresh positions below that). The default 7–21 server-time session window is the London-through-New-York overlap, which is when gold trends cleanest, so the broker should be one that quotes tight spreads through those hours — InpMaxSpreadPoints=50 is the hard ceiling. Because the EA runs up to 5 concurrent positions per side and uses a 9% weekly loss limit plus 3% daily loss limit, an ECN or RAW-spread account with low commission and sufficient margin headroom is preferable. Traders who want the signal cleaner should raise InpSignalThreshold above 70, while traders who want more trades should lower it; the EA's regime classifier already filters out the chop, so it is most useful for trend-following portfolios where the user is comfortable sitting out range-bound days.
Strategy Logic
Pipsgrowth EX18026 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218026
Version: 2.00
BRIEF:
KAMA (Kaufman Adaptive MA) slope + price/KAMA regime- adaptive trend signal, aggregated across recent bars with persistence+decay. Entries gated by ADX+ATR-pctile+BB-width regime and HTF-EMA side. ATR-based SL/TP, ATR trailing, break-even, partial TP, capital-allocation cap, daily-loss limit, profit-gated pyramid scaling, full exec layer, OnTester. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
RegimeToString()NormPrice()NormVol()StopsLevelPrice()ClampMinStop()CountMyPositions()SumMyFloatingPnL()RealizedSince()EffectiveCapital()UpdateRegime()RefreshKAMA()AggregateSignal()- ...and 10 more
INTERNAL CONSTANTS (22 total):
KAMA_CALC_DEPTH= 200 //KAMAstabilization lookbackADX_MIN_TREND=20.0//ADXfloor for "trending" regimeBB_PERIOD= 20 // Bollinger period (regime width)BB_DEV=2.0// Bollinger deviationATR_PCTILE_LOOKBACK= 100 //ATRpercentile lookback barsBE_TRIGGER_R=1.0// Break-even trigger (multiples of R)PARTIAL_TP_FRACTION=0.5// Partial TP close fractionPARTIAL_TP_AT_R=1.5// Partial TP trigger (multiples of R)MAX_BARS_IN_TRADE= 120 // Time-based exit (bars)SESSION_START_HOUR= 7 // London open (server time)SESSION_END_HOUR= 21 // NY close (server time)SLOPE_BARS= 3 //KAMAslope lookback barsSIGNAL_PERSISTENCE= 3 // Signal aggregation barsSIGNAL_DECAY=0.8// Signal decay factorKAMA_SIGNAL_WEIGHT=1.0//KAMAweight in aggregator- ...and 7 more
INPUT PARAMETERS (22 total across 6 groups):
- [===
IDENTITY===]InpMagic=22218026// Magic number - [===
IDENTITY===]InpTradeComment= "Psgrowth.com Expert_18026" // Trade comment - [===
IDENTITY===]InpEnableTrading=true// Master enable - [===
IDENTITY===]InpDryRun=true// Dry-run (no live sends) - [===
IDENTITY===]InpKillSwitch=false// Hard kill (close-only) - [===
SIGNAL(KAMA) ===]InpKAMAPeriod= 14 //KAMAER period - [===
SIGNAL(KAMA) ===]InpKAMAFastSC= 2 //KAMAfastSC(EMAequiv) - [===
SIGNAL(KAMA) ===]InpKAMASlowSC= 30 //KAMAslowSC(EMAequiv) - [===
SIGNAL(KAMA) ===]InpSignalThreshold=70.0// Aggregated signal threshold % - [===
RISK&SIZING===]InpRiskPercent=0.5// Risk per trade (% of eff cap) - [===
RISK&SIZING===]InpMaxOpenTrades= 5 // Max concurrent trades (thisEA) - [===
RISK&SIZING===]InpDailyLossLimitPercent=3.0// Daily loss limit (% of eff cap) - [===
RISK&SIZING===]InpCapitalCapAmount=0.0// Capital cap amount ($) - [===
RISK&SIZING===]InpCapitalCapFloor=50.0// Capital cap floor ($) - [===
EXIT/MANAGE===]InpATRPeriod= 14 //ATRperiod - [===
EXIT/MANAGE===]InpATRSLMult=2.0// SL = mult *ATR - [===
EXIT/MANAGE===]InpATRTPMult=3.0// TP = mult *ATR - [===
EXIT/MANAGE===]InpATRTrailMult=2.5// Trail = mult *ATR - [===
REGIME/CONFIRM===]InpADXPeriod= 14 //ADXperiod - [===
REGIME/CONFIRM===]InpHTF= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //HTFtimeframe (side filter) - [===
EXEC===]InpMaxSpreadPoints=50.0// Max spread (points) - [===
EXEC===]InpSlippagePoints= 10 //Slippage(points)
// Pipsgrowth EX18026 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// KAMA (Kaufman Adaptive MA) slope + price/KAMA regime- adaptive trend signal, aggregated across recent bars with persistence+decay. Entries gated by ADX+ATR-pctile+BB-width regime and HTF-EMA side. ATR-based SL/TP, ATR trailing, break-even, partial TP, capital-allocation cap, daily-loss limit, profit-gated pyramid scaling, full exec layer, OnTester. 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 | 22218026 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_18026" | Trade comment |
| InpEnableTrading | true | Master enable |
| InpDryRun | true | Dry-run (no live sends) |
| InpKillSwitch | false | Hard kill (close-only) |
| InpKAMAPeriod | 14 | KAMA ER period |
| InpKAMAFastSC | 2 | KAMA fast SC (EMA equiv) |
| InpKAMASlowSC | 30 | KAMA slow SC (EMA equiv) |
| InpSignalThreshold | 70.0 | Aggregated signal threshold % |
| InpRiskPercent | 0.5 | Risk per trade (% of eff cap) |
| InpMaxOpenTrades | 5 | Max concurrent trades (this EA) |
| InpDailyLossLimitPercent | 3.0 | Daily loss limit (% of eff cap) |
| InpCapitalCapAmount | 0.0 | Capital cap amount ($) |
| InpCapitalCapFloor | 50.0 | Capital cap floor ($) |
| InpATRPeriod | 14 | ATR period |
| InpATRSLMult | 2.0 | SL = mult * ATR |
| InpATRTPMult | 3.0 | TP = mult * ATR |
| InpATRTrailMult | 2.5 | Trail = mult * ATR |
| InpADXPeriod | 14 | ADX period |
| InpHTF | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF timeframe (side filter) |
| InpMaxSpreadPoints | 50.0 | Max spread (points) |
| InpSlippagePoints | 10 | Slippage (points) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18026 XAUUSD TrendRider v2 — KAMA adaptive trend follow, full 12-layer stack."
#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>
#include <Trade/SymbolInfo.mqh>
#include <Trade/AccountInfo.mqh>
#include <Trade/OrderInfo.mqh>
#include <Trade/DealInfo.mqh>
//+------------------------------------------------------------------+
//| NON-INPUT CONSTANTS (tunables moved out of input surface) |
//+------------------------------------------------------------------+
#define KAMA_CALC_DEPTH 200 // KAMA stabilization lookback
#define ADX_MIN_TREND 20.0 // ADX floor for "trending" regime
#define BB_PERIOD 20 // Bollinger period (regime width)
#define BB_DEV 2.0 // Bollinger deviation
#define ATR_PCTILE_LOOKBACK 100 // ATR percentile lookback bars
#define BE_TRIGGER_R 1.0 // Break-even trigger (multiples of R)
#define PARTIAL_TP_FRACTION 0.5 // Partial TP close fraction
#define PARTIAL_TP_AT_R 1.5 // Partial TP trigger (multiples of R)
#define MAX_BARS_IN_TRADE 120 // Time-based exit (bars)
#define SESSION_START_HOUR 7 // London open (server time)
#define SESSION_END_HOUR 21 // NY close (server time)
#define SLOPE_BARS 3 // KAMA slope lookback bars
#define SIGNAL_PERSISTENCE 3 // Signal aggregation bars
#define SIGNAL_DECAY 0.8 // Signal decay factor
#define KAMA_SIGNAL_WEIGHT 1.0 // KAMA weight in aggregator
#define MIN_RR 1.5 // Minimum reward:risk
#define COOLDOWN_BARS_AFTER_LOSS 5 // Cooldown after a loss
#define WEEKLY_LOSS_LIMIT_PCT 9.0 // Weekly loss limit %
#define VOL_SURGE_MULT 1.8 // Volume surge threshold (x avg)
#define HTF_EMA_FAST 50 // HTF EMA fast period
#define HTF_EMA_SLOW 200 // HTF EMA slow period
#define PYRAMID_MAX_LEVELS 3 // Hard cap on pyramid adds (default OFF)
//+------------------------------------------------------------------+
//| INPUTS (22 total — hard cap respected) |
//+------------------------------------------------------------------+
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)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.