P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18063 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M15

Pipsgrowth.com EX18063 HullTest_PyMatch — MTF inline Hull-MA consensus + full risk/regime stack, 12-layer.

Overview

Pipsgrowth EX18063 TrendFollow is a three-leg Hull moving-average consensus strategy on M15, with M30 and H1 acting as confirmation telescopes. Each leg carries its own ADX threshold, and the EA only fires when at least two of the three timeframes slope in the same direction with no opposition vote. The whole system is built around the idea that a single Hull cross on a fast chart is noise, but a fast chart, a medium chart, and a slow chart all leaning the same way is information worth trading.

The Hull values are computed in-line from raw close arrays rather than pulled from a child indicator. CalcLWMA builds a linear-weighted average of N consecutive closes with weights descending from period to 1, and CalcHullValue returns 2*LWMA(period/2) - LWMA(period). HullDirection then samples that result at offsets 0, 1, and 2 on the closed-bar series and demands a monotonic slope across two bars and a close beyond the current Hull value before declaring +1 or -1. The per-timeframe ADX gate sits inside HullDirection, so a chart that is technically rising but lacks the trend strength to clear its floor is treated as a non-vote rather than a vote. The M15 fast leg has a 24 ADX minimum, the M30 medium leg 28, and the H1 slow leg 30; raising any of those floors is the cleanest way to dial selectivity.

With InpMinHullsAgree=2 the EA only trades when the count of agreement votes is at least 2 and the count of opposite votes is 0. A clean long setup needs M15 and M30 both returning +1 (with H1 neutral or agreeing), and a short needs the inverse pattern. The asymmetric rule is deliberate: a +1/+1/0 signal is allowed, but a +1/0/-1 signal is rejected. That veto-on-opposition clause is what filters out the period after a fast chart flips bullish while the dominant chart is still in a downtrend, which is the single most common source of false breakouts on M15.

Confirmation runs after the vote, not before. ConfirmBlock checks four gates: H1 EMA(50) agrees with the direction and is itself sloping in the same way, the ATR-percentile sits inside the 35-92 band (excluding both compressed and climactic volatility), server time is in Asia, London, or New York, and the planned R-multiple of TP2 over the stop is at least 1.5. InpMinConfirms=2 means a trade can fire when only two of the four gates are clear, and in practice the session and R-multiple gates pass almost trivially while the HTF EMA gate is the one that does the real filtering against counter-trend signals.

The regime classifier pulls from three different sources: H1 ADX for trend strength, M15 ATR(14) percentile over a 50-bar window for volatility context, and 20-period Bollinger bandwidth versus its own rolling average. The output is one of seven states. StrongTrend is ADX >= 30 and ATR-percentile >= 60, WeakTrend is ADX >= 22 and ATR-percentile >= 40, Breakout is BB width above 1.4x its rolling average with ATR-percentile >= 70, Compress is BB width below 0.7x its average, Expand is ATR-percentile >= 80, Choppy is ADX < 18, and Range is the catch-all. Choppy is the only state that blocks entries outright; the others modulate signal quality but do not veto the trade on their own.

Risk and the no-trade gate form the standard safety stack. Risk per trade is 0.75% of effective capital, which sits above the 0.5% floor that most of the TrendFollow family uses; position size is sized against the ATR(14) stop distance through CalcLotByRisk and clamped to the broker's lot step and limits via NormVol. Daily loss limit is 3% and weekly is 9%, with the weekly cap deliberately looser than the 6% that other EAs in the corpus tend to enforce. The capital cap is opt-in: InpCapitalCapAmount=0 disables it, but when set the EA uses min(cap, equity) as effective capital and refuses to take new entries below a $50 floor. Cooldown fires after 2 consecutive losses and lasts 3 M15 bars. Friday at hour 20 server time forces a close of every open position, Saturday and Sunday are no-trade, and the spread filter compares the current spread to a rolling average with a 3.0x multiplier.

