P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18117 TrendFollow

MT5 Expert Advisor (Open Source) · USDJPY · M5

Pipsgrowth.com EX18117 PipsGrowth_EA_USDJPYm — USDJPY M5 multi-indicator scalper, full 12-layer stack.

Overview

Pipsgrowth EX18117 is a USDJPY M5 multi-indicator scalper built around a closed-bar EMA(9)/EMA(21) crossover that has to clear a 13-gate consensus filter before it opens anything. The file ships with magic 22218117, a fixed 1.0 percent risk per trade, and fourteen MetaTrader 5 indicator handles, all of which are released in OnDeinit: two EMA handles on the current timeframe, eight Linear Weighted Moving Average handles used to reconstruct the True Hull MA on both the current timeframe and the chosen higher timeframe, and four filter handles (RSI 14, ADX 14, ATR 14, MACD 12/26/9).

The spine of the entry logic is the True Hull MA. Because MQL5 cannot express a WMA of an indicator buffer dynamically, the EA approximates the textbook Hull MA in CalculateHullMA: it computes rawHull = 2*LWMA(n/2) - LWMA(n) for each of the last sqrt(n) bars and then averages those values together. The result is cached per bar in UpdateHullValues for four series (fast current-TF, slow current-TF, fast HTF, slow HTF). On every closed bar the EA compares the closed EMA(9) and EMA(21) values from bar 1 and bar 2; if the fast line crossed above the slow line, the system runs ValidateBuyFilters, which demands True Hull fast > slow on both timeframes, an EMA slope of at least 0.05 points per bar (ruling out flat markets), no proximity within 50 points of the daily R1 or R2 pivot (so the entry is not parked at obvious resistance), tick volume at or above 0.8 times its 20-bar average, RSI under 75, ADX at or above 20, MACD histogram above zero, ATR(14) at or above 0.0005, current spread under 60 points, server hour between 2 and 21, and — if the news filter is enabled — no USD or JPY high-impact event within the configured 30 minutes before / 15 minutes after window. Sells run ValidateSellFilters, which is the mirror image (RSI above 25 instead of below 75, MACD histogram negative, S/R check against S1 and S2).

Sizing is done by CalculateLotSize. When InpFixedLot is zero, the EA divides account balance times InpRiskPercent by the notional stop distance in ticks, floors to the broker volume step, and clamps between min and max lot — a standard 1 percent risk formula. When InpFixedLot is non-zero, that value is used as-is. The 150-point stop and 250-point take profit are passed into the order when it is opened, and the original TP is never modified: only the stop is ratcheted.

The position-management loop in ManagePositions runs every tick. After 50 points of profit, the stop is moved to entry plus 10 points (the breakeven offset), and once the trade is in profit by 50 points or more, a 50-point trailing stop takes over and follows price forward. The ratchet is one-way — the stop only moves up for buys and down for sells, never backwards — and the trailing stop only tightens, never widens, the protective floor. Pyramid entries are handled separately in CheckPyramidOpportunity: the EA looks for an open position on the side it intends to add to, requires the most recent same-direction position to be in profit by at least 30 points, requires every open position on that side to still be in the green (AllPositionsProfitable), and re-runs the full filter stack before opening the next leg. Lots for the pyramid leg are scaled by MathPow(InpPyramidMultiplier, currentCount), so with the default multiplier of 1.0 every leg is the same size; setting it to 1.5 gives a geometric ramp. CheckPyramidOpportunity only fires for one side at a time and only up to InpMaxPyramid/2+1 legs per side, even though InpMaxPyramid is set to 5 by default — the practical pyramid cap per direction is 3, with the total exposure cap of 5 between both sides.

Exits are layered. CheckExitSignals runs after the pyramid check and looks for the reverse EMA crossover, which closes every open position on the opposite side (a bullish cross while sells are open closes all sells, and vice versa). RSI extremes are also exit triggers: if RSI climbs above 75 with the trade already 50 points in profit, the long is closed via ClosePositionsAtExtreme, and the mirror logic closes shorts at RSI under 25. The same ClosePositionsAtExtreme routine wraps the close in a 3x200ms retry via TryClose_EX18117 to handle requotes and price changes. The OnTick function is wrapped in a portfolio guard: IsDrawdownExceeded updates g_peakEquity whenever equity climbs to a new high (and never resets it) and short-circuits new entries when current equity is more than 20 percent below that peak — but ManagePositions keeps running, so trailing stops and breakeven adjustments continue to protect open positions.

