P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18018 TrendFollow

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

Pipsgrowth.com EX18018 USDJPY_MultiIndicator_System — 5-signal consensus vote, full 12-layer stack.

Overview

EX18018 USDJPY MultiIndicator System is a USDJPY-tuned trend-following EA that builds each trade decision from a five-signal consensus vote and a regime gate. Instead of relying on a single indicator or a hard-coded crossover, the engine polls five independent technical signals and only fires when at least three of them agree on direction, then it double-checks the trade against a separate confirmation layer that includes higher-timeframe trend, volatility percentile, spread, and reward-to-risk viability. The result is a system that is willing to wait for a confluence of supporting evidence before it puts risk on, and that refuses to act when its market-state classifier judges the chart unfit for trend trading.

The five voters run on every closed bar. VoteTrend combines ADX(14) above the 20-threshold with +DI/-DI side alignment, price position relative to a 20-period LWMA, and the slope of that LWMA. VoteRSI looks at the base M15 RSI(14) reaching oversold/overbought extremes and turning, and it cross-validates the turn against the average of H1 RSI(14) and H4 RSI(14) — a higher-timeframe agreement check that filters out counter-trend hooks. VoteStoch is a textbook stochastic main/signal cross confined to the extreme zones (under 30 for bullish, over 70 for bearish). VoteMACD is a 12-26-9 main/signal cross with histogram direction. VoteSR is the most distinctive of the five: it computes the classic daily pivot and the five-line Tirone range from the prior 20 daily bars entirely in code (no external indicator), then votes bullish when price is within 30 points of the lower pivot, the lower Tirone level, or a pivot-bid-side tag, and bearish on the resistance side. The consensus function GetConsensus() collects all five and returns +1 (long) only when bull >= 3 and bull > bear, or -1 (short) on the mirror condition. Anything less than three agreeing votes produces no signal at all.

The regime layer runs before consensus. CalcRegime() reads the current ATR percentile (over a 50-bar lookback) and BB(20,2) width ratio, then classifies the chart into one of seven states — STRONG_TREND, WEAK_TREND, RANGE, BREAKOUT, EXPAND, COMPRESS, or CHOPPY — using thresholds such as ADX >= 25 and ATR-pctile >= 50% for strong trend, ADX < 18 and width ratio < 0.95 for compression, and width ratio > 1.30 with low ATR-pctile for choppy. The gate function RegimeAllowsEntry() then allows entries only in the four trending or volatility-expanding states; RANGE, COMPRESS, and CHOPPY all block new trades regardless of how strong the consensus looks. This is what keeps the EA from getting chopped up when the chart is sideways.

The confirmation layer runs after consensus. ConfirmAll() checks five things: an inline H1 EMA(50) slope direction that must agree with the consensus (price above EMA and EMA rising for longs, mirror for shorts), ATR-pctile must sit between 20 and 95 (so the EA trades both quiet and volatile conditions but refuses absolute extremes), the live spread must be at or below InpMaxSpreadPts = 30 points, the configured reward-to-risk ratio must be at least 1.0, and the signal must come from a closed bar. Any single failure is logged with a tag (HTF, VOLpct, SPR, RR) and the trade is dropped.

Position management is conservative and tight. Each entry uses an ATR-based stop of 1.5xATR(14) from the entry price and a take-profit at 1.5x that stop, giving the standard 1:1.5 reward-to-risk ratio. Lot size comes from CalcLots(), which targets 0.5% of the effective capital at the configured stop distance. The trailing stop kicks in at 2.0xATR from current price, ratcheting only in the profitable direction. Once the trade moves 1R in profit, the stop is moved to entry plus one point in a single one-shot break-even step. There is no partial-close in the live path — the EA runs one entry to its full TP/SL/trail. The 100-bar max-in-trade timer is a hard ceiling that closes the position if it has not resolved by then (about 25 hours on M15). In addition, every tick the EA re-evaluates the consensus and immediately closes any open position whose direction contradicts the new consensus vote — that is the explicit opposite-signal exit, not just a passive trailing stop.

