P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18056 TrendFollow

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

Pipsgrowth.com EX18056 Hull2EA_Lite_v2 — Dual Hull-MA slope consensus with regime gate, full 12-layer stack.

Overview

EX18056 is a single-symbol Hull-MA slope consensus engine that turns a two-line moving-average agreement into a trend-following bias. The engine keeps no manual pivot lists, no overnight position bookkeeping, and no chart-object drawing — the only state that survives between bars is the last signal bar time, which is the gate that prevents a single closed bar from firing twice in the same direction.

The signal itself is built in two layers. The first layer is an inline Hull Moving Average constructed from raw LWMA handles: a fast composite of period 20 (WMA(10) and WMA(20) blended with a sqrt(20) final smoother) and a slow composite of period 50 (WMA(25) and WMA(50) with a sqrt(50) smoother). The HullSignal() function reads both composites, takes the difference between the last closed value and the value InpHullLookback (default 3) closed bars earlier, and returns +1 only when both slopes point up, -1 only when both slopes point down, and 0 when the two Hulls disagree. Confidence is derived from the magnitude of the combined slope expressed in pips. There is no per-bar re-tinting and no candle pattern — slope agreement is the entire trigger.

The second layer is a regime gate. DetectRegime() samples ADX(14) and a 50-bar ATR percentile plus the growth ratio of Bollinger Band(20, 2) width, and assigns one of seven states: REG_STRONG_TREND (ADX ≥ 30 and ATR-pctile ≥ 60), REG_WEAK_TREND (ADXInpAdxMin=20 and ATR-pctile ≥ 40), REG_BREAKOUT (BB-width growth > 1.20 and ATR-pctile ≥ 65), REG_EXPAND (BB-width growth > 1.05 and ATR-pctile ≥ 50), REG_COMPRESS (BB-width growth < 0.85), REG_RANGE (ADX < 20 and ATR-pctile < 30), and REG_CHOPPY (everything else). The EntrySignal() function silently swallows the Hull signal whenever the regime is CHOPPY, RANGE, or COMPRESS, so the EA never tries to trade flat, mean-reverting, or volatility-collapsing tape.

Confirmation runs after the signal survives the regime filter. ConfirmEntry() reads the H1 EMA(50) value (the HTF handle is wired to g_InpHullHTF, which falls back to PERIOD_H1 because the input value 8 does not match any case in MapTimeframeInt) and rejects a long if the ask is below it, or a short if the bid is above it. It also blocks longs when RSI(14) is above 75 and shorts when RSI is below 25, and verifies that the live ATR-implied reward-to-risk ratio (InpAtrTPmult/InpAtrSLmult = 3.0/1.8 = 1.67) is at or above the InpMinRR=1.3 floor. Spread is rejected above 35 points. The HullSignal/EntrySignal/ConfirmEntry stack is what makes the engine feel selective on M5 gold without over-trading.

Position management is broken into three routines that run on every tick. ManagePositions() ratchets the stop with two parallel layers: a one-shot break-even that fires when unrealized profit reaches 1R and walks the stop to open plus 0.1R (offset), and a 2.5×ATR(14) forward-only trail that only ever tightens. ExitOnOpposite() closes any open position immediately when the live Hull signal flips sign, and ExitOnRegimeChange() force-closes everything whenever the regime becomes CHOPPY or RANGE, regardless of profit. There is no partial-close pathway, no time-stop, and no breakeven re-trigger — the BE is a one-shot per position.

Risk is bounded by four independent caps. Position sizing is 0.5% of effective capital per trade. A 3% daily realized-loss limit (counted off DEAL_PROFIT + DEAL_SWAP + DEAL_COMMISSION for this magic) and a 6% weekly realized-loss limit block new entries when hit. Max concurrent positions is 3, and max concurrent on this symbol is also 3, so the engine never crowds a single name. The optional capital cap (InpCapitalCapAmount=0 means off by default) shrinks the working capital to the smaller of the cap and account equity, and a $50 floor refuses to open new positions when effective capital falls below it. OrderCalcMargin is called before every send, so a margin shortfall is detected before the request reaches the broker.

Execution details that traders care about: InpDryRun is true by default — the EA prints the intended order instead of sending it until you flip the switch. Slippage is 30 points, the order comment is hardcoded to "Psgrowth.com Expert_18056", and a single transient retry is issued on REQUOTE or TIMEOUT. Pyramiding (InpPyramidEnabled) is off by default, but when enabled it requires the latest position to be at least 1.5×ATR in profit and caps total open positions at 3.

The time and session filters are conservative. Entries are blocked when the broker server hour is below 1 or at/above 23, when the day of week is Sunday or Saturday, or when Friday's server hour is 21 or later. Combined with the regime gate, the EA effectively concentrates its trading inside the most liquid part of the week and refuses to roll a position into the Sunday gap or the post-Friday close.

