P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18067 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18067 Momentum_Stacker_EA — Regime-gated trend/momentum stacker, full 12-layer stack.

Overview

The Momentum Stacker runs on the M5 chart but builds its decision from a vertical stack of three timeframes. Three independent Hull-MA pairs are pulled in via iMA(... MODE_LWMA ...) — half-period LWMA and full-period LWMA — for the M1 (20-bar), M5 (30-bar), and M15 (50-bar) charts, and the HullDir() helper compares 2×LWMA(period/2) − LWMA(period) across two consecutive closed bars to return +1 (rising), −1 (falling), or 0 (flat). Those three directional votes feed a six-slot consensus that also scores MACD histogram acceleration on the M1 chart (the M1 histogram value at bar 0 must exceed the value at bar 1, and the sign must match the trade direction), an M1 ATR expansion bar (the 14-period M1 ATR at bar 0 strictly exceeds the value at bar 1), and a tick-volume surge on the M1 chart where the latest 1-minute bar is at least 1.3× the rolling 20-bar average. The signal fires only when at least 4 of these 6 votes (the InpMinConfidence threshold) agree, and the check uses shift=1 so it never re-paints on the still-open bar.

The regime layer sits ahead of the signal and uses the same 14-period ADX and 14-period ATR that later drive the SL distance, plus a 20-period / 2.0-dev Bollinger Band whose width is measured as (upper − lower) / close. ClassifyRegime() first tests for a quiet, tight market (Bollinger width ≤ 0.0150 of price AND ATR percentile ≤ 25 → REG_COMPRESS). Then it tests for REG_STRONG_TREND (ADX ≥ 25 AND ATR percentile ≥ 75). If ADX is at least 18 with ATR percentile ≥ 50, the regime is REG_WEAK_TREND. A high ATR percentile alone with no trend filter yields REG_EXPAND, and a quiet ADX below 15 returns REG_CHOPPY. Three of those six states — REG_RANGE, REG_CHOPPY, REG_COMPRESS — are blockers: the entry gate at the top of OnTick() returns early when g_curRegime lands in any of them. Strong trend, weak trend, and expand are tradeable; momentum is allowed to lead price in any of them.

A set of confirm filters and a set of no-trade gates run before every entry. The confirm layer requires ConfirmHtf() to pass (the M15 close must be on the correct side of the M15 EMA(50)), ConfirmCandleClose() to pass (the most recent M5 candle must be a bullish close for a long, bearish for a short), and ConfirmMinRR() to pass (the projected TP distance versus the SL distance must clear InpMinRR=1.3; when TP is zero, the check uses 2×SL as a stand-in to keep the math well-defined). The no-trade layer checks effective capital against the floor, realized PnL against the daily and weekly loss caps, a 15-minute post-loss cooldown, the current spread against DEF_MAX_SPREAD_PIPS=2.5, the server hour against the 7–20 session window, weekend flags, and the broker's SYMBOL_TRADE_MODE flag.

