P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18061 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1

Pipsgrowth.com EX18061 HullAverage2 — Inline dual Hull-MA slope/color consensus trend follower, full 12-layer stack.

Overview

The Pipsgrowth EX18061 is a single-position, ATR-anchored trend follower that anchors its entire risk architecture on a 1:2 reward-to-risk envelope. Every signal flows through the same constraint: if the math cannot justify a TP that is at least twice the stop distance, the trade is rejected before it ever reaches the order ticket. That single filter defines the character of the system — slow, deliberate, and ruthlessly selective.

The signal is built from two inline Hull moving averages, fast at 34 bars and slow at 89 bars, both computed on close prices. There is no iCustom call, no external indicator file: the Hull math is hand-rolled inside HullValue() using weighted moving averages from WMA(). A 34-bar Hull first derives a half-period WMA at 17 bars, subtracts the full 34-bar WMA, doubles the half, then takes a square-root-period WMA of the resulting series. The slow 89-bar Hull runs the same construction with a 45/89/9 split. The signal function then compares the value at bar 1 (the last closed bar) against bar 2 to determine color: +1 if the curve is rising, -1 if falling, 0 if flat. A trade is only valid when the fast and slow Hulls share the same color, and that color is non-zero. To filter out single-bar whipsaws, HullSignal() demands a confirmation count across HULL_CONFIRM_BARS (set to 2): the fast Hull must agree with its color on both of the two most recent closed bars. The returned confidence climbs from 50% to 100% as the agreement count grows.

A seven-state regime filter runs in front of the signal. DetectRegime() reads ADX(14), ATR(14), and Bollinger Bands(20, 2.0) and reduces the market to one of seven states: STRONG_TREND when ADX clears InpAdxMinTrend (20.0), WEAK_TREND between 18.0 and 20.0, RANGE otherwise. Volatility overrides then apply. If the current ATR sits in the 80th percentile of the last 100 closed bars and is rising, the regime is reclassified as EXPAND when ADX is at or above 22, or BREAKOUT otherwise. ATR in the bottom 20th percentile pushes the state to COMPRESS, as does a Bollinger width contraction of more than 15% bar-over-bar. Width expansion of more than 25% lifts the state to EXPAND. ADX below 15 with elevated ATR percentile flags CHOPPY. The tradeable set is exactly four: STRONG_TREND, WEAK_TREND, BREAKOUT, and EXPAND — three states close the door.

After the signal passes, four confirmation gates must all clear. CheckConfirms() evaluates the higher-timeframe EMA first: an H1 EMA(50) (set in HTF_TIMEFRAME and InpHtfEmaPeriod) must sit on the buy side of the closed-bar close for longs, on the sell side for shorts. Second, the Heikin-Ashi confirm is checked when InpUseHeikinAshi is true (default): the constructed HA candle for the most recent closed bar must be bullish for a long and bearish for a short, derived by averaging open, high, low, and close into the HA body. Third, the prior candle body must agree: a long entry requires the previous bar to close above its open, and shorts require the inverse. Fourth, the reward-to-risk ratio of the proposed trade must be at least 1.5. Because stop and target are set at 2.0x and 4.0x ATR(14), the 1.5 threshold is essentially a sanity check that ATR data was successfully copied and the math is non-degenerate.

The capital cap is the other half of the risk architecture. ComputeEffectiveCapital() takes the minimum of InpCapitalCapAmount and current equity when the cap is positive, otherwise falls back to raw equity. That figure flows into the lot calculation: CalcLotByRisk() uses tick value and tick size to translate the 0.5% risk budget into a lot count normalized to the broker's volume step. The daily loss limit (InpDailyLossLimitPct at 3%) and the hardcoded weekly limit (WEEKLY_LOSS_PCT at 6%) both reference the effective capital. A separate 4-hour cooldown fires from g_cooldownUntil after UpdateLossStreak() detects three or more consecutive losses.

In-trade management follows a layered rule set. When price reaches +1R, two adjustments fire: the stop ratchets to break-even plus 2 points (one-shot, controlled by USE_BREAK_EVEN), and half the position is closed at market if the remaining lot is at least twice the broker minimum (USE_PARTIAL_TP). From that point forward, a forward-only ATR trail at InpAtrTrailMult (2.5xATR(14)) ratchets the stop to lock in additional progress — the stop only ever moves in the direction of the trade. The position is force-closed if it survives longer than InpMaxBarsInTrade (200 bars) or if the Hull color flips to the opposite direction with at least one bar of confirmation.

