P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18114 TrendFollow

MT5 Expert Advisor (Open Source) · USDJPY · M5

Pipsgrowth.com EX18114 PipsGrowth_EA_USDJPYm_v2 — Modular USDJPY M5 multi-indicator EA, full 12-layer stack.

Overview

Pipsgrowth EX18114 is a USDJPY-only M5 trend-following robot built around a 14-handle indicator stack. The author wires EMA(9) crossing EMA(21) as the primary trigger, then demands a four-piece Hull MA agreement before a single ticket is opened. The Hull agreement is not a simple two-line cross. The code stands up eight LWMA handles in OnInit — WMA(N) and WMA(N/2) on the working timeframe and the same pair on the higher timeframe — and from them it computes the textbook Hull raw value of 2·WMA(N/2) − WMA(N), then averages the last √N of those raw values into the final Hull series. The fast pair uses N=20 and the slow pair uses N=50, both on the M5 chart and on the HTF selected by InpHTF (1=M1, 2=M5, 3=M15, 4=M30, 5=H1, 6=H4, 7=D1; the default 8 silently clamps to H1 in MapTimeframeInt). A long entry is only valid if Hull-fast is above Hull-slow on the M5 chart AND on the HTF; a short requires both fast lines to be below both slow lines. That dual-timeframe Hull agreement is the EA's distinctive design choice — the EMA cross fires often, but the double Hull vetoes the majority of weak crosses where the higher timeframe is still trending the other way.

Once a cross is detected, the trade must still survive a nine-filter avoid stack inside CheckAvoidFilters. Filter_RSI vetoes longs when the 14-period RSI is above 70 and shorts when it is below 30. Filter_ADX requires the 14-period ADX to print at least 25 on bar 1, so the trade only enters when the market is actually trending. Filter_ATR enforces a minimum 0.0005 volatility floor on the 14-period ATR, killing entries inside dead Asian-session ranges. Filter_Spread rejects fills when the current spread exceeds 30 points, important on USDJPY where the spread can balloon at the Sunday open. Filter_Session blocks entries outside the 2:00–21:00 server-time window. Filter_News is opt-in via InpUseNewsFilter; when enabled, LoadNewsEvents reads a user-provided news_events.csv (or, if missing, CreateSampleNewsFile seeds a 2026 NFP/FOMC/BOJ sample), and the EA refuses to enter within 30 minutes before or 15 minutes after any USD or JPY event. Filter_SR reads the previous-day D1 OHLC, derives classic pivot points (PP, R1, R2, S1, S2) inside CalculateDailyPivots, and blocks longs within 50 points of R1 or R2 and shorts within 50 points of S1 or S2. Filter_EMASlope requires the M5 EMA(9) to be moving at least 0.05 points per bar, killing flat or rolling-over crosses. Filter_Volume demands the most recent tick volume to be at least 80% of the 20-bar average; CalculateAverageVolume refreshes the baseline on every new bar.

OpenPosition brackets the trade at the moment of entry. CalculateLotSize uses 1% of balance by default, dividing balance × risk% by the SL-distance-implied tick cost, flooring to the lot step, and clamping to the symbol's min and max lot; setting InpFixedLot to anything above 0.0 short-circuits the formula to a fixed size. The bracket is 200 points of stop and 400 points of take profit, a fixed 1:2 R:R that does not move with ATR — the SL is simply Ask ± 200·Point, the TP is Bid ± 400·Point. trade.PositionOpen submits the request with the magic number 22218114, the comment Psgrowth.com Expert_18114, and 10 points of allowed slippage.

The pyramid subsystem layers additional positions onto a winning trade. ProcessPyramidLogic runs after exit checks and before the next entry; if the user has fewer than InpMaxPyramid=5 same-direction positions and the Hull agreement still holds, every existing same-side position is in profit, the most recent position is at least 30 points in profit, and the full nine-filter stack still passes, OpenPyramidPosition adds another leg with a lot size of baseLot × 1.0^legNum (the default multiplier is 1.0, so pyramid legs are equal-sized, not geometric). The pyramid always re-validates the Hull + filter stack on each new leg, so a single late-session volatility spike that flips ADX below 25 or RSI into overbought stops the next leg from being added but does not flatten the legs already on the book.