Risk and sizing are bound together. The risk budget is 0.5% of the effective capital per trade, hard-capped at InpMaxLot=1.0. The effective capital is min(account equity, InpCapitalCapAmount) when the cap input is non-zero, otherwise pure account equity, and a InpCapitalCapFloor=50.0 guard disables entries entirely when effective capital falls below $50. The CalcLots() function converts the dollar risk into lots by dividing riskAmt by the per-lot stop-loss cost, which is derived from the SL distance times g_tickVal / g_tickSize (the broker's tick-value-to-tick-size ratio). Free margin is verified with OrderCalcMargin() before SendOrder() is invoked.

Position management runs in four phases. The first is break-even: at 1.0R profit the stop is ratcheted to open + 1 pip for longs and open − 1 pip for shorts, but only if the move actually tightens the stop (one-shot). The second is partial take-profit: at 1.5R, half the position is closed via TryClosePartial_EX18067 and the rest stays in play. The third is the trailing stop, computed as g_curAtr × InpATRTrailMult = 2.5 × ATR(14) behind the current bid or ask, and it only engages once the position is at least 0.5R into profit; the trail is forward-only and never moves backward. The fourth is the exit cluster: opposite-signal close (the latest EvaluateSignal() direction is against the position), regime-change close (the regime flipped to range, choppy, or compress), and a MAX_BARS_IN_TRADE=240 time stop (M5 × 240 ≈ 20 hours).

Pyramiding is wired but disabled by default. DEF_PYRAMID_ENABLED=false means a long signal is rejected outright when there is already a long position on the book. If the operator flips it on, the same PyramidMaxLevels=3 ceiling applies and a new entry requires the current price to be at least 1.5 × ATR(14) away from the most recent leg in the same direction. The directional exposure caps — DEF_MAX_SYMBOL_LONG=3 and DEF_MAX_SYMBOL_SHORT=3 — apply independently of pyramid mode and sit on top of the magic-wide InpMaxConcurrent=5 limit. A DuplicateEntryGuard (using g_lastEntryBarTime) also enforces MIN_BARS_BETWEEN=1 between consecutive entries on the same magic.

The OnTester() custom fitness score is (netProfit × profitFactor) / (1 + balanceDDPercent), returning 0 when the trade count is below 30 or drawdown is non-positive. The order comment is hardcoded to Psgrowth.com Expert_18067, deviation to 30 points, and the filling mode is set per-symbol via SetTypeFillingBySymbol. All three order-modify helpers (TryClose_EX18067, TryClosePartial_EX18067, TryModify_EX18067) retry three times on requote, timeout, price-off, and price-changed retcodes, with 200ms sleeps on close attempts and 100ms on modifications. As shipped, InpDryRun=true means the EA logs would-be entries to the journal only; you must flip it to false to send live orders, and the global InpKillSwitch is an extra hard stop that returns immediately from OnTick().

Strategy Deep Dive

OnTick() gates on a new M5 bar; the first thing it does is recompute the regime via ClassifyRegime() and re-evaluate the no-trade set (effective-capital floor, daily/weekly PnL, cooldown, spread, session, weekend, broker trade-mode). The signal layer in EvaluateSignal() then runs the three Hull directions, the MACD histogram acceleration on M1, the M1 ATR-rise test, and the M1 volume surge to build a 0–100 confidence score. If confidence clears InpMinConfidence=4 and the confirm passes (HTF EMA, candle close, MinRR), the position is sized from 0.5% risk, capped by InpMaxLot=1.0, and submitted through SendOrder() with 2 retries on requote/timeout. ManageOpenPositions() runs every bar to apply the 1R break-even, 50% partial at 1.5R, the 2.5×ATR trailing stop, and the exit cluster (opposite-signal, regime-flip, 240-bar time stop). The pyramid path is wired but DEF_PYRAMID_ENABLED=false keeps it off unless the operator flips it; with it on, additions require at least 1.5×ATR spacing and stay under PYRAMID_MAX_LEVELS=3 per direction.

Entry Signal

Triggers when at least 4 of 6 votes align on the closed M5 bar: three inline Hull-MA direction signals from the M1 (20-bar), M5 (30-bar), and M15 (50-bar) charts, plus MACD histogram acceleration on M1, an M1 ATR(14) expansion bar, and an M1 tick-volume surge at 1.3× the 20-bar average. The regime must allow entries (strong trend, weak trend, or expand), the M15 close must clear the M15 EMA(50) in the trade direction, and the most recent M5 candle must close on the right side. Pyramiding is off by default, so a fresh signal in the same direction as an existing position is rejected.

Exit Signal

Exits through three independent triggers: an opposite-direction signal from EvaluateSignal(), a regime flip into range/choppy/compress, and a 240-bar M5 time stop (about 20 hours). In-flight, the position is also closed by a 1R break-even snap (ratchets to open+1 pip, one-shot), a 50% partial close at 1.5R, and a 2.5×ATR(14) forward-only trailing stop that activates after 0.5R of profit. All close paths use the 3-retry helpers for requote/timeout/price-change events with 200ms sleeps.

Stop Loss

Initial stop is 1.8 × ATR(14) from entry, clamped to the broker's stops-level minimum and adjusted to the symbol's digits. Distance is purely volatility-relative — there is no swing-based stop. A 1R break-even snap then ratchets the stop to open+1 pip (one-shot) once the position moves 1.0R in favor.

Take Profit

Initial take-profit is 3.6 × ATR(14) from entry — roughly a 1:2 risk-to-reward ratio versus the 1.8×ATR stop. The TP is optional (InpATRTPmult=0 disables it), and the EA also runs a 50% partial close at 1.5R, a 1R break-even snap, and a 2.5×ATR(14) trailing stop — most positions leave before the full TP level when the trail catches a reversal.

Best For

Built for XAUUSD on M5; the M1/M5/M15 Hull stack only needs liquid 1-minute data, so pair it with an ECN or RAW-spread broker that quotes tight gold spreads. Minimum recommended balance is $100, with effective capital kept above the $50 floor that disables entries below that level. Risk is medium — 0.5% per trade with a 1.8×ATR(14) / 3.6×ATR(14) SL/TP bracket — and the default 7–20 server-time session window and 2.5-pip spread cap are sized for London and the London–New York overlap on gold.

Strategy Logic

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

Family: TrendFollow Magic: 22218067 Version: 2.00

BRIEF: Trend-follow / momentum-stack on M5 chart time. Regime layer (ADX + ATR-pct + BB-width) gates entries & sizing; Signal layer uses inline Hull-MA consensus (M1/M5/M15) plus MACD acceleration & ATR-expansion; Entry fires only on closed bar; Confirm (HTF EMA, volume, candle-close, min R/R); No-Trade (spread, session, news, choppy, weekend, exposure); Capital cap drives risk; ATR SL, BE, partial TP, ATR-trail, momentum-decay/opposite-signal exits; pyramid default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Adx
  • Atr
  • Bands
  • MacdM1
  • MacdM5
  • AtrM1
  • EmaHtf
  • MaM1h
  • MaM1f
  • MaM5h
  • MaM5f
  • MaM15h
  • MaM15f

KEY FUNCTIONS:

  • PipsToPrice()
  • PriceToPips()
  • NormVolume()
  • ClampStops()
  • CopyBuf()
  • HullDir()
  • ClassifyRegime()
  • EvaluateSignal()
  • ConfirmHtf()
  • ConfirmCandleClose()
  • ConfirmMinRR()
  • SpreadOK()
  • ...and 16 more

INTERNAL CONSTANTS (37 total):

  • DEF_ADX_STRONG = 25.0 // ADX >= -> StrongTrend
  • DEF_ADX_WEAK = 18.0 // ADX >= -> WeakTrend
  • DEF_ADX_CHOPPY = 15.0 // ADX < -> Choppy
  • DEF_ATR_PCT_LOOKBACK = 50 // bars for ATR percentile
  • DEF_ATR_PCT_EXPAND = 75.0 // ATR percentile >= Expand
  • DEF_ATR_PCT_COMPRESS = 25.0 // ATR percentile <= Compress
  • DEF_BANDS_PERIOD = 20 // Bollinger period
  • DEF_BANDS_DEV = 2.0 // Bollinger std-dev
  • DEF_BBW_COMPRESS_MAX = 0.0150 // BBW <= Compress (range/price)
  • DEF_HULL_M1_PERIOD = 20 // Hull M1 period (bars)
  • DEF_HULL_M5_PERIOD = 30 // Hull M5 period (bars)
  • DEF_HULL_M15_PERIOD = 50 // Hull M15 period (bars)
  • DEF_MACD_FAST = 12 // MACD fast EMA
  • DEF_MACD_SLOW = 26 // MACD slow EMA
  • DEF_MACD_SIGNAL = 9 // MACD signal EMA
  • ...and 22 more

INPUT PARAMETERS (21 total across 6 groups):

  • [=== Identity ===] InpMagic = 22218067 // Magic number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18067" // Trade comment
  • [=== Identity ===] InpDryRun = true // Dry-run (no live orders)
  • [=== Identity ===] InpKillSwitch = false // Global kill switch
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% effective cap)
  • [=== Risk & Sizing ===] InpMaxLot = 1.0 // Hard lot ceiling (lots)
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Max daily loss (% effective cap)
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPct = 6.0 // Max weekly loss (% effective cap)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 5 // Max concurrent positions (magic)
  • [=== Risk & Sizing ===] InpCooldownMinutes = 15 // Cooldown minutes after a loss
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Real-money equity cap ($)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor; block entries below ($)
  • [=== Signal ===] InpHullFastPeriod = 20 // Hull M1 (fast signal) period (bars)
  • [=== Signal ===] InpHullSlowPeriod = 50 // Hull M15 (slow/HTF) period (bars)
  • [=== Signal ===] InpMinConfidence = 4 // Min Hull+momentum votes (of 6)
  • [=== Regime / Confirm ===] InpATRPeriod = 14 // ATR period (bars)
  • [=== Regime / Confirm ===] InpADXPeriod = 14 // ADX period (bars)
  • [=== Regime / Confirm ===] InpMinRR = 1.3 // Min reward:risk ratio
  • [=== Exit / Manage ===] InpATRSLmult = 1.8 // ATR SL multiplier (x)
  • [=== Exit / Manage ===] InpATRTPmult = 3.6 // ATR TP multiplier (x, 0=none)
  • [=== Exit / Manage ===] InpATRTrailMult = 2.5 // ATR trailing multiplier (x)