The trade-management side does not run on every tick. OnTick() calls ManageOpenPositions() only when the ATR buffer is fresh, and the entry logic is gated by IsNewBar() so signals can only fire once per closed M5 bar. TryPyramid() is wired but disabled by default (USE_PYRAMID is hardcoded to false); enabling it permits up to three same-direction legs spaced by 2.0xATR of progress, which matches the conservative character of the rest of the design.

Execution safety is built into the path. OrderCalcMargin() runs before every entry, and the EA refuses to open a trade when required margin exceeds free margin. InpDryRun defaults to true, so a fresh install logs trade intentions to the experts tab without sending orders. TryClose_EX18061, TryClosePartial_EX18061, and TryModify_EX18061 retry up to three times on requote, timeout, price-off, or price-changed retcodes with 200ms / 100ms back-off before giving up. InpKillSwitch is a hard master cutoff that prevents new entries without affecting existing positions.

In a backtest, expect a small number of trades per day — the 4-gate confirm plus the regime filter plus the trend requirement naturally compress the entry set. The custom OnTester() formula multiplies net profit by profit factor and divides by one plus the balance drawdown, with a 30-trade minimum to score non-zero. That favors a profile with high reward-per-trade and a low-to-moderate trade count over a high-frequency equity curve. The Heikin-Ashi gate is the most useful off-switch for traders who find the system too selective: disabling InpUseHeikinAshi increases the entry rate while preserving the rest of the risk and regime logic.

The natural fit is a trader with a $100-plus account trading XAUUSD on M5 with an ECN or low-spread broker, a tolerance for waiting out drawdowns, and a willingness to let winners run to the full 4.0xATR target. The 7-21 server-time session matches the London-New York overlap during US hours, and the 3-pip spread cap means a broker that widens aggressively in pre-market or rollover sessions will produce more spread_high log entries than trades.

Strategy Deep Dive

The signal starts from two inline Hull moving averages — fast 34 and slow 89, both computed in HullValue() from a hand-rolled WMA primitive — and only fires when both slope in the same non-zero direction with at least 2 bars of confirmation. A seven-state regime classifier built from ADX(14), ATR(14) percentile rank across 100 bars, and Bollinger Bands(20, 2.0) width must then be in {STRONG_TREND, WEAK_TREND, BREAKOUT, EXPAND} for the signal to proceed. The order path runs the H1 EMA(50) test, a Heikin-Ashi direction check, a prior-bar candle agreement, and a 1.5 R:R sanity gate before sizing via CalcLotByRisk() and submitting through TryEntry(). Every tick that has a fresh ATR runs ManageOpenPositions() to fire the one-shot break-even at +1R, the 50% partial close at +1R, and the forward-only 2.5xATR trail; new-bar gating plus 3-attempt retry helpers on close, partial close, and modify cover the execution side, with OrderCalcMargin() blocking entries that would breach free margin.

Entry Signal

Long entry fires when the inline 34/89 Hull MA pair both slope in the same direction on a closed bar with at least 2 bars of confirmation, the H1 EMA(50) sits on the buy side of close, Heikin-Ashi and prior-bar candle bodies agree, and the regime is in {STRONG_TREND, WEAK_TREND, BREAKOUT, EXPAND}. Short entry mirrors all of that with the opposite slope, EMA position, and HA/candle directions. The 1.5 R:R confirm gate enforces that the proposed 2.0xATR stop and 4.0xATR target math is non-degenerate before the order is sized.

Exit Signal

At +1R the position moves to break-even plus 2 points and half the position is closed at market, leaving the runner to follow a forward-only 2.5xATR(14) trail. Exit triggers also include a closed-bar opposite-signal flip (Hull color reverses with confirmation) and a 200-bar time stop via InpMaxBarsInTrade. The break-even and partial close fire exactly once per position — the +1R threshold is latched so the second time price touches that level, no further partial closes happen.

Stop Loss