Position management is the most configurable block on the EA. Break-even triggers at profitR >= 1.0 and ratchets the stop to open + 5 points (open - 5 for sells); the trailing stop kicks in at profitR >= 0.8, which is unusually early in the cycle, and walks the stop by 2.0x ATR(14) per new bar. The 50% partial close fires at 1.0R. Three independent exit triggers run in parallel and can cut the trade before TP2 is reached: a stochastic K% cross above 80 on longs or below 20 on shorts (with a 15-point minimum profit floor), an ATR spike above 2.2x its 50-bar average, and a reversal signal where the consensus flips to the opposite direction. The full TP2 at 3.0R is sent on the entry ticket; the trail and the three exit triggers can close the position before it is hit.

Pyramiding is enabled by default and capped at 3 legs in the same direction. The pyramid gate requires every existing same-direction position to be at least 15 points in profit before another leg can be added, which means the EA only adds to winners that are already moving. OrderCalcMargin is checked before each send, slippage is capped at 30 points, and SetTypeFillingBySymbol handles the filling-mode question automatically. InpDryRun=true is the default, which means the EA logs hypothetical orders until you turn it off in the inputs; InpKillSwitch is the panic button that stops new entries without removing the EA from the chart.

For deployment, the EA is tuned for XAUUSD M15 but the M30 and H1 cross-checks mean the strategy behaves best on instruments with sustained directional trends rather than the kind of chop that some FX crosses deliver. A 10-trade cold streak at maximum loss lands at -7.5% of effective capital, well inside the 9% weekly cap, and the 3-bar cooldown after 2 losses is short enough to keep the EA trading but long enough to avoid the revenge-trade pattern. Expect a low-trade-frequency trend follower with selective entries - two or three trades per week on XAUUSD M15 is a realistic baseline, with most of the equity curve coming from a small number of medium-duration trends rather than a high count of small wins.

Strategy Deep Dive

Each M15 tick, the EA computes three independent Hull moving averages on M15, M30, and H1 from raw close arrays using a linear-weighted primitive (CalcLWMA), samples 2-bar monotonic slope on each, and rejects any timeframe whose ADX is below its per-timeframe floor (24 / 28 / 30). The vote counter requires at least 2 timeframes to agree on direction with the opposite count at 0. Confirmation runs after the vote and demands 2 of 4: H1 EMA(50) agreement with slope, ATR-percentile in the 35-92 band, server session in Asia/London/New York, and TP2/SL above 1.5. Regime is classified from H1 ADX, M15 ATR(14) percentile, and Bollinger bandwidth into 7 states, with Choppy the only blocker. Risk is 0.75% of effective capital per trade, sized against the ATR(14) stop, with daily 3% / weekly 9% loss caps, a $50 capital floor, and 2-loss / 3-bar cooldown. The position manager runs break-even at 1.0R, an early ATR trail at 0.8R, 50% partial TP at 1.0R, full TP at 3.0R, and three parallel exit triggers (stochastic, volatility-spike, reverse-consensus).

Entry Signal

Long or short entries fire when at least 2 of 3 timeframes (M15, M30, H1) return the same direction from HullDirection, with each timeframe's ADX above its threshold (24 / 28 / 30) and the opposite-vote count at 0. Confirmation is 2 of 4: H1 EMA(50) agreement with slope, ATR-percentile between 35 and 92, server session in Asia/London/New York, and TP2/SL of at least 1.5. Entries are bar-keyed on M15 (one per closed bar) and blocked when the regime classifier returns Choppy.

Exit Signal

Exits are: (1) full TP at 3.0R, (2) 50% partial close at 1.0R, (3) break-even stop ratchet at 1.0R to open plus 5 points, (4) ATR trail of 2.0x ATR(14) activating at 0.8R, (5) stochastic exit when K% crosses 80/20 in long/short with a 15-point minimum profit, (6) volatility-spike exit when ATR exceeds 2.2x its 50-bar average, and (7) reverse-consensus close when the MTF Hull vote flips. Friday at hour 20 server time and weekend force-close all positions.

