P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18010 TrendFollow

MT5 Expert Advisor (Open Source) · USDJPY · M15, M5, H1

Pipsgrowth.com EX18010 TrendRider_USDJPY_v2_Adaptive — Dual Hull-MA Consensus Trend Rider, full 12-layer stack.

Overview

Pipsgrowth EX18010 TrendRider is a USDJPY-tuned trend-following EA built around a dual-timeframe Hull Moving Average consensus. The header calls it a 'Dual Hull-MA Consensus Trend Rider' and the entire engine is engineered so that a fast M15 Hull and a slow H1 Hull have to agree on direction before the EA will even consider a position. Where most EAs evaluate a single moving average on a single timeframe, EX18010 reads two distinct Hull MAs from two distinct timeframe buffers (g_closeM15[] and g_closeH1[]), asks both to be rising or falling on the same bar, and only then hands the decision off to confirmation, regime, and risk layers.

Hull MA is implemented inline from close arrays — there is no iHull handle. The HullMAFromArr() function constructs each Hull value as 2 × WMA(period/2) − WMA(period) over the requested lookback window, and HullDir() checks the slope across three consecutive bars (HULL_SLOPE_BARS=2 plus the current bar). A direction is BULL only if h0 > h1 > h2, BEAR only if h0 < h1 < h2, otherwise FLAT. For trend strength the EA leans on ADX(14) with a threshold of InpAdxThreshold=18.0 and a 'strong trend' line at InpADXStrong=28.0 — ADX has to clear 18 before any signal is taken, and the 28-level matters because it drives the regime classification (see below).

Regime is a 7-state classifier (ENUM_REGIME) wired into the UpdateRegime() function. Inputs are ADX, an ATR-percentile over a 100-bar lookback, and a Bollinger Bands (period 20, deviation 2.0) width percentile. The mapping: ADX ≥ 28 → STRONG_TREND, ADX ≥ 18 → WEAK_TREND, BB-width percentile < 0.20 → COMPRESS, BB-width percentile > 0.80 combined with ATR-percentile > 0.80 → EXPAND, ATR-percentile > 0.80 alone → BREAKOUT, BB-width percentile < 0.35 → RANGE, else CHOPPY. The RegimeAllowsEntry() whitelist is just four states — STRONG_TREND, WEAK_TREND, BREAKOUT, EXPAND — and the other three (RANGE, COMPRESS, CHOPPY) block entries outright. This is the EA's anti-whipsaw gate: it will not buy into a quiet market even if Hull is rising.

Confirmation is delivered by ConfirmBuy() and ConfirmSell(). A buy requires the bid to be above the closed-bar H1 EMA(50) (the g_htfEma[1] handle from iMA(HTF_TIMEFRAME=PERIOD_H1, HTF_EMA_PERIOD=50)), and either the live EMA is still rising or the live bid is still above the live EMA. RSI(14) has to sit inside a 45–78 band for longs, 22–55 for shorts. If any of those conditions fails, whyN is set to 'HTF_EMA_AGAINST' or 'RSI_OUT_OF_BAND' and the entry is skipped. The signal/confirm pair is computed on the closed bar (g_lastEntryBar guard), so the EA never trades on an unfinished candle.

Stop loss and take profit are ATR-multiples: SL = 1.5 × ATR(14), TP = 2.5 × ATR(14), which gives an R:R of 1:1.67 on the entry. A InpMinRR=1.2 filter is also baked into ManageEntries() — if the projected TP distance is not at least 1.2 × the projected SL distance, the trade is dropped. Lot sizing is fixed-fractional off g_effectiveCap (the active capital cap, see below) at InpRiskPercent=0.5% per trade, via CalcLots() which divides the dollar risk by the stop distance in ticks and clamps the result to the broker's volume step/min/max.