The visual layer is two-tiered. CreateDashboard builds a 200-by-230 dark-slate panel pinned to the top-left with 13 labels (TITLE, SIGNAL, EMA, HULL, RSI, ADX, PIVOT, POS, PROFIT, SPREAD, VOLUME, SESSION, NEWS) that are redrawn on every tick by UpdateDashboard. The SIGNAL label takes its cue from the True Hull MA direction on the current timeframe plus the EMA ordering, not the crossover itself, so it shows a smoothed bias rather than the discrete event. The PIVOT label prints the daily PP, and SESSION / NEWS labels toggle between ACTIVE / PAUSED and OK / BLOCKED depending on the time-of-day and event filters. CreateChartVisuals and UpdateChartVisuals draw the daily pivot HLINEs (PP in gold, R1/R2 in red, S1/S2 in green) and a cyan / magenta dashed HLINE for the live True Hull fast and slow values; a CHART_SIGNAL_ARROW object is created at (0,0) and never moved, so the arrow itself does not function as a real signal marker despite the name.

There is a small but real quirk in the source: the helper functions MapTimeframeInt, MapAppliedPriceInt, and the global variable g_InpHTF are declared twelve times each in the input block, once per input group, because the file was assembled by pasting the same group scaffolding. MQL5 absorbs the duplicate declarations without error. The InpHTF input itself is parsed in OnInit, so the value set in the panel does drive the timeframe used for the higher-timeframe Hull — the redundant g_InpHTF assignments are dead.

Pyramiding is the clearest place where the risk profile diverges from a flat scalper: a single EMA crossover that clears the entire filter stack can turn into three open buys within a few bars if price keeps trending, each at the same lot size. The 20 percent drawdown cap is also a peak-equity-never-reset rule, so a long, slow grind back to the high is required before new entries resume after a drawdown pause.

Strategy Deep Dive

On each new M5 bar, the EA fetches the closed-bar EMA(9) and EMA(21) values from two bars back and the previous bar, looks for a crossover, and then runs the entire ValidateBuyFilters / ValidateSellFilters gauntlet. The True Hull MA is the spine of the filter stack: the EA keeps two pairs of LWMA handles per timeframe (current TF and HTF, defaulting to H1) and reconstructs the Hull series in CalculateHullMA by computing rawHull = 2*LWMA(n/2) - LWMA(n) for each of the last sqrt(n) bars and averaging them, since dynamic WMA-on-WMA cannot be expressed in MQL5. A long only fires when fast Hull > slow Hull on both the current TF and the HTF — the same condition the dashboard's SIGNAL label tracks every tick. The optional news file (USD and JPY events only) blocks entries for 30 minutes before and 15 minutes after each event when InpUseNewsFilter is true. The drawdown guard in IsDrawdownExceeded tracks g_peakEquity (which is never reset) and skips new entries when the current equity is more than 20 percent below that peak.

Entry Signal

Entries fire on a closed-bar EMA(9) crossing above EMA(21) on USDJPY M5, then have to pass a stacked consensus of True Hull MA bullish on both the current timeframe and the chosen higher timeframe, EMA slope above 0.05 points/bar, MACD histogram positive, ADX at or above 20, RSI under 75, ATR(14) above 0.0005, current tick volume at or above 0.8 times its 20-bar average, spread below 60 points, server hour between 2 and 21, and proximity to daily pivot R1 or R2 below 50 points. Sells mirror the same set on the opposite side. After the initial leg, up to five pyramid entries are allowed when each prior leg is in profit by at least 30 points and every open buy (or sell) is still in the green.

Exit Signal

Reverse EMA crossover closes the open basket on the opposite side (a bullish cross while a sell is live triggers a full sell close, and vice versa). Positions already in profit by at least 50 points are also closed when RSI hits the overbought band on longs or the oversold band on shorts, locking in gains at momentum exhaustion. The ManagePositions function then takes over: once price moves 50 points in favour, the stop is ratcheted to entry plus a 10-point offset, and a 50-point trailing stop takes over from there until the position is stopped out or the take profit fills at 250 points.

Stop Loss

Each position opens with a fixed 150-point stop loss attached at entry. The ManagePositions loop then pushes the stop to breakeven plus 10 points after 50 points of profit, and from that point forward a 50-point trailing stop ratchets the stop forward as price advances — the original 150-point stop is never widened, only tightened. There is also a portfolio-level kill switch: if drawdown from the all-time high equity exceeds 20 percent, the entry logic halts (though ManagePositions continues to run).

Take Profit

Take profit is set to 250 points at entry, giving a fixed 1:1.67 reward-to-risk ratio against the 150-point stop. The TP is never moved — only the stop is ratcheted forward by ManagePositions — so the trade resolves either at TP, at the trailing stop, or at a reverse-signal exit.

Best For

Best suited to a USDJPY M5 chart on a low-spread ECN or RAW account, with a recommended starting balance of $100 at the 1 percent risk setting (the 150-point stop translates to roughly 1.5 pips on the 5-decimal JPY pair). The default server-time session window of 2-21 covers Asia, London and the New York open, and the daily pivot R1/R2/S1/S2 lines on the chart are most useful when the broker's server clock aligns with the Tokyo or London open. The news filter should be enabled with the seeded 2026 USD/JPY NFP, FOMC and BOJ calendar when running through macro event weeks.