Stop Loss

Initial stop is 1.5 x ATR(14) on M15, floored to the broker's stops-level plus 1 point via EnforceStopsDistance. The stop ratchets to open + 5 points (open - 5 for sells) once profit reaches 1.0R, and from there an ATR trail of 2.0 x ATR(14) takes over once profit clears 0.8R, walking the stop forward each new bar.

Take Profit

TP1 fires at 1.0R and closes 50% of the position. The full TP2 at 3.0R is the trade's terminal target and is set on the entry ticket; the ATR trail, the stochastic cross exit, the volatility-spike exit, and the reverse-consensus exit can all close the trade before TP2 is reached.

Best For

Recommended for XAUUSD M15 with a minimum balance of $100, MEDIUM risk tolerance, and 0.75% per-trade risk. The 30-point H1 ADX floor makes the strategy well-suited to instruments with sustained directional trends and ill-suited to choppy FX crosses. Run only during the Asia, London, and New York server sessions, since the EA blocks entries outside those windows. A low-spread broker is needed because the spread filter uses a 3.0x rolling-average multiplier; for XAUUSD M15 this typically means a sub-30-point typical spread, which most ECN or RAW accounts meet without issue. Switch InpDryRun to false only after the strategy passes both backtest and forward test on the chosen symbol and broker.

Strategy Logic

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

Family: TrendFollow Magic: 22218063 Version: 2.00

BRIEF: Multi-timeframe inline Hull-MA (LWMA primitive) slope- color consensus across M15/M30/H1, each gated by its own ADX. Full 12-layer stack: regime(ADX+ATR-pctile+BBwidth), consensus signal, bar-keyed entry, 2-confirmer confirm block, full no-trade gate, capital-allocation-cap risk/sizing, ATR-trail+ BE+ partial TP + stochastic/vol/reversal exits, OnTester. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • NormPrice()
  • NormVol()
  • DayStart()
  • WeekStart()
  • RegimeClassify()
  • EffectiveCapital()
  • EADayRealizedPnL()
  • EAWeekRealizedPnL()
  • CalcLWMA()
  • CalcHullValue()
  • HullDirection()
  • ComputeRegime()
  • ...and 16 more

INTERNAL CONSTANTS (34 total):

  • DEF_HULL1_PERIOD = 130 // M15 Hull period
  • DEF_HULL1_DIVISOR = 16.5 // M15 Hull divisor (kept for compat)
  • DEF_HULL2_PERIOD = 200 // M30 Hull period
  • DEF_HULL2_DIVISOR = 11.0 // M30 Hull divisor
  • DEF_HULL3_PERIOD = 300 // H1 Hull period
  • DEF_HULL3_DIVISOR = 15.0 // H1 Hull divisor
  • DEF_HULL_SLOPE_BARS = 2 // Hull rising/falling bars (1->2->3)
  • DEF_ADX_PERIOD = 20 // ADX period (all tfs)
  • DEF_ATR_PERIOD = 14 // ATR period
  • DEF_ATR_PCTILE_BARS = 50 // ATR percentile lookback
  • DEF_BB_PERIOD = 20 // Bollinger period
  • DEF_BB_DEV = 2.0 // Bollinger deviation
  • DEF_STOCH_K = 45 // Stochastic %K
  • DEF_STOCH_D = 28 // Stochastic %D
  • DEF_STOCH_SLOW = 23 // Stochastic slowing
  • ...and 19 more