Initial stop is set at 2.0xATR(14) from entry and adjusted outward to satisfy the broker's stops-level minimum; from the first +1R touch the stop ratchets to break-even plus 2 points and the 2.5xATR(14) forward-only trail takes over as the only stop modification.

Take Profit

Take profit is set at 4.0xATR(14) from entry (1:2 reward-to-risk against the 2.0xATR stop), with a 50% partial close also fired at +1R to lock in initial risk-reward. The 1.5 R:R confirm gate enforces a minimum acceptable target-to-stop ratio before the order is placed, so a degenerate ATR reading is caught upstream.

Best For

Best fit is a single-position trader on XAUUSD M5 with a $100-plus account and tolerance for slow signals, since the 4-gate confirm stack and regime filter compress entries to a handful per session. The 7-21 server-time window covers the London and New York overlap, and the 3-pip spread cap requires an ECN or RAW-spread broker that holds its quote in active hours. The 3% daily and 6% weekly loss limits plus the 4-hour cooldown after three consecutive losses are wired to InpCapitalCapAmount set to $0 by default — raise that input to your real-money allocation to engage the daily/weekly caps against the capped equity, and an emergency shutdown sits behind InpKillSwitch.

Strategy Logic

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

Family: TrendFollow Magic: 22218061 Version: 2.00

BRIEF: Inline dual Hull-MA (fast/slow) computed from WMA primitives (iMA LWMA) gives slope + color consensus. Entries fire only on closed-bar color agreement gated by an ADX+ATR- pct+BB-width regime filter, HTF-EMA agreement and Heikin-Ashi confirm. Capital-allocation cap drives all risk/sizing. In-trade mgmt: break-even, ATR-trail, partial TP, regime/opposite exit. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • Norm()
  • StopsLevelPrice()
  • AdjustSlForStops()
  • AdjustTpForStops()
  • SeriesCopy()
  • WMA()
  • HullValue()
  • RegimeAllowsEntry()
  • HullSignal()
  • HeikinAshiConfirm()
  • InSession()
  • SpreadPoints()
  • ...and 21 more

INTERNAL CONSTANTS (1 total):

  • MIN_TRADES_TESTER = 30 // ================= INPUTS (22) ====================

INPUT PARAMETERS (21 total across 8 groups):

  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18061" // Trade comment
  • [=== Hull Signal ===] InpHullFastPeriod = 34 // Fast Hull period (bars)
  • [=== Hull Signal ===] InpHullSlowPeriod = 89 // Slow Hull period (bars)
  • [=== Regime Filter ===] InpAdxPeriod = 14 // ADX period (bars)
  • [=== Regime Filter ===] InpAdxMinTrend = 20.0 // ADX min for StrongTrend (-)
  • [=== Regime Filter ===] InpAtrPeriod = 14 // ATR period (bars)
  • [=== Regime Filter ===] InpBandsPeriod = 20 // Bollinger period (bars)
  • [=== Confirm ===] InpHtfEmaPeriod = 50 // HTF EMA period (bars)
  • [=== Confirm ===] InpUseHeikinAshi = true // Require Heikin-Ashi confirm
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective cap)
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (% of effective cap)
  • [=== Risk & Sizing ===] InpAtrSlMult = 2.0 // SL = ATR * mult (-)
  • [=== Risk & Sizing ===] InpAtrTpMult = 4.0 // TP = ATR * mult (-)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 1 // Max concurrent positions (-)
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Cap amount ($ real money)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor below which no new entries ($)
  • [=== In-Trade Management ===] InpAtrTrailMult = 2.5 // ATR trailing multiplier (-)
  • [=== In-Trade Management ===] InpMaxBarsInTrade = 200 // Max bars before forced exit
  • [=== Exec & Safety ===] InpMagic = 22218061 // Magic number
  • [=== Exec & Safety ===] InpDryRun = true // Dry-run (no live orders)
  • [=== Exec & Safety ===] InpKillSwitch = false // Master kill switch