Expectations in backtest: with the 7-state regime filter, expect relatively few trades per week on M5 XAUUSD — most of the week is filtered out as CHOPPY or RANGE. The trades that do fire will be longer than a typical M5 trend bot because the 1R BE plus 2.5×ATR trail give runners room to breathe. The OnTester formula (net * pf) / (1 + dd) requires at least 30 trades to score non-zero, so short optimization windows will be heavily penalized. Use the tester with the full 90-day window or longer, with every tick or 1-minute OHLC, and the spread modeled as variable.

Pyramiding is the most interesting configurable behavior beyond the core signal. With InpPyramidEnabled true, the engine may add a second or third position in the same direction, but only when the existing position is already 1.5×ATR in profit. This is not a grid — each pyramid is a brand-new risk allocation that has to pass the regime gate, the HTF-EMA confirm, the RSI limit, the spread cap, and the daily/weekly loss limits. Most traders will leave it off; it is provided for users who want the option to scale into trends.

Strategy Deep Dive

On every tick, the EA rebuilds the inline Hull composites for the last InpHullFastPeriod+10 and InpHullSlowPeriod+10 closed bars by blending the raw LWMA(period/2) and LWMA(period) handles, applies a sqrt(period) linear smoother, and diffs the last value against the InpHullLookback-prior value to get a slope. HullSignal() returns +1, -1, or 0 from the two-line agreement. DetectRegime() reads ADX(14), a 50-bar ATR percentile, and a Bollinger-Band width growth ratio to bucket the market into one of seven states; EntrySignal() drops the trade whenever the regime is CHOPPY, RANGE, or COMPRESS. Surviving signals pass through ConfirmEntry(), which checks H1 EMA(50) agreement, RSI(14) bounds, the ATR-implied R:R floor of 1.3, and the 35-point spread cap. Sizing is 0.5% of effective capital via CalcLots(), and OrderCalcMargin is called before send. ManagePositions() runs the 1R→BE+0.1R and 2.5×ATR trail every tick; ExitOnOpposite() and ExitOnRegimeChange() force-closed on signal flip and on CHOPPY/RANGE.

Entry Signal

Entry triggers when both the inline fast Hull(20) and slow Hull(50) have a positive slope over the last InpHullLookback=3 closed bars (or both negative for shorts), the regime classifier returns STRONG_TREND, WEAK_TREND, BREAKOUT, or EXPAND (CHOPPY/RANGE/COMPRESS are filtered out), the live price is on the correct side of the H1 EMA(50), RSI(14) is below 75 for longs or above 25 for shorts, the implied reward-to-risk ratio meets the InpMinRR=1.3 floor, and the spread is at or below 35 points. The same closed bar never fires twice because the signal-bar timestamp is cached.

Exit Signal

Exits are driven by the Hull signal flip (ExitOnOpposite closes a long the moment both Hulls slope negative and a short the moment both slope positive) and by the regime classifier — when DetectRegime returns CHOPPY or RANGE, every open position on this magic is force-closed regardless of profit. There is no partial-close pathway, no time-based stop, and no basket profit target. The trailing stop is forward-only and only tightens.

Stop Loss

Per-trade stop is set at 1.8×ATR(14) below the entry ask for longs or above the entry bid for shorts, and is always clamped to respect the broker's stops-level minimum. A one-shot break-even fires when unrealized profit reaches 1R and walks the stop to open + 0.1R, and a 2.5×ATR(14) forward-only trail tightens on every tick thereafter. The stop can never loosen.

Take Profit

Per-trade take-profit is set at 3.0×ATR(14) above the entry for longs or below the entry for shorts, which gives a fixed ~1.67 R:R against the 1.8×ATR stop. The TP is not split — there is no partial-close or scaled exit; the position is held until the trailing stop, the opposite Hull signal, or the regime-change close takes it out.

Best For

Best on M5 XAUUSD with a $100 minimum deposit and a MEDIUM risk profile. The 0.5% per-trade risk and 3% daily / 6% weekly realized-loss caps keep the EA conservative, but the regime gate concentrates trading into the most directional hours of the London and New York sessions — Friday after 21:00 server, weekends, and the 23:00-01:00 illiquid window are all blocked. Use a low-spread ECN or RAW account (the 35-point spread cap is fine for gold, but thinner spreads improve fill quality on the BE+trail ratchet).

Strategy Logic

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

Family: TrendFollow Magic: 22218056 Version: 2.00

BRIEF: Dual inline Hull-MA (fast/slow) slope-color consensus drives trend-following entries; ADX/ATR-pct/BB-width regime gate filters choppy/range; HTF-EMA + RSI confirm; ATR-based SL, break-even + ATR trailing, partial TP, opposite-signal & regime-change exits; optional profit-only pyramiding. Capital-allocation cap and per-magic daily-loss isolation. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • FastRaw1
  • FastRaw2
  • SlowRaw1
  • SlowRaw2
  • Adx
  • Atr
  • Bands
  • HtfEma
  • Rsi