INPUT PARAMETERS (25 total across 6 groups):

  • [=== Identity ===] InpMagic = 22218063 // Magic number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18063" // Trade comment
  • [=== Identity ===] InpDryRun = true // Dry-run: skip order sends
  • [=== Identity ===] InpKillSwitch = false // Kill switch: stop all new entries
  • [=== Risk & Sizing ===] InpRiskPercent = 0.75 // Risk per trade (% effective_capital)
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (% effective_capital)
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPct = 9.0 // Weekly loss limit (% effective_capital)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 3 // Max concurrent positions (this EA, this symbol)
  • [=== Risk & Sizing ===] InpMaxSymbolExposure = 3 // Max positions per symbol
  • [=== Risk & Sizing ===] InpCooldownLosses = 2 // Cooldown after N consecutive losses
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Capital cap amount ($, real money)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Capital cap floor ($, blocks new entries)
  • [=== Signal ===] InpMinHullsAgree = 2 // Min Hull TFs agreeing (1-3)
  • [=== Signal ===] InpAdxThresholdM15 = 24.0 // ADX threshold M15
  • [=== Signal ===] InpAdxThresholdM30 = 28.0 // ADX threshold M30
  • [=== Signal ===] InpAdxThresholdH1 = 30.0 // ADX threshold H1
  • [=== Regime / Confirm ===] InpRegimeAdxMin = 18 // Regime ADX minimum (else no-trade)
  • [=== Regime / Confirm ===] InpMinConfirms = 2 // Min confirmations required (1-4)
  • [=== Exit / Manage ===] InpEnableBE = true // Enable break-even
  • [=== Exit / Manage ===] InpBETriggerR = 1.0 // BE trigger (R multiples)
  • [=== Exit / Manage ===] InpEnableTrail = true // Enable ATR trailing
  • [=== Exit / Manage ===] InpEnablePartial = true // Enable partial TP at TP1
  • [=== Exit / Manage ===] InpEnableStochExit = true // Enable stochastic exit
  • [=== Exit / Manage ===] InpEnableVolExit = true // Enable volatility-spike exit
  • [=== Exit / Manage ===] InpEnableRevExit = true // Enable reversal (opposite-consensus) exit
Pseudocode
// Pipsgrowth EX18063 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Multi-timeframe inline Hull-MA (LWMA primitive) slope- color consensus across M15/M30/H1, each gated by its own ADX. Full 12-layer stack: regime(ADX+ATR-pctile+BBwidth), consensus signal, bar-keyed entry, 2-confirmer confirm block, full no-trade gate, capital-allocation-cap risk/sizing, ATR-trail+ BE+ partial TP + stochastic/vol/reversal exits, 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:
M15

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
InpMagic22218063Magic number
InpTradeComment"Psgrowth.com Expert_18063"Trade comment
InpDryRuntrueDry-run: skip order sends
InpKillSwitchfalseKill switch: stop all new entries
InpRiskPercent0.75Risk per trade (% effective_capital)
InpDailyLossLimitPct3.0Daily loss limit (% effective_capital)
InpWeeklyLossLimitPct9.0Weekly loss limit (% effective_capital)
InpMaxConcurrent3Max concurrent positions (this EA, this symbol)
InpMaxSymbolExposure3Max positions per symbol
InpCooldownLosses2Cooldown after N consecutive losses
InpCapitalCapAmount0.0Capital cap amount ($, real money)
InpCapitalCapFloor50.0Capital cap floor ($, blocks new entries)
InpMinHullsAgree2Min Hull TFs agreeing (1-3)
InpAdxThresholdM1524.0ADX threshold M15
InpAdxThresholdM3028.0ADX threshold M30
InpAdxThresholdH130.0ADX threshold H1
InpRegimeAdxMin18Regime ADX minimum (else no-trade)
InpMinConfirms2Min confirmations required (1-4)
InpEnableBEtrueEnable break-even
InpBETriggerR1.0BE trigger (R multiples)
InpEnableTrailtrueEnable ATR trailing
InpEnablePartialtrueEnable partial TP at TP1
InpEnableStochExittrueEnable stochastic exit
InpEnableVolExittrueEnable volatility-spike exit
InpEnableRevExittrueEnable reversal (opposite-consensus) exit
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18063.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18063 HullTest_PyMatch — MTF inline Hull-MA consensus + full risk/regime stack, 12-layer."