The risk envelope wraps everything. Effective capital is min(InpCapitalCapAmount, account_equity) with a $50 floor below which no new entries are taken, the daily realized loss is monitored against a 3% of effective capital limit, and the EA enforces a hard one-position-per-symbol cap with its own magic number 22218018. The session filter runs from 07:00 to 20:00 server time and blocks weekends entirely. The dry-run flag InpDryRun defaults to true so the EA logs its intended trades to the Experts tab without sending orders, and the kill switch InpKillSwitch is available for emergency flat. The OnTester fitness function (net * profit_factor) / (1 + max_balance_dd) with a 30-trade minimum reward is the optimization target.

All indicator work is done in-line with native MT5 handles — ADX, ATR, Bollinger Bands, three RSI handles for M15/H1/H4, Stochastic, MACD, LWMA, and an H1 ATR — so there is no iCustom dependency and no DLL to load. Order send, modify, and close operations are wrapped in three-retry helpers (TryClose_EX18018, TryClosePartial_EX18018, TryModify_EX18018) that re-quote on transient errors with 200 ms / 100 ms back-off. A single entry-send retry on requote/timeout/price-changed gives the system a second chance at the broker without spamming orders.

What to expect in a backtest: EX18018 will take fewer trades than a single-indicator EA on the same period, but the trade frequency is meaningful because the consensus threshold is 3-of-5 rather than 5-of-5. Expect the equity curve to stair-step through trending USDJPY days and to flatten (or even trade a few losses) through RANGE/COMPRESS/CHOPPY days. A 30-trade minimum in the strategy tester fitness is a deliberate filter against curve-fit samples that look good on 12 trades.

Strategy Deep Dive

On every tick the EA refreshes the symbol and the day-state, then computes the seven-state regime classifier from ADX(14), ATR(14) percentile over a 50-bar lookback, and Bollinger Bands(20,2) width ratio. When a new bar opens, five voter functions run in sequence — Trend (ADX+DI+price-vs-LWMA+slope), RSI (base M15 extreme+turn with H1/H4 MTF agreement), Stochastic (main/signal cross in extreme zone), MACD (12-26-9 cross+histogram direction), and S/R (inline daily-pivot + Tirone proximity within 30 points) — and the GetConsensus() function returns a directional signal only when at least three of the five agree. A ConfirmAll() pass then checks H1 EMA(50) slope, ATR-pctile band, live spread, R/R, and closed-bar source before the order is sized at 0.5% of effective capital with a 1.5xATR stop and a 1.5xSL target. ManageExits() runs every tick and re-evaluates the consensus for the opposite-signal exit, the 2.0xATR trail, the one-shot break-even at 1R, and the 100-bar time-based close. All orders pass through three-retry wrappers that re-quote on transient broker errors with 200/100 ms back-off.

Entry Signal

Entry fires only when the 5-signal consensus panel returns +1 (long) or -1 (short) — meaning at least three of Trend, RSI, Stochastic, MACD, and the inlined daily-pivot/Tirone S/R vote in the same direction — and the chart is in one of the four allowed regime states (STRONG_TREND, WEAK_TREND, BREAKOUT, or EXPAND). The trade is then run through a five-condition confirm gate (H1 EMA(50) slope agreement, ATR-pctile 20-95, spread <= 30 points, R/R >= 1.0, closed-bar signal) before a single order is sized at 0.5% of effective capital and sent with a 1.5xATR(14) stop and a 1.5xSL target. Duplicate entries on the same closed bar are blocked via g_last_entry_bar, and the EA permits at most one open position per symbol.

Exit Signal

Three exit paths run side by side. Every tick the EA re-evaluates the 5-signal consensus and immediately closes any open position whose side contradicts the new vote (the explicit opposite-signal exit). The trailing stop at 2.0xATR(14) ratchets the stop in the profitable direction only, and a single one-shot break-even step moves the stop to entry+1 point once the trade has moved 1R. Finally, a hard 100-bar timer closes the position if it has not resolved by then (about 25 hours on M15).

Stop Loss

Stop-loss is fixed at 1.5xATR(14) at entry (with a broker-stops-level floor of 1.5x the minimum distance, so the stop never sits inside the freeze zone). The stop is then moved to break-even (entry+1 point) one-shot once price reaches 1R in profit, after which the 2.0xATR(14) trailing stop takes over and ratchets in the profitable direction.

Take Profit