Pseudocode
// Pipsgrowth EX18067 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Trend-follow / momentum-stack on M5 chart time. Regime layer (ADX + ATR-pct + BB-width) gates entries & sizing; Signal layer uses inline Hull-MA consensus (M1/M5/M15) plus MACD acceleration & ATR-expansion; Entry fires only on closed bar; Confirm (HTF EMA, volume, candle-close, min R/R); No-Trade (spread, session, news, choppy, weekend, exposure); Capital cap drives risk; ATR SL, BE, partial TP, ATR-trail, momentum-decay/opposite-signal exits; pyramid default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

ON_INIT:
    Create indicator handles: Adx, Atr, Bands, MacdM1, MacdM5, AtrM1, EmaHtf, MaM1h, MaM1f, MaM5h, MaM5f, MaM15h, MaM15f
    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
InpMagic22218067Magic number
InpTradeComment"Psgrowth.com Expert_18067"Trade comment
InpDryRuntrueDry-run (no live orders)
InpKillSwitchfalseGlobal kill switch
InpRiskPercent0.5Risk per trade (% effective cap)
InpMaxLot1.0Hard lot ceiling (lots)
InpDailyLossLimitPct3.0Max daily loss (% effective cap)
InpWeeklyLossLimitPct6.0Max weekly loss (% effective cap)
InpMaxConcurrent5Max concurrent positions (magic)
InpCooldownMinutes15Cooldown minutes after a loss
InpCapitalCapAmount0.0Real-money equity cap ($)
InpCapitalCapFloor50.0Floor; block entries below ($)
InpHullFastPeriod20Hull M1 (fast signal) period (bars)
InpHullSlowPeriod50Hull M15 (slow/HTF) period (bars)
InpMinConfidence4Min Hull+momentum votes (of 6)
InpATRPeriod14ATR period (bars)
InpADXPeriod14ADX period (bars)
InpMinRR1.3Min reward:risk ratio
InpATRSLmult1.8ATR SL multiplier (x)
InpATRTPmult3.6ATR TP multiplier (x, 0=none)
InpATRTrailMult2.5ATR trailing multiplier (x)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18067.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18067 Momentum_Stacker_EA — Regime-gated trend/momentum stacker, 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>