Three exit paths run on every closed M5 bar. CheckEMAReversal watches the same EMA 9/21 cross that triggers entries and, when the cross flips against an open position, calls ClosePositionsByType to flatten every same-direction position via TryClose_EX18114 (three attempts at 200ms, retrying on requote/timeout/price-changed/price-off). CheckRSIExtreme closes profitable longs when RSI prints above 70 and profitable shorts when RSI prints below 30, gated by an InpBreakevenPoints=50 minimum profit so a brand-new trade is not stopped out by a single overbought print. ManageOpenPositions runs on every tick and handles the in-trade maintenance: when profit reaches 50 points, the stop is ratcheted to entry + 10 points (one-way ratchet — the SL only ever moves towards profit); when profit reaches 100 points, the trailing stop kicks in at 100 points behind price and ratchets up bar by bar.

A global drawdown brake sits above the entry logic. IsDrawdownExceeded updates g_peakEquity on every tick and computes (peak − current) / peak × 100. If the drawdown from peak ever exceeds 20%, ProcessEntryLogic and ProcessPyramidLogic are short-circuited, but ManageOpenPositions keeps running so existing trades are still managed, and a chart comment logs the pause.

The visual layer is modest but functional. CreateDashboard builds a 200×250 dark-slate panel in the upper-left corner with twelve labels — title, signal, EMA values, Hull direction (UP/DN coloured lime/red), RSI, ADX, pivot, position counts, total P/L, spread, average volume, session state, and news status. UpdateDashboard refreshes them every tick. UpdateChartVisuals redraws cyan and magenta dashed HLINEs at the current Hull fast and Hull slow values, and DrawPivotLines lays down five solid/dotted HLINEs (gold PP, red R1/R2, green S1/S2). OnInit emits a warning if the chart symbol is not USDJPY or USDJPYm, but the EA does not refuse to start — it just notes the mismatch in the log.

Realistic expectations for a backtest or live deployment: the EMA 9/21 cross fires on the M5 USDJPY chart 8 to 15 times per London + New York session combined, and the double-Hull agreement knocks roughly two-thirds of those out. The remaining 3 to 5 candidates still have to survive the nine-filter stack, which in choppy conditions can leave the EA flat for entire sessions. When a trade does trigger, the fixed 1:2 R:R means a single win pays for two losses; with the 20% drawdown pause and the 100-point trailing stop, the EA can ride one strong London breakout for two or three pyramid legs and book 300 to 800 points of profit. Loss clusters tend to come from Tokyo-session false breaks where the EMA cross fires just before the New York open and the HTF Hull flips inside the 50-point SL — this is exactly the regime where the S/R filter and the EMA-slope filter are most useful, and traders should keep both enabled in live deployment. The pyramid lot multiplier of 1.0 makes the system behave like a position-stacking scalper rather than a martingale; if you want geometric scaling, raise InpPyramidMultiplier above 1.0 and accept the corresponding increase in margin usage and the per-leg margin check inside the order path.

Strategy Deep Dive

OnInit stands up fourteen indicator handles — EMA(9) and EMA(21) on the working timeframe, eight LWMA handles for the four Hull MA pairs (WMA(N=20) + WMA(N/2=10) and WMA(N=50) + WMA(N/2=25) on both M5 and the HTF, defaulting to H1), plus RSI(14), ADX(14), ATR(14), and MACD(12,26,9). OnTick first calls ManageOpenPositions to update trailing/breakeven, then bails until IsNewBar reports a new M5 candle. UpdateIndicatorCache refreshes the cached Hull values for the four series, CalculateAverageVolume recomputes the 20-bar volume baseline, and CheckDayChange re-runs CalculateDailyPivots when the date rolls over. IsDrawdownExceeded updates g_peakEquity and short-circuits entry logic when the drawdown from peak exceeds 20%. ProcessExitLogic runs CheckEMAReversal and CheckRSIExtreme on the closed bar; ProcessPyramidLogic then looks for a pyramid add; finally ProcessEntryLogic detects the EMA cross on bar 1, calls CheckHullConfirmation to verify both Hull pairs agree, runs the full CheckAvoidFilters chain, enforces the 2/3 position caps (InpMaxPosPerDir, InpMaxPositions), and on success calls OpenPosition which sizes the lot via CalculateLotSize and submits a market order with 200-point SL and 400-point TP through the CTrade wrapper at 10 points of slippage.