Take-profit is set at 1.5x the stop distance, giving a fixed 1:1.5 reward-to-risk ratio. The TP is placed at order open and is not modified during the trade — the trailing stop, break-even step, and opposite-signal exit are what move the exit, not the TP itself.

Best For

Designed for USDJPY on M15 (also valid M5 and M30) with a $100 minimum account balance at MEDIUM risk — the 0.5% risk-per-trade and 3% daily loss cap keep the EA on a controlled path even when the consensus fires several times in a row. The 30-point spread cap and the volatility-percentile filter (20-95) make the system pair best with a low-spread ECN or raw-spread broker; avoid brokers that quote USDJPY wider than 25 points during your session. Run during the 07:00-20:00 server-time window (London and the New York morning overlap) and weekend-flat — the regime gate already blocks the worst sideways hours, but a session that overlaps the two most liquid USDJPY windows gives the consensus the highest-quality inputs.

Strategy Logic

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

Family: TrendFollow Magic: 22218018 Version: 2.00

BRIEF: Multi-indicator consensus vote (inlined from MT5-native primitives — no iCustom). Five independent signals vote: (1) Trend = ADX>thr + DI side + price>WMA + AMA-slope; (2) RSI = MTF RSI reversal (H1+H4 avg) + base RSI extreme; (3) Stoch = main/signal cross in extreme zone; (4) MACD = main/signal cross + histogram direction; (5) S/R = proximity to inline daily pivot/Tirone level. Regime gate (ADX + ATR-pctile + BB-width) blocks Range/Choppy. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • ResetDayState()
  • RefreshDayIfNeeded()
  • NL()
  • AdjPrice()
  • IsNewBar()
  • MinStopsDist()
  • ClampVolume()
  • RegimeAllowsEntry()
  • VoteTrend()
  • VoteRSI()
  • VoteStoch()
  • VoteMACD()
  • ...and 12 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (21 total across 5 groups):

  • [=== GENERAL ===] InpMagic = 22218018 // Magic number (id)
  • [=== GENERAL ===] InpTradeComment = "Psgrowth.com Expert_18018" // Trade comment
  • [=== GENERAL ===] InpDryRun = true // Dry-run (no real orders)
  • [=== GENERAL ===] InpKillSwitch = false // Emergency kill switch
  • [=== GENERAL ===] InpMaxSpreadPts = 30.0 // Max spread (points)
  • [=== REGIME ===] InpADXPeriod = 14 // ADX period (bars)
  • [=== REGIME ===] InpADXMinTrend = 20.0 // ADX min for trend regime
  • [=== REGIME ===] InpATRPctLookback = 50 // ATR percentile lookback (bars)
  • [=== SIGNAL ===] InpRSIPeriod = 14 // RSI period (bars)
  • [=== SIGNAL ===] InpRSIOversold = 30.0 // RSI oversold threshold
  • [=== SIGNAL ===] InpRSIOverbought = 70.0 // RSI overbought threshold
  • [=== SIGNAL ===] InpMAPeriod = 20 // Trend WMA period (bars)
  • [=== SIGNAL ===] InpStochPeriod = 14 // Stochastic period (bars)
  • [=== RISK & SIZING ===] InpCapitalCapAmount = 0.0 // Capital cap ($ equity)
  • [=== RISK & SIZING ===] InpCapitalCapFloor = 50.0 // Floor below which no entry ($)
  • [=== RISK & SIZING ===] InpRiskPercent = 0.5 // Risk per trade (% of eff cap)
  • [=== RISK & SIZING ===] InpDailyLossPct = 3.0 // Daily loss limit (% eff cap)
  • [=== RISK & SIZING ===] InpATRSLMult = 1.5 // SL = ATR * mult (price)
  • [=== EXIT / MANAGE ===] InpRR = 1.5 // Reward:Risk for TP
  • [=== EXIT / MANAGE ===] InpATRTrailMult = 2.0 // ATR trailing multiplier
  • [=== EXIT / MANAGE ===] InpMaxBarsInTrade = 100 // Max bars in trade