Pseudocode
// Pipsgrowth EX18061 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Inline dual Hull-MA (fast/slow) computed from WMA primitives (iMA LWMA) gives slope + color consensus. Entries fire only on closed-bar color agreement gated by an ADX+ATR- pct+BB-width regime filter, HTF-EMA agreement and Heikin-Ashi confirm. Capital-allocation cap drives all risk/sizing. In-trade mgmt: break-even, ATR-trail, partial TP, regime/opposite exit. 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:
M5H1

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
InpTradeComment"Psgrowth.com Expert_18061"Trade comment
InpHullFastPeriod34Fast Hull period (bars)
InpHullSlowPeriod89Slow Hull period (bars)
InpAdxPeriod14ADX period (bars)
InpAdxMinTrend20.0ADX min for StrongTrend (-)
InpAtrPeriod14ATR period (bars)
InpBandsPeriod20Bollinger period (bars)
InpHtfEmaPeriod50HTF EMA period (bars)
InpUseHeikinAshitrueRequire Heikin-Ashi confirm
InpRiskPercent0.5Risk per trade (% of effective cap)
InpDailyLossLimitPct3.0Daily loss limit (% of effective cap)
InpAtrSlMult2.0SL = ATR * mult (-)
InpAtrTpMult4.0TP = ATR * mult (-)
InpMaxConcurrent1Max concurrent positions (-)
InpCapitalCapAmount0.0Cap amount ($ real money)
InpCapitalCapFloor50.0Floor below which no new entries ($)
InpAtrTrailMult2.5ATR trailing multiplier (-)
InpMaxBarsInTrade200Max bars before forced exit
InpMagic22218061Magic number
InpDryRuntrueDry-run (no live orders)
InpKillSwitchfalseMaster kill switch
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18061.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18061 HullAverage2 — Inline dual Hull-MA slope/color consensus trend follower, full 12-layer stack."

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

//--- hardcoded constants (not exposed as inputs to stay within 22-input cap)
#define HULL_PRICE          PRICE_CLOSE
#define HULL_CONFIRM_BARS   2
#define BANDS_DEV           2.0
#define ATR_PCT_LOOKBACK    100
#define HTF_TIMEFRAME       PERIOD_H1
#define WEEKLY_LOSS_PCT     6.0
#define MAX_SYMBOL_POS      1
#define COOLDOWN_LOSSES     3
#define USE_BREAK_EVEN      true
#define USE_PARTIAL_TP      true
#define USE_PYRAMID         false
#define PYRAMID_MAX_LEVELS  3
#define PYRAMID_ATR_SPACE   2.0
#define SESSION_START_HR    7
#define SESSION_END_HR      21
#define MAX_SPREAD_POINTS   30
#define DEVIATION_POINTS    20
#define MIN_TRADES_TESTER   30

//================= INPUTS (22) ====================
input group "=== Identity ==="
input string           InpTradeComment       = "Psgrowth.com Expert_18061"; // Trade comment

input group "=== Hull Signal ==="
input int              InpHullFastPeriod   = 34;            // Fast Hull period (bars)
input int              InpHullSlowPeriod   = 89;            // Slow Hull period (bars)

input group "=== Regime Filter ==="
input int              InpAdxPeriod        = 14;            // ADX period (bars)
input double           InpAdxMinTrend      = 20.0;          // ADX min for StrongTrend (-)
input int              InpAtrPeriod         = 14;            // ATR period (bars)
input int              InpBandsPeriod       = 20;           // Bollinger period (bars)

input group "=== Confirm ==="
input int              InpHtfEmaPeriod      = 50;            // HTF EMA period (bars)
input bool             InpUseHeikinAshi    = true;          // Require Heikin-Ashi confirm

input group "=== Risk & Sizing ==="
input double           InpRiskPercent       = 0.5;           // Risk per trade (% of effective cap)
input double           InpDailyLossLimitPct = 3.0;           // Daily loss limit (% of effective cap)
input double           InpAtrSlMult         = 2.0;           // SL = ATR * mult (-)
input double           InpAtrTpMult         = 4.0;           // TP = ATR * mult (-)
input int              InpMaxConcurrent      = 1;             // Max concurrent positions (-)

input group "=== Capital Allocation Cap ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable          // Enable capital cap
input double           InpCapitalCapAmount   = 0.0;        // Cap amount ($ real money)
input double           InpCapitalCapFloor    = 50.0;         // Floor below which no new entries ($)

Full source code available on download

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

Tags:ex18061trendfollowpipsgrowthfreemt5xauusd

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_EX18061.mq5
File Size32.3 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100