//=================== FIXED TUNABLES (compile-time) =================
// Regime thresholds (ADX + ATR percentile + Bollinger Band Width)
#define DEF_ADX_STRONG         25.0     // ADX >= -> StrongTrend
#define DEF_ADX_WEAK           18.0     // ADX >= -> WeakTrend
#define DEF_ADX_CHOPPY         15.0     // ADX <  -> Choppy
#define DEF_ATR_PCT_LOOKBACK   50       // bars for ATR percentile
#define DEF_ATR_PCT_EXPAND     75.0     // ATR percentile >= Expand
#define DEF_ATR_PCT_COMPRESS   25.0     // ATR percentile <= Compress
#define DEF_BANDS_PERIOD       20       // Bollinger period
#define DEF_BANDS_DEV          2.0      // Bollinger std-dev
#define DEF_BBW_COMPRESS_MAX   0.0150   // BBW <= Compress (range/price)

// Inline Hull-MA periods (M1 fast/slow, M5, M15 HTF)
#define DEF_HULL_M1_PERIOD     20       // Hull M1 period (bars)
#define DEF_HULL_M5_PERIOD     30       // Hull M5 period (bars)
#define DEF_HULL_M15_PERIOD    50       // Hull M15 period (bars)

// Momentum detection (MACD + ATR-rise + volume surge)
#define DEF_MACD_FAST          12       // MACD fast EMA
#define DEF_MACD_SLOW          26       // MACD slow EMA
#define DEF_MACD_SIGNAL        9        // MACD signal EMA
#define DEF_VOL_AVG_PERIOD     20       // Volume average period
#define DEF_VOL_SURGE_MULT     1.3      // Volume surge multiplier (x)

// Confirm / no-trade
#define DEF_HTF_EMA_PERIOD     50       // HTF EMA period on M15
#define DEF_MAX_SPREAD_PIPS    2.5      // Max spread (pips)
#define DEF_SESSION_START_H    7        // Session start (server hour 0-23)
#define DEF_SESSION_END_H      20       // Session end   (server hour 0-23)
#define DEF_NEWS_WINDOW_MIN    0        // News-window minutes around HH:00
#define DEF_MIN_BARS_BETWEEN   1        // Min bars between entries
#define DEF_SLIPPAGE_POINTS    30       // Order deviation (points)

// Manage / exit
#define DEF_BE_TRIGGER_R       1.0      // Break-even trigger (R-multiple)
#define DEF_BE_OFFSET_PIPS     1.0      // Break-even offset (pips)
#define DEF_PARTIAL_PCT        50.0     // Partial TP size (%)
#define DEF_PARTIAL_AT_R       1.5      // Partial TP trigger (R)
#define DEF_MAX_BARS_IN_TRADE  240      // Max bars in trade (M5 ~20h)
#define DEF_EXIT_OPP_SIGNAL    true     // Exit on opposite signal
#define DEF_EXIT_REGIME_CHG    true     // Exit on regime flip to Range/Choppy
#define DEF_MAX_SYMBOL_LONG    3        // Max long exposure per symbol
#define DEF_MAX_SYMBOL_SHORT   3        // Max short exposure per symbol

// Pyramid (default OFF, hard-capped at 5)
#define DEF_PYRAMID_ENABLED    false    // Enable pyramiding
#define DEF_PYRAMID_MAX_LEVELS 3        // Max pyramid levels (<=5)

Full source code available on download

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

Tags:ex18067trendfollowpipsgrowthfreemt5xauusd

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