P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18025 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18025 XAUUSD TrendRider — KAMA adaptive trend follow, full 12-layer stack.

Overview

Pipsgrowth EX18025 TrendRider is a single-pair gold EA that trades a self-built Kaufman Adaptive Moving Average. There is no Pine-port, no foreign indicator buffer, no copy-pasted MT4 port: the RefreshKAMA() function in the .mq5 reconstructs the KAMA series from raw close prices on every new bar, with an Efficiency Ratio lookback of InpKAMAPeriod = 14 bars, a fast smoothing constant of 2 (≈ EMA-1) and a slow smoothing constant of 30 (≈ EMA-29). The Efficiency Ratio — change over 14 bars divided by the sum of 14 one-bar absolute changes — sets the smoothing coefficient at every step, so the curve whipsaws tightly in directional runs and flattens into a near-horizontal line in chop. That adaptive behaviour is the entire reason the EA exists: a fixed EMA lags the wrong way in ranging gold, and a fixed fast EMA chops the account in ranging gold, and KAMA is the textbook compromise.

From that KAMA series the engine derives a per-bar signal in RefreshKAMA() itself, not in a separate function. For each of the last SIGNAL_PERSISTENCE + 1 = 4 closed bars it computes three numbers: kSlope (KAMA minus KAMA three bars back, set by #define SLOPE_BARS 3), pricePos (close minus KAMA) and priceChg (bar-over-bar close change). These feed a four-quadrant lookup that returns a signed score from -1.0 to +1.0 — full credit when slope, price-side and bar-change all agree, partial credit when only two of the three align, and a small counter-signal otherwise. The scores are clamped to [-1, +1] and stored in g_kamaSignal[].

AggregateSignal() then takes a decay-weighted mean across the last 3 bars (SIGNAL_PERSISTENCE = 3, SIGNAL_DECAY = 0.8), giving the most recent bar a weight of 1.0, the bar before 0.8, and the bar before that 0.64. The result is scaled to -100..+100, and TryEntry() only fires when that aggregate clears InpSignalThreshold = 70 in the bull direction or -70 in the bear direction. The 70% bar is a deliberate filter: a single KAMA tick is not enough, two are not enough, three aligned bars in a row with the most recent weighted most heavily are what the EA treats as a real move.

No signal can fire unless the regime classifier says the market is tradeable. UpdateRegime() reads ADX(14), ATR(14) and Bollinger Bands(20, 2.0) on the current chart and maps them to one of seven states. ADX above 30 puts the chart in REGIME_STRONG_TREND; ADX between 20 and 30 yields REGIME_WEAK_TREND; ADX below 20 with high ATR-percentile and rising BB width gives REGIME_BREAKOUT; high ATR-percentile alone gives REGIME_EXPAND; tight BB and low ATR-percentile gives REGIME_COMPRESS; low ATR-percentile with normal width yields REGIME_RANGE; and the catch-all is REGIME_CHOPPY. The NoTrade() gate then hard-blocks entries in REGIME_CHOPPY and REGIME_RANGE — a trend-rider that has no business in a sideways tape. REGIME_CHOPPY is also a per-tick exit trigger inside ManageExits(): as soon as the regime classifier flips the chart to choppy, every open position is force-closed. That is the EA's own way of saying "the conditions I was designed for no longer hold."

Confirmation is a separate two-factor gate. ConfirmEntry() reads the higher-timeframe EMA(50) and EMA(200) — InpHTF is set to 8, which is outside the documented 1–7 range, so MapTimeframeInt() falls through to its default: branch and resolves to PERIOD_H1. (Anyone reading the source expecting W1 or MN will get the standard H1 instead.) The function refuses a long if the H1 fast EMA is below the slow EMA, and refuses a short in the mirror case. The second factor is the closed bar's close against KAMA: a buy needs the close to be above KAMA(1), a sell needs it below. Both factors must clear before TryEntry() will size a position.

The size of every position is set by CalcLots(), which divides the dollar risk budget (0.5% of effective capital by default, via InpRiskPercent) by the per-lot loss implied by the broker's tick size and tick value at the ATR-based stop distance. Two pre-send safety checks sit underneath: OrderCalcMargin confirms the broker will accept the order, and the result is compared against AccountInfo::FreeMargin(). A CapitalCapAmount input lets a deployer cap the equity the EA treats as its own (set to 0.0 by default, which means it trades the full account balance), with a $50 floor below which new entries are blocked.

Stop and target are ATR-based and ATR-only. InpATRSLMult = 2.0 puts the stop two ATR(14) points away from the entry; InpATRTPMult = 3.0 puts the target three ATR(14) points away, which is exactly 1:1.5 reward-to-risk. The pre-trade gate refuses to send an order if that ratio would fall below MIN_RR = 1.5, so a sudden volatility crush cannot silently degrade the structure. Once in a trade, ManageExits() runs four parallel ratchets: (1) an ATR trail at InpATRTrailMult = 2.5, which only ratchets forward and only past the entry price — the stop never goes backwards and never goes into the loss zone; (2) a break-even at 1R that pulls the stop to entry plus a tiny offset; (3) a 50% partial close at 1.5R; and (4) a hard time exit after MAX_BARS_IN_TRADE = 120 bars. Opposite-signal flips also force-close: a long is closed the moment the aggregated KAMA signal crosses -70, and vice versa.

Risk scaffolding sits around all of this. InpDailyLossLimitPercent = 3.0 blocks the EA from opening new positions once realized PnL for the day is below -3% of effective capital. A weekly cap of WEEKLY_LOSS_LIMIT_PCT = 9.0% does the same on a rolling seven-day window. A counter inside UpdateLossStreak() walks the deal history; once it sees a losing close, it forces a COOLDOWN_BARS_AFTER_LOSS = 5 bar pause before the next entry. The session filter is hard-coded via #define SESSION_START_HOUR 7 and #define SESSION_END_HOUR 21 — London open through NY close in server time — and NoTrade() also refuses to trade on Saturday and Sunday. A spread gate rejects entries when the current spread exceeds InpMaxSpreadPoints = 50 points. The InpKillSwitch input flips the EA into a close-only mode that force-closes every open position and refuses to open new ones until toggled back. InpDryRun = true by default prints every would-be fill to the journal but does not actually send orders, which is the safe way to validate the EA on a fresh broker.

Filling mode is auto-detected from the symbol: FOK if the broker advertises it, otherwise IOC, otherwise the legacy RETURN. Every send goes through a 3-attempt retry loop in TryClose_EX18025(), TryClosePartial_EX18025() and TryModify_EX18025(), with a 200 ms sleep on requote, timeout, price-changed and price-off responses. The MT5 Strategy Tester's optimization criterion is custom: OnTester() returns (netProfit * profitFactor) / (1.0 + maxBalanceDrawdown), gated to a 30-trade minimum and a positive drawdown denominator — meaning the optimizer prefers a smooth equity curve over a high-return one with deep drawdowns.

EX18025 is, in practical terms, a meta-trend-follower. The KAMA is the trend filter, the persistence-and-decay aggregator is the patience filter, the regime classifier is the volatility filter, the H1 EMA pair is the structural filter, and the ATR-based stops plus BE-plus-partial-plus-trail is the trade-management filter. Five independent reasons all have to agree before a ticket goes to the broker, and any one of them reverting kills the trade. That is the design choice that separates this EA from a simple moving-average cross: a single signal can be wrong, but five filters agreeing and then disagreeing is rare, and the EA is built around that rarity.

Strategy Deep Dive

On every new M5 bar, the EA rebuilds a 200-bar KAMA series in-line from raw closes, using a 14-bar Efficiency Ratio and smoothing constants 2/30, then derives a per-bar signed score from KAMA slope, price-vs-KAMA position and bar-over-bar change. The last 3 of those scores are decay-weighted (factors 1.0, 0.8, 0.64) and scaled to -100..+100; only an aggregate that crosses +70 or -70 is even candidate for entry. The regime classifier then maps ADX(14) + ATR-percentile + BB(20,2) width into one of seven states, and CHOPPY or RANGE are hard-blocked by NoTrade(). Confirmation demands H1 EMA(50) above EMA(200) for longs (and the mirror for shorts) plus the closed-bar close on the correct side of KAMA(1). Sizing is 0.5% of effective capital at the ATR distance, with OrderCalcMargin and a free-margin check before send; the trade is then run through a 2.5x ATR forward-only trail, a 1R break-even, a 50% partial at 1.5R, a 120-bar time exit, an opposite-signal exit, and a regime-CHOPPY exit. Per-tick housekeeping updates realised PnL, the consecutive-loss counter and the cooldown timer.

Entry Signal

Long entries require the decay-weighted KAMA aggregate (3 bars, decay 0.8) to clear +70 while H1 EMA(50) is above H1 EMA(200) and the closed-bar close is above KAMA(1). Shorts are the mirror: aggregate below -70 with H1 EMA(50) below H1 EMA(200) and the close below KAMA(1). ADX must also leave the chart out of CHOPPY and RANGE regimes. The full per-tick decision lives in TryEntry().

Exit Signal

Three exit paths run in parallel. (1) The 2.5x ATR trail ratchets the stop forward only, never backwards, and only past entry. (2) Break-even fires at 1R and 50% partial close at 1.5R. (3) The hard time exit closes any position still open after 120 bars. An opposite-signal cross of the KAMA aggregate forces an immediate close, and REGIME_CHOPPY triggers a force-close on every open position.

Stop Loss

Per-trade stop is exactly InpATRSLMult = 2.0 × ATR(14) on the closed bar before entry, with a pre-trade gate refusing to send if the implied reward-to-risk would fall below 1.5. The 2.5x ATR trail and a 1R break-even ratchet provide ongoing protection after the trade is live. A daily 3% loss cap and a 9% weekly loss cap on effective capital provide the equity-level circuit-breakers.

Take Profit

Initial take-profit is InpATRTPMult = 3.0 × ATR(14), giving a 1:1.5 reward-to-risk paired with the 2.0x ATR stop. Targets are also realised progressively: 50% of the position is closed at 1.5R as a partial TP, and the remainder is left to the 2.5x ATR trail, with a 120-bar hard time exit if the move stalls.

Best For

A single-chart gold bot calibrated for $100 minimum and the M5 timeframe, so it suits small prop-style accounts and retail gold traders who can keep the chart up during the London-New York overlap. The 50-point spread ceiling and the 7-21 server-time window mean a low-spread, fast-execution broker is mandatory — IC Markets, Pepperstone, Exness or similar ECN/Raw. With InpMaxOpenTrades = 5 per side and a 0.5% risk budget, a $1,000–$5,000 account runs the strategy as designed; a $100 account trades it as the absolute minimum and should expect small absolute swings. Test thoroughly in MT5 Strategy Tester before going live.

Strategy Logic

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

Family: TrendFollow Magic: 22218025 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 MT5 indicators

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 // KAMA stabilization lookback
  • ADX_MIN_TREND = 20.0 // ADX floor for "trending" regime
  • BB_PERIOD = 20 // Bollinger period (regime width)
  • BB_DEV = 2.0 // Bollinger deviation
  • ATR_PCTILE_LOOKBACK = 100 // ATR percentile lookback bars
  • BE_TRIGGER_R = 1.0 // Break-even trigger (multiples of R)
  • PARTIAL_TP_FRACTION = 0.5 // Partial TP close fraction
  • PARTIAL_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 // KAMA slope lookback bars
  • SIGNAL_PERSISTENCE = 3 // Signal aggregation bars
  • SIGNAL_DECAY = 0.8 // Signal decay factor
  • KAMA_SIGNAL_WEIGHT = 1.0 // KAMA weight in aggregator
  • ...and 7 more

INPUT PARAMETERS (22 total across 6 groups):

  • [=== IDENTITY ===] InpMagic = 22218025 // Magic number
  • [=== IDENTITY ===] InpTradeComment = "Psgrowth.com Expert_18025" // 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 // KAMA ER period
  • [=== SIGNAL (KAMA) ===] InpKAMAFastSC = 2 // KAMA fast SC (EMA equiv)
  • [=== SIGNAL (KAMA) ===] InpKAMASlowSC = 30 // KAMA slow SC (EMA equiv)
  • [=== 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 (this EA)
  • [=== 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 // ATR period
  • [=== 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 // ADX period
  • [=== REGIME / CONFIRM ===] InpHTF = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF timeframe (side filter)
  • [=== EXEC ===] InpMaxSpreadPoints = 50.0 // Max spread (points)
  • [=== EXEC ===] InpSlippagePoints = 10 // Slippage (points)
Pseudocode
// Pipsgrowth EX18025 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

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
InpMagic22218025Magic number
InpTradeComment"Psgrowth.com Expert_18025"Trade comment
InpEnableTradingtrueMaster enable
InpDryRuntrueDry-run (no live sends)
InpKillSwitchfalseHard kill (close-only)
InpKAMAPeriod14KAMA ER period
InpKAMAFastSC2KAMA fast SC (EMA equiv)
InpKAMASlowSC30KAMA slow SC (EMA equiv)
InpSignalThreshold70.0Aggregated signal threshold %
InpRiskPercent0.5Risk per trade (% of eff cap)
InpMaxOpenTrades5Max concurrent trades (this EA)
InpDailyLossLimitPercent3.0Daily loss limit (% of eff cap)
InpCapitalCapAmount0.0Capital cap amount ($)
InpCapitalCapFloor50.0Capital cap floor ($)
InpATRPeriod14ATR period
InpATRSLMult2.0SL = mult * ATR
InpATRTPMult3.0TP = mult * ATR
InpATRTrailMult2.5Trail = mult * ATR
InpADXPeriod14ADX period
InpHTF8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF timeframe (side filter)
InpMaxSpreadPoints50.0Max spread (points)
InpSlippagePoints10Slippage (points)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18025.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18025 XAUUSD TrendRider — 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.

Tags:ex18025trendfollowpipsgrowthfreemt5xauusd

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