#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>
#include <Trade/SymbolInfo.mqh>
#include <Trade/AccountInfo.mqh>

//================= TUNABLE CONSTANTS (NOT inputs) =================
#define DEF_HULL1_PERIOD       130     // M15 Hull period
#define DEF_HULL1_DIVISOR      16.5    // M15 Hull divisor (kept for compat)
#define DEF_HULL2_PERIOD       200     // M30 Hull period
#define DEF_HULL2_DIVISOR      11.0    // M30 Hull divisor
#define DEF_HULL3_PERIOD       300     // H1 Hull period
#define DEF_HULL3_DIVISOR      15.0    // H1 Hull divisor
#define DEF_HULL_SLOPE_BARS    2       // Hull rising/falling bars (1->2->3)
#define DEF_ADX_PERIOD         20      // ADX period (all tfs)
#define DEF_ATR_PERIOD         14      // ATR period
#define DEF_ATR_PCTILE_BARS    50      // ATR percentile lookback
#define DEF_BB_PERIOD          20      // Bollinger period
#define DEF_BB_DEV             2.0     // Bollinger deviation
#define DEF_STOCH_K            45      // Stochastic %K
#define DEF_STOCH_D            28      // Stochastic %D
#define DEF_STOCH_SLOW         23      // Stochastic slowing
#define DEF_STOCH_OB           80.0    // Stochastic overbought
#define DEF_STOCH_OS           20.0    // Stochastic oversold
#define DEF_STOCH_MIN_PROFIT   15.0    // Stochastic exit min profit (pts)
#define DEF_VOL_SPIKE_MULT     2.2     // ATR-spike exit multiplier
#define DEF_VOL_ATR_AVG        50      // ATR-spike average lookback
#define DEF_PROFIT_GATE_PTS    15.0    // Pyramid profit gate (pts)
#define DEF_MAX_PYRAMID        3       // Max pyramid levels (hard-cap 5)
#define DEF_HTF_TF             PERIOD_H1
#define DEF_HTF_EMA_PERIOD     50      // HTF EMA period
#define DEF_BE_OFFSET_PTS      5.0     // BE offset (pts)
#define DEF_PARTIAL_RATIO       0.50   // Partial close ratio (TP1)
#define DEF_TP1_R              1.0     // TP1 distance in R
#define DEF_TP2_R              3.0     // TP2 distance in R
#define DEF_SL_ATR_MULT        1.5     // SL = ATR * mult (floor stops-level)
#define DEF_TRAIL_ATR_MULT     2.0     // ATR trail distance multiplier
#define DEF_TRAIL_TRIGGER_R    0.8     // Trail activation in R
#define DEF_COOLDOWN_BARS      3       // Bars cooldown after loss
#define DEF_SPREAD_MULT_MAX    3.0     // Max spread vs rolling avg
#define DEF_EOD_HOUR           20      // EOD close hour (server time)
#define DEF_MAX_SLIPPAGE_PTS   30      // Slippage in points

//================= INPUTS (12-22) =================
input group "=== Identity ==="
input ulong  InpMagic         = 22218063;                                  // Magic number
input string InpTradeComment  = "Psgrowth.com Expert_18063";               // Trade comment
input bool   InpDryRun        = true;                                     // Dry-run: skip order sends
input bool   InpKillSwitch    = false;                                    // Kill switch: stop all new entries

input group "=== Risk & Sizing ==="
input double InpRiskPercent        = 0.75;                                // Risk per trade (% effective_capital)
input double InpDailyLossLimitPct  = 3.0;                                 // Daily loss limit (% effective_capital)
input double InpWeeklyLossLimitPct = 9.0;                                 // Weekly loss limit (% effective_capital)
input int    InpMaxConcurrent      = 3;                                   // Max concurrent positions (this EA, this symbol)

Full source code available on download

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

Tags:ex18063trendfollowpipsgrowthfreemt5xauusd

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