Entry Signal

A long entry requires the EMA(9) to cross above EMA(21) on the closed M5 bar (bar 1 vs bar 2), with the dual Hull MA agreement — Hull-fast above Hull-slow on both the M5 chart and the higher timeframe — then clearing the nine-filter avoid stack (RSI 14 not overbought, ADX 14 above 25, ATR 14 above 0.0005, spread below 30 points, server hour 2–21, optional news quiet, not within 50 points of R1/R2 resistance for longs or S1/S2 support for shorts, EMA slope above 0.05 pts/bar, and tick volume above 80% of the 20-bar average). Position size is 1% of balance by SL distance, with a fixed-lot override available.

Exit Signal

Three exit paths run on every closed bar: CheckEMAReversal closes the entire side when the EMA 9/21 cross flips against the open positions, CheckRSIExtreme closes profitable positions on the same side when RSI pushes above 70 (buys) or below 30 (sells) and the position is at least 50 points in profit, and ManageOpenPositions ratchets the stop to breakeven + 10 points once profit hits 50 points and activates a 100-point trailing stop once profit hits 100 points.

Stop Loss

Fixed 200-point stop set at entry via OpenPosition and never moved wider. ManageOpenPositions then ratchets the stop to entry + 10 points once profit reaches 50 points, and from 100 points of profit the trailing stop at 100 points behind price ratchets the stop up bar by bar — the stop only ever moves towards profit, never away from it.

Take Profit

Fixed 400-point take profit set at entry (1:2 R:R against the 200-point stop). Pyramiding layers additional positions onto a winning trade when the same-side stack is fully profitable, the most recent leg is at least 30 points in profit, the dual-Hull agreement still holds, and the full nine-filter stack still passes; the default lot multiplier is 1.0 (equal-sized legs), so a single winning trend can stack up to 5 tickets with the same take profit and stop.

Best For

USDJPY-only M5 trend follower aimed at prop-firm and small-retail accounts; the minimum recommended balance is $100 (the 1%-of-balance risk with 200-point SL and 0.01 lot minimum on USDJPY starts producing useful position sizes at that level, and the 20% drawdown pause protects the account if the trade stack goes against). Best paired with a low-spread USDJPY ECN broker — the 30-point spread cap and 10-point slippage setting assume sub-pip fills — and run on a VPS with stable session hours 2:00–21:00 server time (typically a GMT+2 or GMT+3 broker covering Asian + London + New York in one window, since the EA will not enter outside that band).

Strategy Logic

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

Family: TrendFollow Magic: 22218114 Version: 2.00