Strategy Logic

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

Family: TrendFollow Magic: 22218117 Version: 2.00

BRIEF: USDJPY M5 scalping EA using EMA crossover, Hull MA, RSI, ADX, ATR, and MACD for multi-indicator consensus. Features multi-timeframe confirmation, pyramiding, session/news/S-R filters, volume filter, trailing stop, and breakeven. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • IsNewBar()
  • LogBarInfo()
  • GetIndicatorValue()
  • CheckEntrySignals()
  • ValidateBuyFilters()
  • ValidateSellFilters()
  • IsWithinSession()
  • LoadNewsEvents()
  • CreateSampleNewsFile()
  • IsNearNews()
  • IsDrawdownExceeded()
  • CountPositions()
  • ...and 27 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (48 total across 13 groups):

  • [=== Risk Management ===] InpRiskPercent = 1.0 // Risk per trade (%) [1-2]
  • [=== Risk Management ===] InpFixedLot = 0.0 // Fixed lot (0=auto-risk)
  • [=== Risk Management ===] InpMaxPositions = 3 // Max total positions
  • [=== Risk Management ===] InpMaxPosPerDir = 2 // Max positions per direction
  • [=== Risk Management ===] InpStopLossPoints = 150 // Stop Loss (points)
  • [=== Risk Management ===] InpTakeProfitPoints = 250 // Take Profit (points)
  • [=== Risk Management ===] InpTrailingPoints = 50 // Trailing Stop (points)
  • [=== Risk Management ===] InpBreakevenPoints = 50 // Breakeven trigger (points)
  • [=== Risk Management ===] InpBreakevenOffset = 10 // Breakeven offset (points)
  • [=== Risk Management ===] InpMaxDDPercent = 20.0 // Max Drawdown to pause (%)
  • [=== EMA Settings ===] InpEMA_Fast = 9 // Fast EMA Period [step=1]
  • [=== EMA Settings ===] InpEMA_Slow = 21 // Slow EMA Period [step=1]
  • [=== Hull MA Settings ===] InpHull_Fast = 20 // Hull Fast Period [step=5]
  • [=== Hull MA Settings ===] InpHull_Slow = 50 // Hull Slow Period [step=5]
  • [=== Filter Indicators ===] InpRSI_Period = 14 // RSI Period
  • [=== Filter Indicators ===] InpRSI_OB = 75 // RSI Overbought [step=5]
  • [=== Filter Indicators ===] InpRSI_OS = 25 // RSI Oversold [step=5]
  • [=== Filter Indicators ===] InpADX_Period = 14 // ADX Period
  • [=== Filter Indicators ===] InpADX_Min = 20 // ADX Minimum Trend [step=5]
  • [=== Filter Indicators ===] InpATR_Period = 14 // ATR Period
  • [=== Filter Indicators ===] InpATR_MinVol = 0.0005 // ATR Minimum Volatility
  • [=== Filter Indicators ===] InpMACD_Fast = 12 // MACD Fast
  • [=== Filter Indicators ===] InpMACD_Slow = 26 // MACD Slow
  • [=== Filter Indicators ===] InpMACD_Signal = 9 // MACD Signal
  • [=== Multi-Timeframe ===] InpHTF = 7 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher Timeframe
  • [=== Pyramid Settings ===] InpMaxPyramid = 5 // Max Pyramid Positions
  • [=== Pyramid Settings ===] InpPyramidMinProfit = 30 // Min Profit for Pyramid (points)
  • [=== Pyramid Settings ===] InpPyramidMultiplier = 1.0 // Lot Multiplier (1.0=fixed)
  • [=== Session Filter (Server Time) ===] InpSessionStart = 2 // Session Start Hour
  • [=== Session Filter (Server Time) ===] InpSessionEnd = 21 // Session End Hour
  • [=== News Filter ===] InpNewsBefore = 30 // Minutes Before News
  • [=== News Filter ===] InpNewsAfter = 15 // Minutes After News
  • [=== News Filter ===] InpUseNewsFilter = false // Enable News Filter
  • [=== News Filter ===] InpNewsFile = "news_events.csv" // News Events File
  • [=== S/R Filter ===] InpUseSRFilter = true // Enable S/R Filter
  • [=== S/R Filter ===] InpSRProximity = 50 // S/R Proximity (points)
  • [=== S/R Filter ===] InpShowPivots = true // Show Pivot Lines
  • [=== EMA Slope Filter ===] InpEMASlopeMin = 0.05 // Min EMA Slope (points/bar)
  • [=== Volume Filter ===] InpUseVolumeFilter = true // Enable Volume Filter
  • [=== Volume Filter ===] InpVolumePeriod = 20 // Volume MA Period
  • [=== Volume Filter ===] InpVolumeMultiplier = 0.8 // Min Volume vs Avg
  • [=== Visual Settings ===] InpShowIndicators = true // Show Indicators on Chart
  • [=== Visual Settings ===] InpBuyColor = clrLime // Buy Signal Color
  • [=== Visual Settings ===] InpSellColor = clrRed // Sell Signal Color
  • [=== Visual Settings ===] InpPivotColor = clrGold // Pivot Line Color
  • [=== System ===] InpMagicNumber = 22218117 // Magic number
  • [=== System ===] InpMaxSpread = 60.0 // Max Spread (points)
  • [=== System ===] InpSlippage = 10 // Slippage (points)
