Pipsgrowth EX18022 TrendFollow
MT5 Expert Advisor (Open Source) · USDJPY · M15, M5, M30
Pipsgrowth.com EX18022 USDJPYm — EMA(9/21) cross + Hull MA + RSI + MACD + ADX, full 12-layer stack.
Overview
Pipsgrowth EX18022 TrendFollow is an MT5 Expert Advisor that takes a textbook EMA(9/21) crossover and surrounds it with enough confirmation logic that a single bar of noise cannot reach the order ticket. The entry trigger is the crossover itself — bullish when the 9-EMA closes above the 21-EMA on the current completed bar, bearish on the mirror — but every other condition that could let a fake signal through is closed. Five independent votes must agree, a higher-timeframe agreement check has to clear, and a regime classifier has to declare the market trendable before the EA will send an order. The result is a 12-layer trend system that filters on the way in and manages on the way out, with no martingale, no grid, and no scaling by default.
The signal stack is the most distinctive part of EX18022. On top of the EMA(9/21) cross the EA inlines a full Hull Moving Average implementation rather than calling a native HMA indicator — it builds HMA(20) and HMA(50) from LWMA halves and fulls and adds an HMA_SLOPE_BARS=3 slope check on each. The long vote requires HMA(20) rising, HMA(50) rising, and HMA(20) above HMA(50); the short vote mirrors. RSI(14) is used as a side filter rather than a trigger: longs require RSI below the InpRSIOb threshold (default 70) and shorts require RSI above InpRSIOs (default 30). MACD(12,26,9) contributes its histogram sign — long only when main minus signal is positive, short only when negative. ADX(14) gates trend strength with InpAdxThreshold=20 and requires +DI above -DI for longs and the opposite for shorts. The HTF agreement layer runs on PERIOD_H1, comparing close to a 50-EMA and checking that the H1 Hull(50) slope agrees with the direction; this is the layer that most filters out counter-trend attempts during the day.
The regime classifier is a 7-state engine that decides whether the market is even worth trading. It looks at three values: ADX(14) main, the current ATR(14) percentile rank within a 200-bar rolling window, and Bollinger Band width (period 20, deviation 2.0) expressed as a fraction of the middle band. From those it produces one of: StrongTrend (ADX at least 1.5x threshold AND ATR-pctile at least 0.70), WeakTrend (ADX at threshold AND ATR-pctile at least 0.50), Expand (ATR-pctile at least 0.85 with positive BB-width), Compress (ATR-pctile at most 0.15), Breakout (ATR-pctile at least 0.65 with elevated BB-width), Range (ADX at most half threshold), or Choppy. Entries are allowed only in StrongTrend, WeakTrend, Breakout, and Expand; a flip into Range, Compress, or Choppy forces any open position to close via the RegimeAllowsEntry check that runs on every manage tick.
Risk control is the part of the code that runs first on every entry attempt. The EffectiveCapital() function returns account equity unless InpCapitalCapAmount is set, in which case it caps the equity at that dollar amount (so a $200 account with cap=100 treats itself as a $100 account for sizing and loss-limit purposes). InpCapitalCapFloor=50 blocks any new trade if effective capital falls below $50. The RealizedPnL() helper walks the deal history filtered by magic 22218022 and computes profit plus swap minus absolute commission. Three loss gates read from it: a daily realized loss limit of 3% of effective capital, a weekly realized loss limit of 6%, and a consecutive-loss cooldown of 5 bars (the cooldown constant COOLDOWN_BARS) when the last two closed deals were both losses. The CountConsecLosses() function scans the most recent 10 deals in reverse and counts losses until the first winner, and the cooldown engages only when that count reaches InpCooldownAfterLoss=2.
Position sizing follows the classic risk-per-stop formula. For each signal the EA computes an initial stop as the worse of (a) the recent 14-bar swing low/high and (b) entry ± 1.5 × ATR(14), then floors the result against the broker stops-level distance. Risk money is effective_capital × InpRiskPercent / 100 (default 0.50%) and lots are RiskMoney / (stop_dist / TickSize) × TickValuePerLot, clamped to the symbol lot step and to a minimum of VolMin(). OrderCalcMargin is then called to verify that free margin covers the request; if not, the entry is skipped with a log line. There is no fixed take-profit at the order level — the EA passes tp=0 and lets its manage functions close the position adaptively. The minimum reward-to-risk ratio is enforced at entry via InpMinRR=1.20, so a 1.5:1 trade is allowed but a 0.9:1 is not.
Trade management runs on every tick and runs five separate exit paths. The Chandelier-style trailing stop ratchets the stop to high_since − InpChandelierK × ATR (default 3.0x) for longs and the mirror for shorts, only ever ratcheting in the profitable direction. A break-even move fires once when MFE reaches InpBE_R_Mult=1.0 times the entry ATR, lifting the stop to entry plus one R. A partial close of 50% fires at the same MFE threshold (the TP1_R_MULT=1.0 constant), locking in half the position. The final close trigger is TP_FINAL_R_MULT=3.0 times the entry ATR in MFE, which exits the remaining half. Time-based exit is a hard 200 bars in trade (InpMaxBarsInTrade). Opposite-signal exit checks whether the EMA(9/21) cross has flipped on the most recent closed bar. Regime change and session end both force a close — IsWithinSession() returns true only for server hours 2 through 21, so any position still open at hour 21 is force-closed.
The no-trade gate that runs before any order is sent is exhaustive and explicit. In order, it blocks on: kill switch active, effective capital below the $50 floor, daily realized loss has hit the 3% threshold, weekly loss has hit 6%, current spread exceeds InpMaxSpreadPoints=30 points, regime is not in the allowed set, position count is at InpMaxConcurrent=1, current time is before cooldown_until, the same bar would receive a second entry (the last_entry_bar == last_bar_time check), current server hour is outside the 2-21 window, or the most recent close is non-positive. The panel label in the top-left corner of the chart displays the active block reason plus the current EMA, RSI, ADX, ATR-percentile, and regime string.
The MT5 tester criterion is the same shape used across the TrendFollow family: (net_profit × profit_factor) / (1 + balance_ddrel_percent), with a hard minimum of 30 trades required for a non-zero return. A strategy that makes money but with low PF or high drawdown will score low; a strategy that has high PF and low DD will score high. The function lives at the bottom of the source as OnTester() and the constants are pulled directly from TesterStatistics().
The OpenTrade() function also includes a retry path for transient order failures: on a TRADE_RETCODE_REQUOTE, TRADE_RETCODE_PRICE_OFF, or TRADE_RETCODE_TIMEOUT retcode the EA re-sends the same order once without changing parameters. TryClose_EX18022, TryClosePartial_EX18022, and TryModify_EX18022 wrap the standard CTrade calls with the same three-attempt retry loop, sleeping 200ms on transient errors between attempts. The order comment is Psgrowth.com Expert_18022 so this EA trades are filterable in the deal history.
For live deployment, EX18022 expects a USDJPY broker with tight spreads (under 30 points at the chosen timeframe — the no-trade gate is unforgiving on this) and accurate tick data. The Strategy Tester reports typically show MEDIUM-risk equity curves with shallow drawdowns, because the 5-vote confirmation and 3:1 final R target combine to favor high-quality signals over trade frequency. Pyramiding is not enabled; only one position per magic 22218022 is ever open at a time, so the EA scales up only by increasing lot size from the risk formula, not by adding to a winner. The InpDryRun=true default means the EA will print its intended actions to the Experts log without sending any real order, which is the recommended first week of operation before switching to live.
Strategy Deep Dive
On every tick the EA refreshes rates, calls ManageOpenPosition to update the trailing stop, break-even, partial, and final-target logic on any open trade, then — when a new bar opens — reads EMA(9/21), HMA(20/50 inlined from LWMA halves), RSI(14), MACD(12,26,9) histogram, ADX(14) with +DI/-DI, Bollinger(20, 2.0) width, and ATR(14) on the closed bar (shift=1). It pushes the new ATR into a 200-bar rolling window for percentile rank, classifies the regime into one of seven states, and — if the regime allows entry and the no-trade gate clears (kill switch, capital floor, daily/weekly loss limits, spread ≤ 30 points, cooldown, max concurrent, session 2-21 server) — runs the 5-vote confirmation with H1 EMA(50) + H1 HMA(50) slope agreement before sizing the lot from 0.5% of effective capital and sending the order.
EX18022 takes long entries when EMA(9) closes above EMA(21) on the completed bar AND HMA(20) and HMA(50) are both rising with HMA(20) > HMA(50), RSI(14) < 70, MACD(12,26,9) histogram is positive, ADX(14) >= 20 with +DI > -DI, and the H1 close is above the H1 50-EMA with the H1 Hull(50) slope agreeing. Shorts are the mirror. A 7-state regime classifier (ADX, ATR-percentile, BB-width) must classify the market as StrongTrend, WeakTrend, Breakout, or Expand before the entry is sent.
Positions close on whichever fires first: MFE reaching 3x entry ATR (the final target), an opposite EMA(9/21) cross on a closed bar, a regime change into Range/Compress/Choppy, server hour crossing 21, or 200 bars in trade. The Chandelier trail at 3.0x ATR(14) ratchets the stop in the profitable direction on every tick.
Initial stop is the worse of the 14-bar swing low/high and entry ± 1.5 × ATR(14), then floored against the broker stops-level distance. After entry the stop ratchets to a 3.0x ATR(14) Chandelier trail; break-even fires at +1R; partial close of 50% at +1R.
No fixed TP at order level — the EA passes tp=0 and lets the manage logic handle it. A 50% partial close fires at +1R MFE and the remaining 50% closes at +3R MFE. The minimum R:R at entry is 1.20.
Best deployed on USDJPY M15 with a $100 minimum account (the $50 capital floor and 0.5% per-trade risk keep drawdowns contained), though the EA also works on M5 and M30. Choose a low-spread ECN broker — the 30-point spread ceiling will gate you out of wide-spread accounts immediately. Run during server hours 2-21, which covers the London session through the New York close for most broker timezones.
Strategy Logic
Pipsgrowth EX18022 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218022
Version: 2.00
BRIEF:
EMA(9/21) close-bar crossover confirmed by inlined Hull MA slope (LTF+HTF), RSI side, MACD histogram sign and ADX strength. Regime gate (ADX+ATR-pctile+BB-width), HTF-EMA agreement, capital-allocation-cap, BE/partial/ATR-trail exits, pyramid OFF by default. Broker-portable, 12-layer, single self-contained. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
TickSize()TickValuePerLot()VolMin()VolMax()VolStep()StopsLevel()SpreadPoints()NormalizePrice()ClampVolume()PushFIFO()PercentRankOf()RecentLow()- ...and 23 more
INTERNAL CONSTANTS (27 total):
EMA_FAST_PERIOD= 9 // FastEMAperiod (signal core)EMA_SLOW_PERIOD= 21 // SlowEMAperiod (signal core)HULL_FAST_PERIOD= 20 // Hull MA fast periodHULL_SLOW_PERIOD= 50 // Hull MA slow periodHTF_PERIOD=PERIOD_H1// Higher timeframe for trend agreementHTF_HULL_PERIOD= 50 //HTFHull MA periodHTF_EMA_PERIOD= 50 //HTFEMAagreement periodRSI_PERIOD= 14 //RSIperiodMACD_FAST= 12 //MACDfastMACD_SLOW= 26 //MACDslowMACD_SIGNAL= 9 //MACDsignalADX_PERIOD= 14 //ADXperiodATR_PERIOD= 14 //ATRperiodATR_PCTILE_WINDOW= 200 //ATR-percentile rolling windowBB_PERIOD= 20 // Bollinger width period- ...and 12 more
INPUT PARAMETERS (20 total across 6 groups):
- [=== Identity ===]
InpMagic=22218022// Magic number (2220000+ExpertID) - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18022" // Trade comment - [=== Identity ===]
InpDryRun=true// Dry-run mode (no real orders) - [=== Identity ===]
InpKillSwitch=false// Kill switch (closes all, blocks new) - [=== Risk & Sizing ===]
InpRiskPercent=0.50// Risk % of effective capital per trade - [=== Risk & Sizing ===]
InpDailyLossLimitPct=3.00// Daily realized loss limit (% of eff cap) - [=== Risk & Sizing ===]
InpWeeklyLossLimitPct=6.00// Weekly realized loss limit (% of eff cap) - [=== Risk & Sizing ===]
InpMaxConcurrent= 1 // Max concurrent trades (this magic) - [=== Risk & Sizing ===]
InpCooldownAfterLoss= 2 // Cooldown bars after consecutive losses - [=== Risk & Sizing ===]
InpMaxSpreadPoints=30.0// Max allowed spread (points) - [=== Capital Allocation Cap ===]
InpCapitalCapAmount=0.0// Capital cap (real money $, not notional) - [=== Capital Allocation Cap ===]
InpCapitalCapFloor=50.00// Floor below which entries are blocked - [=== Signal ===]
InpRSIOb= 70 //RSIoverbought (BUYfilter) - [=== Signal ===]
InpRSIOs= 30 //RSIoversold (SELLfilter) - [=== Signal ===]
InpAdxThreshold=20.0//ADXmin for trend strength - [=== Regime & Confirm ===]
InpHtfAgreeEnabled=true// RequireHTFHull/EMAagreement - [=== Regime & Confirm ===]
InpMinRR=1.20// Min required R/R for entry - [=== Exit & Manage ===]
InpChandelierK=3.0//ATRtrailing multiple (Chandelier) - [=== Exit & Manage ===]
InpBE_R_Mult=1.0// Break-even at +R multiple - [=== Exit & Manage ===]
InpMaxBarsInTrade= 200 // Max bars in trade (time exit)
// Pipsgrowth EX18022 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// EMA(9/21) close-bar crossover confirmed by inlined Hull MA slope (LTF+HTF), RSI side, MACD histogram sign and ADX strength. Regime gate (ADX+ATR-pctile+BB-width), HTF-EMA agreement, capital-allocation-cap, BE/partial/ATR-trail exits, pyramid OFF by default. Broker-portable, 12-layer, single self-contained. 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
How to Install This EA on MT5
- 1Download the .mq5 file using the button above
- 2Open MetaTrader 5 on your computer
- 3Click File → Open Data Folder in the top menu
- 4Navigate to MQL5 → Experts and paste the .mq5 file there
- 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
- 6Drag the EA onto an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the dialog
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpMagic | 22218022 | Magic number (2220000+ExpertID) |
| InpTradeComment | "Psgrowth.com Expert_18022" | Trade comment |
| InpDryRun | true | Dry-run mode (no real orders) |
| InpKillSwitch | false | Kill switch (closes all, blocks new) |
| InpRiskPercent | 0.50 | Risk % of effective capital per trade |
| InpDailyLossLimitPct | 3.00 | Daily realized loss limit (% of eff cap) |
| InpWeeklyLossLimitPct | 6.00 | Weekly realized loss limit (% of eff cap) |
| InpMaxConcurrent | 1 | Max concurrent trades (this magic) |
| InpCooldownAfterLoss | 2 | Cooldown bars after consecutive losses |
| InpMaxSpreadPoints | 30.0 | Max allowed spread (points) |
| InpCapitalCapAmount | 0.0 | Capital cap (real money $, not notional) |
| InpCapitalCapFloor | 50.00 | Floor below which entries are blocked |
| InpRSIOb | 70 | RSI overbought (BUY filter) |
| InpRSIOs | 30 | RSI oversold (SELL filter) |
| InpAdxThreshold | 20.0 | ADX min for trend strength |
| InpHtfAgreeEnabled | true | Require HTF Hull/EMA agreement |
| InpMinRR | 1.20 | Min required R/R for entry |
| InpChandelierK | 3.0 | ATR trailing multiple (Chandelier) |
| InpBE_R_Mult | 1.0 | Break-even at +R multiple |
| InpMaxBarsInTrade | 200 | Max bars in trade (time exit) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18022 USDJPYm — EMA(9/21) cross + Hull MA + RSI + MACD + ADX, 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 (not inputs) ====================
#define EMA_FAST_PERIOD 9 // Fast EMA period (signal core)
#define EMA_SLOW_PERIOD 21 // Slow EMA period (signal core)
#define HULL_FAST_PERIOD 20 // Hull MA fast period
#define HULL_SLOW_PERIOD 50 // Hull MA slow period
#define HTF_PERIOD PERIOD_H1 // Higher timeframe for trend agreement
#define HTF_HULL_PERIOD 50 // HTF Hull MA period
#define HTF_EMA_PERIOD 50 // HTF EMA agreement period
#define RSI_PERIOD 14 // RSI period
#define MACD_FAST 12 // MACD fast
#define MACD_SLOW 26 // MACD slow
#define MACD_SIGNAL 9 // MACD signal
#define ADX_PERIOD 14 // ADX period
#define ATR_PERIOD 14 // ATR period
#define ATR_PCTILE_WINDOW 200 // ATR-percentile rolling window
#define BB_PERIOD 20 // Bollinger width period
#define BB_DEVIATION 2.0 // Bollinger deviation
#define SL_ATR_MULT 1.5 // Initial SL = SL_ATR_MULT * ATR (floor)
#define SWING_LOOKBACK 14 // Swing lookback for initial SL
#define TP1_R_MULT 1.0 // First target R multiple (partial 50%)
#define TP_FINAL_R_MULT 3.0 // Final target R multiple (close)
#define PARTIAL_PCT 0.50 // Partial close fraction at TP1
#define COOLDOWN_BARS 5 // Bars cooldown after losing close
#define MAX_SYMBOL_EXPOSURE 1 // Max simultaneous positions (this magic)
#define NEWS_WINDOW_MIN 0 // Manual news blackout minutes (0=off)
#define SESSION_START_HOUR 2 // Session start hour (server time)
#define SESSION_END_HOUR 21 // Session end hour (server time)
#define HMA_SLOPE_BARS 3 // Bars to measure Hull slope (sign agreement)
//==================== INPUTS (20 total, grouped) ========================
input group "=== Identity ==="
input int InpMagic = 22218022; // Magic number (2220000+ExpertID)
input string InpTradeComment = "Psgrowth.com Expert_18022"; // Trade comment
input bool InpDryRun = true; // Dry-run mode (no real orders)
input bool InpKillSwitch = false; // Kill switch (closes all, blocks new)
input group "=== Risk & Sizing ==="
input double InpRiskPercent = 0.50; // Risk % of effective capital per trade
input double InpDailyLossLimitPct = 3.00; // Daily realized loss limit (% of eff cap)
input double InpWeeklyLossLimitPct = 6.00; // Weekly realized loss limit (% of eff cap)
input int InpMaxConcurrent = 1; // Max concurrent trades (this magic)
input int InpCooldownAfterLoss = 2; // Cooldown bars after consecutive losses
input double InpMaxSpreadPoints = 30.0; // Max allowed spread (points)
input group "=== Capital Allocation Cap ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable // Enable capital allocation cap
input double InpCapitalCapAmount = 0.0; // Capital cap (real money $, not notional)Full source code available on download
Educational purposes only. Do NOT use with real money. Test on demo accounts only.
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
Markets.com
Exness
IC Markets
Similar Expert Advisors
View All Expert AdvisorsMore Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.