Capital is gated by InpCapAmount (default 0.0 = no cap, the EA trades the full account equity) and InpCapFloor=50.0 USD (entries blocked if equity is below the floor). The capital cap input is a USD-equity ceiling: if you set it to 5000 the EA only ever sizes off the lesser of 5000 or the live equity, which makes prop-firm allocations trivial. The NoTradeGates() function also enforces a daily 3% loss limit and a weekly 6% loss limit (both computed from the magic's own realized PnL via SumRealized()), a 3-consecutive-losses cooldown of 6 hours, max-open-positions of 5, a session window of 00:00–21:00 server time, and a spread gate that blocks entries when spread > 30% of ATR(14). Saturday/Sunday is hard-blocked.

Open-position management runs every tick through ManageOpen(). Three soft-exit protections are stacked: a break-even move that ratchets SL to entry + 0.1 × ATR once profit exceeds 1.0 × ATR, an ATR trailing stop that activates at +1.5 × ATR profit and runs at 1.0 × ATR behind bid/ask (only ratchets in the favorable direction), and a 50% partial close that fires when price reaches halfway to TP (only when remaining volume is at least 1.5 × volMin). Three hard exits sit on top: a volatility-spike exit that closes any in-profit position when ATR(14) exceeds 2.6 × its 20-bar average, a stochastic exit (K crossing D from the overbought/oversold side, periods 14/3/3, levels 80/20), and an opposite-Hull exit that closes a long when the fast M15 Hull flips to BEAR. All three hard exits are gated by profitDist >= 0 — they never cut a loss, only protect a winner.

Pyramiding is wired in (up to 5 levels, spaced at 1.0 × ATR apart) but disabled by default — InpPyramidEnable=false. Weekend protection is a hard flatten at Friday 20:00 server time via ShouldCloseForWeekend(). The 3-retry TryClose_EX18010, TryClosePartial_EX18010, and TryModify_EX18010 functions each retry with 200ms / 100ms sleeps on requotes, price-off, timeout, and price-changed retcodes before giving up. Filling mode is auto-detected: FOK if the broker permits it, otherwise IOC, otherwise RETURN.

OnTester() returns (netProfit × max(0.01, profitFactor)) / (1 + balanceDDpct) with a 30-trade minimum, so the strategy is judged in the optimizer on a profit-per-unit-of-drawdown basis rather than raw net. The InpDryRun input defaults to true — out of the box the EA logs DRYRUN BUY/SELL/MODIFY/CLOSE lines to the journal instead of placing orders, which is the safest way to validate on a new broker before going live. The lot-size calc, regime classifier, and signal logic all run identically in dry-run; only the order sends are stubbed.

The 12-layer stack the header advertises maps cleanly: REGIME (7-state classifier), SIGNAL (dual Hull consensus + ADX), ENTRY (closed-bar gate, INIT vs PYRAMID tags), CONFIRM (H1-EMA50 + RSI band), NO-TRADE (8 gates incl. capital floor, loss limits, cooldown, spread, session, weekend, max-positions, regime), CAPITAL CAP (USD-equity ceiling with floor), RISK (0.5% fractional off effective cap), SIZING (CalcLots with ClampVolume to broker step), MANAGE (BE + trail + partial TP), EXIT (opp-Hull, stoch, vol-spike), SCALING (pyramid OFF by default), and OnTester (custom criterion). On USDJPY M15 with the default inputs, the EA reads a low-ADX Asia session as CHOPPY and refuses to trade, then engages STRONG_TREND once London opens and ADX clears 28. The dual-Hull design is the EX18010 signature — distinct from ex18009's H1 triple-EMA stack, ex18004's 7-state regime with HTF agreement, and the more aggressive 5-way confirmation used in ex18007.

Strategy Deep Dive

Each tick the EA refreshes two close arrays — g_closeM15[] from the working timeframe and g_closeH1[] from HULL_SLOW_TF=PERIOD_H1 — and feeds them into HullMAFromArr() to compute inline Hull MAs (2×WMA(p/2) − WMA(p)) for periods 30 and 70 respectively. HullDir() then checks each Hull for a strict three-bar slope (h0 > h1 > h2 for BULL, h0 < h1 < h2 for BEAR), and a signal is only emitted when both timeframes agree AND ADX(14) clears the 18.0 threshold. Confirmation runs the candidate through H1-EMA(50) agreement, RSI(14) band 45–78/22–55, and a closed-bar guard, and ManageEntries() size- and SL/TP-frames the order with 0.5% of g_effectiveCap at risk. Open positions are shepherded by ManageOpen() through break-even at +1×ATR, ATR-trail at +1.5×ATR, 50% partial at 50% TP-distance, and three profit-only hard exits: opposite-Hull flip, stochastic overbought/oversold cross, and ATR(14) > 2.6× its 20-bar average. The 7-state regime classifier (ADX + ATR-percentile + BB-width) gates entries to STRONG_TREND, WEAK_TREND, BREAKOUT, EXPAND only, and NoTradeGates() additionally enforces a 3% daily / 6% weekly loss cap, a 6-hour cooldown after 3 consecutive losses, a USD-equity capital cap with a $50 floor, max 5 open positions, and a Friday 20:00 weekend flatten.

Entry Signal

Entries require a dual-Hull consensus: the fast M15 Hull (period 30, computed inline as 2×WMA(15) − WMA(30)) and the slow H1 Hull (period 70) must both slope up for a long, both slope down for a short, and ADX(14) must clear the 18.0 threshold. The signal then has to clear three confirmation gates: bid above the H1 EMA(50) with a still-rising or still-supportive EMA, RSI(14) inside 45–78 (long) or 22–55 (short), and the entry happens on a closed bar only. Regime must be STRONG_TREND, WEAK_TREND, BREAKOUT, or EXPAND — RANGE, COMPRESS, and CHOPPY block entries outright.

Exit Signal

Three hard exits, all profit-gated (never cut a loss): opposite-Hull flip (fast M15 Hull going BEAR closes longs), stochastic overbought/oversold cross (K crossing D from 80/20, periods 14/3/3), and volatility-spike exit (ATR(14) above 2.6× its 20-bar average). Soft exits stack on top: break-even at +1.0×ATR profit moves SL to entry+0.1×ATR, ATR trail starts at +1.5×ATR profit and runs at 1.0×ATR, and a 50% partial close fires at 50% of TP distance. Friday 20:00 server time hard-flattens everything for the weekend.

Stop Loss

Stop loss is a fixed 1.5 × ATR(14) from entry, recomputed every tick and always ratcheted forward by the break-even and trailing-stop logic. The SL also has to respect the broker's stops-level minimum via RespectStopsBuySL/RespectStopsSellSL. The InpMinRR=1.2 filter additionally drops any setup where the projected TP distance is less than 1.2 × the projected SL distance.

Take Profit

Take profit is a fixed 2.5 × ATR(14) from entry, giving a default 1.67:1 reward-to-risk ratio. Half of the position is closed at 50% of the TP distance (a 50% partial TP) so the trade effectively secures some profit before the final leg. The hard TP is checked in the standard MQL5 way on the order itself.

Best For

USDJPY traders running M15 with the option to step up to H1, on a broker that reports clean 5-digit pricing and supports FOK or IOC filling. Minimum recommended balance is $100, but the 0.5% per-trade risk and the $50 capital floor mean the EA scales gracefully from a $100 micro account to a $5,000 prop-firm allocation (set InpCapAmount to enforce the cap). Best in the London and New York sessions when ADX tends to clear 18, and the 3%/6% daily/weekly loss limits make it suitable for prop-firm challenge accounts. Avoid running it through the Asian session on Friday — the 20:00 server-time flatten will frequently close profitable shorts at the worst possible moment.

Strategy Logic

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

Family: TrendFollow Magic: 22218010 Version: 2.00

BRIEF: Dual Hull-MA Consensus Trend Rider — DUAL inline Hull-MA consensus (fast M15 + slow H1). Fast/slow Hull slope must agree AND price must hold on the side AND ADX must be above threshold. Entries confirmed by HTF EMA agreement + RSI not-extreme + closed-bar. Full regime layer (ADX+ATR-pctile+BB-width) gates entries and sizing/trail. Capital-allocation-cap, ATR-trail, BE, partial TP, pyramid OFF by default, stochastic/volatility exit, daily/weekly loss limits, no-trade gates, broker- portable fills. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • ATR
  • ADX
  • RSI
  • BB
  • HTFema
  • Stoch

KEY FUNCTIONS:

  • NormPrice()
  • ClampVolume()
  • StopsLevelPrice()
  • RespectStopsBuySL()
  • RespectStopsSellSL()
  • LogFail()
  • CountPositions()
  • SumRealized()
  • WMA()
  • HullMAFromArr()
  • UpdateRegime()
  • RegimeAllowsEntry()
  • ...and 19 more

INTERNAL CONSTANTS (30 total):

  • ATR_PERIOD = 14 // ATR period
  • ADX_PERIOD = 14 // ADX period
  • RSI_PERIOD = 14 // RSI period
  • BB_PERIOD = 20 // Bollinger period
  • BB_DEVIATION = 2.0 // Bollinger deviation
  • ATR_PCT_LOOKBACK = 100 // ATR-percentile lookback
  • HTF_EMA_PERIOD = 50 // HTF EMA period (HTF timeframe)
  • HTF_TIMEFRAME = PERIOD_H1 // HTF timeframe for slow Hull + EMA confirm
  • PYRAMID_MAX_LEVELS = 5 // Pyramid hard cap
  • PYRAMID_ATR_MULT = 1.0 // Pyramid spacing (xATR)
  • MAX_BARS_HOLD = 0 // Time-based exit (0 = disabled)
  • BE_ATR_MULT = 1.0 // Break-even trigger (xATR)
  • BE_BUFFER_ATR = 0.1 // Break-even buffer (xATR)
  • TRAIL_ATR_MULT = 1.5 // ATR trail start (xATR profit)
  • TRAIL_ATR_DIST = 1.0 // ATR trail distance (xATR)
  • ...and 15 more

INPUT PARAMETERS (20 total across 5 groups):

  • [=== Identity ===] InpMagicNum = 22218010 // Magic number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18010" // Trade comment
  • [=== Identity ===] InpSlippagePts = 30 // Max slippage (points)
  • [=== Identity ===] InpDryRun = true // Dry-run (no live sends)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk % per trade (of effective cap)
  • [=== Risk & Sizing ===] InpDailyLossPct = 3.0 // Daily loss limit %
  • [=== Risk & Sizing ===] InpWeeklyLossPct = 6.0 // Weekly loss limit %
  • [=== Risk & Sizing ===] InpMaxPositions = 5 // Max concurrent positions (pyramid cap)
  • [=== Risk & Sizing ===] InpCooldownLosses = 3 // Cooldown after N losses (count)
  • [=== Risk & Sizing ===] InpKillSwitch = false // Kill switch (flatten+halt)
  • [=== Capital Allocation Cap ===] InpCapAmount = 0.0 // Capital cap amount (USD equity)
  • [=== Capital Allocation Cap ===] InpCapFloor = 50.0 // Capital floor (USD, block entries)
  • [=== Hull Signal ===] InpHullFastPeriod = 30 // Hull Fast (M15) period
  • [=== Hull Signal ===] InpHullSlowPeriod = 70 // Hull Slow (H1) period
  • [=== Hull Signal ===] InpAdxThreshold = 18.0 // ADX threshold for trend strength
  • [=== Hull Signal ===] InpADXStrong = 28.0 // ADX for StrongTrend regime
  • [=== Exit / Manage ===] InpSLMultiplier = 1.5 // Stop loss (xATR)
  • [=== Exit / Manage ===] InpTPMultiplier = 2.5 // Take profit (xATR)
  • [=== Exit / Manage ===] InpMinRR = 1.2 // Minimum reward:risk ratio
  • [=== Exit / Manage ===] InpPyramidEnable = false // Enable pyramiding (off by default)
Pseudocode
// Pipsgrowth EX18010 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Dual Hull-MA Consensus Trend Rider — DUAL inline Hull-MA consensus (fast M15 + slow H1). Fast/slow Hull slope must agree AND price must hold on the side AND ADX must be above threshold. Entries confirmed by HTF EMA agreement + RSI not-extreme + closed-bar. Full regime layer (ADX+ATR-pctile+BB-width) gates entries and sizing/trail. Capital-allocation-cap, ATR-trail, BE, partial TP, pyramid OFF by default, stochastic/volatility exit, daily/weekly loss limits, no-trade gates, broker- portable fills. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

ON_INIT:
    Create indicator handles: ATR, ADX, RSI, BB, HTFema, Stoch
    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:
USDJPY
Optimized Timeframes:
M15M5H1

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
InpMagicNum22218010Magic number
InpTradeComment"Psgrowth.com Expert_18010"Trade comment
InpSlippagePts30Max slippage (points)
InpDryRuntrueDry-run (no live sends)
InpRiskPercent0.5Risk % per trade (of effective cap)
InpDailyLossPct3.0Daily loss limit %
InpWeeklyLossPct6.0Weekly loss limit %
InpMaxPositions5Max concurrent positions (pyramid cap)
InpCooldownLosses3Cooldown after N losses (count)
InpKillSwitchfalseKill switch (flatten+halt)
InpCapAmount0.0Capital cap amount (USD equity)
InpCapFloor50.0Capital floor (USD, block entries)
InpHullFastPeriod30Hull Fast (M15) period
InpHullSlowPeriod70Hull Slow (H1) period
InpAdxThreshold18.0ADX threshold for trend strength
InpADXStrong28.0ADX for StrongTrend regime
InpSLMultiplier1.5Stop loss (xATR)
InpTPMultiplier2.5Take profit (xATR)
InpMinRR1.2Minimum reward:risk ratio
InpPyramidEnablefalseEnable pyramiding (off by default)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18010.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18010 TrendRider_USDJPY_v2_Adaptive — Dual Hull-MA Consensus Trend Rider, 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>

//========================== TUNABLE CONSTANTS ============================
// (kept out of the input surface to satisfy the 12-22 input cap)
#define ATR_PERIOD          14      // ATR period
#define ADX_PERIOD          14      // ADX period
#define RSI_PERIOD          14      // RSI period
#define BB_PERIOD           20      // Bollinger period
#define BB_DEVIATION        2.0     // Bollinger deviation
#define ATR_PCT_LOOKBACK    100     // ATR-percentile lookback
#define HTF_EMA_PERIOD      50      // HTF EMA period (HTF timeframe)
#define HTF_TIMEFRAME       PERIOD_H1 // HTF timeframe for slow Hull + EMA confirm
#define PYRAMID_MAX_LEVELS  5       // Pyramid hard cap
#define PYRAMID_ATR_MULT    1.0     // Pyramid spacing (xATR)
#define MAX_BARS_HOLD       0       // Time-based exit (0 = disabled)
#define BE_ATR_MULT         1.0     // Break-even trigger (xATR)
#define BE_BUFFER_ATR       0.1     // Break-even buffer (xATR)
#define TRAIL_ATR_MULT      1.5     // ATR trail start (xATR profit)
#define TRAIL_ATR_DIST      1.0     // ATR trail distance (xATR)
#define PARTIAL_TP_RATIO    0.50    // Partial TP fraction at TP1
#define SESSION_START_HOUR  0       // Session window start (broker server time)
#define SESSION_END_HOUR    21      // Session window end   (broker server time)
#define MAX_SPREAD_PCT      0.30    // Max spread as fraction of ATR (30%)
#define HULL_SLOPE_BARS     2       // Hull rising/falling lookback bars
#define STOCH_K             14      // Stochastic %K
#define STOCH_D             3       // Stochastic %D
#define STOCH_SLOWING       3       // Stochastic slowing
#define STOCH_OVERBOUGHT    80.0    // Stochastic overbought
#define STOCH_OVERSOLD      20.0    // Stochastic oversold
#define VOL_SPIKE_MULT      2.6     // ATR-spike exit multiplier
#define HULL_SLOW_TF        PERIOD_H1 // Hull slow timeframe
#define WEEKEND_CLOSE_HOUR  20      // Friday close-all hour
#define STOCH_EXIT_ENABLE   true    // Stochastic-exit toggle
#define VOL_EXIT_ENABLE     true    // Volatility-spike-exit toggle

//+------------------------------------------------------------------+
//| ENUMERATIONS                                                     |
//+------------------------------------------------------------------+
enum ENUM_TRADE_DIRECTION
{
   TRADE_BUY_ONLY  = 0,   // Buy Only
   TRADE_SELL_ONLY = 1,   // Sell Only
   TRADE_BOTH      = 2    // Both Directions
};

enum ENUM_REGIME
{
   REG_STRONG_TREND = 0,  // StrongTrend
   REG_WEAK_TREND   = 1,  // WeakTrend

Full source code available on download

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

Tags:ex18010trendfollowpipsgrowthfreemt5usdjpy

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_EX18010.mq5
File Size41.0 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M15M5H1
Currency Pairs
USDJPY
Min. Deposit$100