KEY FUNCTIONS:

  • HullSignal()
  • EntrySignal()
  • ConfirmEntry()
  • NoTradeReason()
  • EffectiveCapital()
  • EARealizedPnL()
  • DayStart()
  • WeekStart()
  • NormalizeLots()
  • CalcLots()
  • RespectStops()
  • OpenOrder()
  • ...and 9 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (22 total across 6 groups):

  • [=== General ===] InpDryRun = true // Dry-run (no live orders)
  • [=== General ===] InpKillSwitch = false // Global kill switch
  • [=== General ===] InpMagic = 22218056 // Magic number
  • [=== General ===] InpTradeComment = "Psgrowth.com Expert_18056" // Trade comment
  • [=== Hull Signal ===] InpHullFastPeriod = 20 // Fast Hull period (bars)
  • [=== Hull Signal ===] InpHullSlowPeriod = 50 // Slow Hull period (bars)
  • [=== Hull Signal ===] InpHullLookback = 3 // Slope confirm bars
  • [=== Hull Signal ===] InpHullHTF = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF Hull timeframe
  • [=== Regime Gate ===] InpAdxMin = 20.0 // Min ADX for trend
  • [=== Regime Gate ===] InpAtrPctLookback = 50 // ATR-pctile lookback (bars)
  • [=== Confirm ===] InpHtfEmaPeriod = 50 // HTF EMA period (bars)
  • [=== Confirm ===] InpMinRR = 1.3 // Min reward:risk ratio
  • [=== Confirm ===] InpMaxSpreadPts = 35 // Max spread (points)
  • [=== Risk & Sizing ===] InpCapitalCapAmount = 0.0 // Capital cap amount ($)
  • [=== Risk & Sizing ===] InpCapitalCapFloor = 50.0 // Capital floor ($)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (%)
  • [=== Risk & Sizing ===] InpDailyLossPct = 3.0 // Daily loss limit (%)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 3 // Max concurrent trades
  • [=== SL/TP & Manage ===] InpAtrSLmult = 1.8 // SL = ATR * mult
  • [=== SL/TP & Manage ===] InpAtrTPmult = 3.0 // TP = ATR * mult
  • [=== SL/TP & Manage ===] InpTrailATRmult = 2.5 // Trail ATR mult
  • [=== SL/TP & Manage ===] InpPyramidEnabled = false // Pyramiding enabled
Pseudocode
// Pipsgrowth EX18056 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Dual inline Hull-MA (fast/slow) slope-color consensus drives trend-following entries; ADX/ATR-pct/BB-width regime gate filters choppy/range; HTF-EMA + RSI confirm; ATR-based SL, break-even + ATR trailing, partial TP, opposite-signal & regime-change exits; optional profit-only pyramiding. Capital-allocation cap and per-magic daily-loss isolation. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

ON_INIT:
    Create indicator handles: FastRaw1, FastRaw2, SlowRaw1, SlowRaw2, Adx, Atr, Bands, HtfEma, Rsi
    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
InpDryRuntrueDry-run (no live orders)
InpKillSwitchfalseGlobal kill switch
InpMagic22218056Magic number
InpTradeComment"Psgrowth.com Expert_18056"Trade comment
InpHullFastPeriod20Fast Hull period (bars)
InpHullSlowPeriod50Slow Hull period (bars)
InpHullLookback3Slope confirm bars
InpHullHTF8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF Hull timeframe
InpAdxMin20.0Min ADX for trend
InpAtrPctLookback50ATR-pctile lookback (bars)
InpHtfEmaPeriod50HTF EMA period (bars)
InpMinRR1.3Min reward:risk ratio
InpMaxSpreadPts35Max spread (points)
InpCapitalCapAmount0.0Capital cap amount ($)
InpCapitalCapFloor50.0Capital floor ($)
InpRiskPercent0.5Risk per trade (%)
InpDailyLossPct3.0Daily loss limit (%)
InpMaxConcurrent3Max concurrent trades
InpAtrSLmult1.8SL = ATR * mult
InpAtrTPmult3.0TP = ATR * mult
InpTrailATRmult2.5Trail ATR mult
InpPyramidEnabledfalsePyramiding enabled
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18056.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18056 Hull2EA_Lite_v2 — Dual Hull-MA slope consensus with regime gate, full 12-layer stack."

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

//============================ INPUTS ================================
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)
   {
      case 1: return PRICE_CLOSE;
      case 2: return PRICE_OPEN;
      case 3: return PRICE_HIGH;
      case 4: return PRICE_LOW;
      case 5: return PRICE_MEDIAN;
      case 6: return PRICE_TYPICAL;
      case 7: return PRICE_WEIGHTED;
      default: return PRICE_CLOSE;
   }
}
ENUM_TIMEFRAMES g_InpHullHTF = PERIOD_H1;
input group "=== General ==="
input bool           InpDryRun           = true;       // Dry-run (no live orders)
input bool           InpKillSwitch       = false;      // Global kill switch
input ulong          InpMagic            = 22218056;    // Magic number
input string         InpTradeComment     = "Psgrowth.com Expert_18056"; // Trade comment

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;

Full source code available on download

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

Tags:ex18056trendfollowpipsgrowthfreemt5xauusd

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