Pseudocode
// Pipsgrowth EX18018 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Multi-indicator consensus vote (inlined from MT5-native primitives — no iCustom). Five independent signals vote: (1) Trend = ADX>thr + DI side + price>WMA + AMA-slope; (2) RSI = MTF RSI reversal (H1+H4 avg) + base RSI extreme; (3) Stoch = main/signal cross in extreme zone; (4) MACD = main/signal cross + histogram direction; (5) S/R = proximity to inline daily pivot/Tirone level. Regime gate (ADX + ATR-pctile + BB-width) blocks Range/Choppy. 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:
M15M5M30

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
InpMagic22218018Magic number (id)
InpTradeComment"Psgrowth.com Expert_18018"Trade comment
InpDryRuntrueDry-run (no real orders)
InpKillSwitchfalseEmergency kill switch
InpMaxSpreadPts30.0Max spread (points)
InpADXPeriod14ADX period (bars)
InpADXMinTrend20.0ADX min for trend regime
InpATRPctLookback50ATR percentile lookback (bars)
InpRSIPeriod14RSI period (bars)
InpRSIOversold30.0RSI oversold threshold
InpRSIOverbought70.0RSI overbought threshold
InpMAPeriod20Trend WMA period (bars)
InpStochPeriod14Stochastic period (bars)
InpCapitalCapAmount0.0Capital cap ($ equity)
InpCapitalCapFloor50.0Floor below which no entry ($)
InpRiskPercent0.5Risk per trade (% of eff cap)
InpDailyLossPct3.0Daily loss limit (% eff cap)
InpATRSLMult1.5SL = ATR * mult (price)
InpRR1.5Reward:Risk for TP
InpATRTrailMult2.0ATR trailing multiplier
InpMaxBarsInTrade100Max bars in trade
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18018.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18018 USDJPY_MultiIndicator_System — 5-signal consensus vote, 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>

//=========================== INPUTS =================================
input group "=== GENERAL ==="
input int     InpMagic            = 22218018;     // Magic number (id)
input string  InpTradeComment     = "Psgrowth.com Expert_18018"; // Trade comment
input bool    InpDryRun           = true;         // Dry-run (no real orders)
input bool    InpKillSwitch       = false;        // Emergency kill switch
input double  InpMaxSpreadPts     = 30.0;         // Max spread (points)

input group "=== REGIME ==="
input int     InpADXPeriod        = 14;           // ADX period (bars)
input double  InpADXMinTrend      = 20.0;         // ADX min for trend regime
input int     InpATRPctLookback   = 50;           // ATR percentile lookback (bars)

input group "=== SIGNAL ==="
input int     InpRSIPeriod        = 14;           // RSI period (bars)
input double  InpRSIOversold      = 30.0;         // RSI oversold threshold
input double  InpRSIOverbought    = 70.0;         // RSI overbought threshold
input int     InpMAPeriod         = 20;           // Trend WMA period (bars)
input int     InpStochPeriod      = 14;           // Stochastic period (bars)

input group "=== RISK & SIZING ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable         // Capital allocation cap on
input double  InpCapitalCapAmount = 0.0;        // Capital cap ($ equity)
input double  InpCapitalCapFloor  = 50.0;         // Floor below which no entry ($)
input double  InpRiskPercent      = 0.5;          // Risk per trade (% of eff cap)
input double  InpDailyLossPct     = 3.0;          // Daily loss limit (% eff cap)
input double  InpATRSLMult        = 1.5;          // SL = ATR * mult (price)

input group "=== EXIT / MANAGE ==="
input double  InpRR               = 1.5;          // Reward:Risk for TP
input double  InpATRTrailMult     = 2.0;          // ATR trailing multiplier
input int     InpMaxBarsInTrade   = 100;          // Max bars in trade

//=========================== GLOBALS ================================
CTrade         trade;
CSymbolInfo    sym;
CPositionInfo  pos;
CAccountInfo   acc;

int    hADX, hATR, hBB, hRSI_H1, hRSI_H4, hRSI_M15, hStoch, hMACD, hMAfast;
int    hATR_HTF;

double g_tick_value, g_tick_size, g_point;
int    g_digits;
long   g_stops_lvl, g_freeze_lvl;
double g_eff_capital = 0.0;
double g_day_start_equity = 0.0;

Full source code available on download

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

Tags:ex18018trendfollowpipsgrowthfreemt5usdjpy

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