BRIEF: Modular USDJPY M5 EA v2 using EMA crossover, Hull MA with HTF confirmation, RSI/ADX/ATR/MACD filters, session/news/S-R filters, volume filter, pyramid scaling, trailing stop, and breakeven. Organized by module: Entry, Avoid, Exit, Pyramid, Risk, System. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • IsNewBar()
  • UpdateIndicatorCache()
  • CheckDayChange()
  • ProcessEntryLogic()
  • CheckHullConfirmation()
  • CheckAvoidFilters()
  • Filter_RSI()
  • Filter_ADX()
  • Filter_ATR()
  • Filter_Spread()
  • Filter_Session()
  • Filter_News()
  • ...and 34 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (45 total across 6 groups):

  • [=== Entry Logic ===] InpEMA_Fast = 9 // Fast EMA Period
  • [=== Entry Logic ===] InpEMA_Slow = 21 // Slow EMA Period
  • [=== Entry Logic ===] InpHull_Fast = 20 // Hull MA Fast Period
  • [=== Entry Logic ===] InpHull_Slow = 50 // Hull MA Slow Period
  • [=== Entry Logic ===] InpHTF = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher Timeframe for Hull
  • [=== Avoid Logic (Filters) ===] InpRSI_Period = 14 // RSI Period
  • [=== Avoid Logic (Filters) ===] InpRSI_OB = 70 // RSI Overbought Level
  • [=== Avoid Logic (Filters) ===] InpRSI_OS = 30 // RSI Oversold Level
  • [=== Avoid Logic (Filters) ===] InpADX_Period = 14 // ADX Period
  • [=== Avoid Logic (Filters) ===] InpADX_Min = 25 // ADX Minimum for Trend
  • [=== Avoid Logic (Filters) ===] InpATR_Period = 14 // ATR Period
  • [=== Avoid Logic (Filters) ===] InpATR_MinVol = 0.0005 // ATR Min Volatility
  • [=== Avoid Logic (Filters) ===] InpMaxSpread = 30.0 // Max Spread (points)
  • [=== Avoid Logic (Filters) ===] InpSessionStart = 2 // Session Start Hour
  • [=== Avoid Logic (Filters) ===] InpSessionEnd = 21 // Session End Hour
  • [=== Avoid Logic (Filters) ===] InpUseNewsFilter = false // Enable News Filter
  • [=== Avoid Logic (Filters) ===] InpNewsFile = "news_events.csv" // News File
  • [=== Avoid Logic (Filters) ===] InpNewsBefore = 30 // Minutes Before News
  • [=== Avoid Logic (Filters) ===] InpNewsAfter = 15 // Minutes After News
  • [=== Avoid Logic (Filters) ===] InpUseSRFilter = true // Enable S/R Filter
  • [=== Avoid Logic (Filters) ===] InpSRProximity = 50 // S/R Distance (points)
  • [=== Avoid Logic (Filters) ===] InpEMASlopeMin = 0.05 // Min EMA Slope (pts/bar)
  • [=== Avoid Logic (Filters) ===] InpUseVolumeFilter = true // Enable Volume Filter
  • [=== Avoid Logic (Filters) ===] InpVolumePeriod = 20 // Volume Average Period
  • [=== Avoid Logic (Filters) ===] InpVolumeMultiplier = 0.8 // Min Volume vs Average
  • [=== Exit Logic ===] InpStopLossPoints = 200 // Stop Loss (points)
  • [=== Exit Logic ===] InpTakeProfitPoints = 400 // Take Profit (points)
  • [=== Exit Logic ===] InpTrailingPoints = 100 // Trailing Stop (points)
  • [=== Exit Logic ===] InpBreakevenPoints = 50 // Breakeven Trigger (points)
  • [=== Exit Logic ===] InpBreakevenOffset = 10 // Breakeven Offset (points)
  • [=== Exit Logic ===] InpMACD_Fast = 12 // MACD Fast (for reversal)
  • [=== Exit Logic ===] InpMACD_Slow = 26 // MACD Slow
  • [=== Exit Logic ===] InpMACD_Signal = 9 // MACD Signal
  • [=== Pyramid Logic ===] InpMaxPyramid = 5 // Max Pyramid Positions
  • [=== Pyramid Logic ===] InpPyramidMinProfit = 30 // Min Profit for Pyramid (pts)
  • [=== Pyramid Logic ===] InpPyramidMultiplier = 1.0 // Lot Multiplier per Leg
  • [=== Risk Management ===] InpRiskPercent = 1.0 // Risk Per Trade (%)
  • [=== Risk Management ===] InpFixedLot = 0.0 // Fixed Lot (0=auto)
  • [=== Risk Management ===] InpMaxPositions = 3 // Max Total Positions
  • [=== Risk Management ===] InpMaxPosPerDir = 2 // Max Per Direction
  • [=== Risk Management ===] InpMaxDDPercent = 20.0 // Max Drawdown to Pause (%)
  • [=== System ===] InpMagicNumber = 22218114 // Magic number
  • [=== System ===] InpSlippage = 10 // Slippage (points)
  • [=== System ===] InpShowPivots = true // Show Pivot Lines
  • [=== System ===] InpShowIndicators = true // Show Indicator Lines