Pseudocode
// Pipsgrowth EX18117 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// USDJPY M5 scalping EA using EMA crossover, Hull MA, RSI, ADX, ATR, and MACD for multi-indicator consensus. Features multi-timeframe confirmation, pyramiding, session/news/S-R filters, volume filter, trailing stop, and breakeven. 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
InpRiskPercent1.0Risk per trade (%) [1-2]
InpFixedLot0.0Fixed lot (0=auto-risk)
InpMaxPositions3Max total positions
InpMaxPosPerDir2Max positions per direction
InpStopLossPoints150Stop Loss (points)
InpTakeProfitPoints250Take Profit (points)
InpTrailingPoints50Trailing Stop (points)
InpBreakevenPoints50Breakeven trigger (points)
InpBreakevenOffset10Breakeven offset (points)
InpMaxDDPercent20.0Max Drawdown to pause (%)
InpEMA_Fast9Fast EMA Period [step=1]
InpEMA_Slow21Slow EMA Period [step=1]
InpHull_Fast20Hull Fast Period [step=5]
InpHull_Slow50Hull Slow Period [step=5]
InpRSI_Period14RSI Period
InpRSI_OB75RSI Overbought [step=5]
InpRSI_OS25RSI Oversold [step=5]
InpADX_Period14ADX Period
InpADX_Min20ADX Minimum Trend [step=5]
InpATR_Period14ATR Period
InpATR_MinVol0.0005ATR Minimum Volatility
InpMACD_Fast12MACD Fast
InpMACD_Slow26MACD Slow
InpMACD_Signal9MACD Signal
InpHTF7Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher Timeframe
InpMaxPyramid5Max Pyramid Positions
InpPyramidMinProfit30Min Profit for Pyramid (points)
InpPyramidMultiplier1.0Lot Multiplier (1.0=fixed)
InpSessionStart2Session Start Hour
InpSessionEnd21Session End Hour
InpNewsBefore30Minutes Before News
InpNewsAfter15Minutes After News
InpUseNewsFilterfalseEnable News Filter
InpNewsFile"news_events.csv"News Events File
InpUseSRFiltertrueEnable S/R Filter
InpSRProximity50S/R Proximity (points)
InpShowPivotstrueShow Pivot Lines
InpEMASlopeMin0.05Min EMA Slope (points/bar)
InpUseVolumeFiltertrueEnable Volume Filter
InpVolumePeriod20Volume MA Period
InpVolumeMultiplier0.8Min Volume vs Avg
InpShowIndicatorstrueShow Indicators on Chart
InpBuyColorclrLimeBuy Signal Color
InpSellColorclrRedSell Signal Color
InpPivotColorclrGoldPivot Line Color
InpMagicNumber22218117Magic number
InpMaxSpread60.0Max Spread (points)
InpSlippage10Slippage (points)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18117.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18117 PipsGrowth_EA_USDJPYm — USDJPY M5 multi-indicator scalper, full 12-layer stack."

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

//+------------------------------------------------------------------+
//| INPUT PARAMETERS - ALL OPTIMIZABLE                               |
//+------------------------------------------------------------------+
// Risk Management
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 "=== Risk Management ==="
input double InpRiskPercent = 1.0;       // Risk per trade (%) [1-2]
input double InpFixedLot = 0.0;      // Fixed lot (0=auto-risk)
input int InpMaxPositions = 3;       // Max total positions
input int InpMaxPosPerDir = 2;       // Max positions per direction
input int InpStopLossPoints = 150;   // Stop Loss (points)
input int InpTakeProfitPoints = 250; // Take Profit (points)
input int InpTrailingPoints = 50;   // Trailing Stop (points)
input int InpBreakevenPoints = 50;   // Breakeven trigger (points)
input int InpBreakevenOffset = 10;   // Breakeven offset (points)
input double InpMaxDDPercent = 20.0; // Max Drawdown to pause (%)

// Signal Parameters - OPTIMIZABLE
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:ex18117trendfollowpipsgrowthfreemt5usdjpy

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