Pseudocode
// Pipsgrowth EX18114 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Modular USDJPY M5 EA v2 using EMA crossover, Hull MA with HTF confirmation, RSI/ADX/ATR/MACD filters, session/news/S-R filters, volume filter, pyramid scaling, trailing stop, and breakeven. Organized by module: Entry, Avoid, Exit, Pyramid, Risk, System. 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:
USDJPY
Optimized Timeframes:
M5

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
InpEMA_Fast9Fast EMA Period
InpEMA_Slow21Slow EMA Period
InpHull_Fast20Hull MA Fast Period
InpHull_Slow50Hull MA Slow Period
InpHTF8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher Timeframe for Hull
InpRSI_Period14RSI Period
InpRSI_OB70RSI Overbought Level
InpRSI_OS30RSI Oversold Level
InpADX_Period14ADX Period
InpADX_Min25ADX Minimum for Trend
InpATR_Period14ATR Period
InpATR_MinVol0.0005ATR Min Volatility
InpMaxSpread30.0Max Spread (points)
InpSessionStart2Session Start Hour
InpSessionEnd21Session End Hour
InpUseNewsFilterfalseEnable News Filter
InpNewsFile"news_events.csv"News File
InpNewsBefore30Minutes Before News
InpNewsAfter15Minutes After News
InpUseSRFiltertrueEnable S/R Filter
InpSRProximity50S/R Distance (points)
InpEMASlopeMin0.05Min EMA Slope (pts/bar)
InpUseVolumeFiltertrueEnable Volume Filter
InpVolumePeriod20Volume Average Period
InpVolumeMultiplier0.8Min Volume vs Average
InpStopLossPoints200Stop Loss (points)
InpTakeProfitPoints400Take Profit (points)
InpTrailingPoints100Trailing Stop (points)
InpBreakevenPoints50Breakeven Trigger (points)
InpBreakevenOffset10Breakeven Offset (points)
InpMACD_Fast12MACD Fast (for reversal)
InpMACD_Slow26MACD Slow
InpMACD_Signal9MACD Signal
InpMaxPyramid5Max Pyramid Positions
InpPyramidMinProfit30Min Profit for Pyramid (pts)
InpPyramidMultiplier1.0Lot Multiplier per Leg
InpRiskPercent1.0Risk Per Trade (%)
InpFixedLot0.0Fixed Lot (0=auto)
InpMaxPositions3Max Total Positions
InpMaxPosPerDir2Max Per Direction
InpMaxDDPercent20.0Max Drawdown to Pause (%)
InpMagicNumber22218114Magic number
InpSlippage10Slippage (points)
InpShowPivotstrueShow Pivot Lines
InpShowIndicatorstrueShow Indicator Lines
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18114.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18114 PipsGrowth_EA_USDJPYm_v2 — Modular USDJPY M5 multi-indicator EA, full 12-layer stack."

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

// ╔═══════════════════════════════════════════════════════════════════╗
// ║                    INPUT PARAMETERS BY MODULE                      ║
// ╚═══════════════════════════════════════════════════════════════════╝

//+------------------------------------------------------------------+
//| ENTRY LOGIC 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_InpHTF = PERIOD_H1;
input group "=== Entry Logic ==="
input int InpEMA_Fast = 9;                                    // Fast EMA Period
input int InpEMA_Slow = 21;               // Slow EMA Period
input int InpHull_Fast = 20;              // Hull MA Fast Period
input int InpHull_Slow = 50;              // Hull MA Slow Period
input int InpHTF = 8; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher Timeframe for Hull

//+------------------------------------------------------------------+
//| AVOID LOGIC INPUTS (FILTERS)                                      |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)

Full source code available on download

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

Tags:ex18114trendfollowpipsgrowthfreemt5usdjpy

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_EX18114.mq5
File Size53.6 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
USDJPY
Min. Deposit$100