Pipsgrowth EX18021 TrendFollow
MT5 Expert Advisor (Open Source) · USDJPY · M15, M5, H1
Pipsgrowth.com EX18021 USDJPY UT Bot — ATR trailing-stop trend follow, full 12-layer stack.
Overview
Pipsgrowth EX18021 is a UT Bot-style trend-following EA built for USDJPY. The strategy uses a Pine-style ATR trailing stop, ported to MT5 and walked forward across 250 closed bars, with signals triggering only on a trend flip.
The whole engine sits in OnTick. Each new bar DetectRegime() classifies the market using ADX(14), a 60-bar ATR percentile rank, and a Bollinger Band(20, 2.0) width ratio. Eight regimes are possible: REG_NONE, REG_STRONG_TREND, REG_WEAK_TREND, REG_RANGE, REG_BREAKOUT, REG_COMPRESS, REG_EXPAND, and REG_CHOPPY. ADX at or above 30 promotes strong trend; 20 to 30 gives weak trend; ATR percentile below 25 marks compression, above 70 combined with a 15% band-width expansion flags expansion; falling width with rising ADX catches breakout; everything else is range. CHOPPY is the only regime that fully blocks entries — RANGE and COMPRESS are tolerated at signal time but trigger a regime-change exit once a position is open.
CoreSignal() walks the UT Bot trail forward across TRAIL_SYNC_LOOKBACK (250) closed bars. The trail is seeded with the oldest close and updated per bar using a 2.0×ATR(10) buffer, with the canonical long-continuation, short-continuation, and flip-side rules. A long signal fires when the close of the last closed bar is above the trail while the prior bar's close was not; a short signal is the mirror. The same module also computes a confidence score between 0 and 100 from how far price has pushed beyond the trail relative to the 2×ATR band. The score is logged but not gated — the trade is binary on/off from the flip.
Before any order is sent, NoTradeBlock() runs through nine gates. Kill switch, spread above 35 points, low-liquidity session (outside the 6 to 21 server window), CHOPPY regime, news/big-candle detection (a bar with high-low range above 3×ATR), cooldown after three consecutive losses, equity below the $50 floor, daily loss above 3% of effective capital, and maximum open trade count of 1. The same function also blocks weekends: Friday after 21:00 server time and all of Saturday/Sunday. ConfirmEntry() adds the higher-timeframe EMA(50) on H1: longs require the last close above the H1 EMA, shorts require below. If the higher-timeframe copy returns fewer than two bars, the confirm is treated as passed (degraded but not blocking).
Sizing is risk-percent based. The lot formula reads riskMoney = g_eff_cap × 0.5%, then divides by per-lot loss = slDistance × tickValue / tickSize, before clamping to the broker's volume step and bounds. The capital cap input (InpCapitalCapAmount) defaults to 0, which disables it and uses raw equity; any non-zero value caps risk against the smaller of equity and the cap. The $50 equity floor still applies regardless. The minimum lot that comes out of the formula is checked against the broker's volume_min — if it falls below, the entry is skipped with a diagnostic print rather than sending an undersized order.
The stop is set at 1.5×ATR(14) from entry, with a minimum equal to the broker's stops level or 5 points, whichever is larger. Take-profit is twice that distance, giving a 1:2 risk-reward. TryEntry() also handles UT Bot flips correctly: if the new signal is opposite to an open position, the opposing position is closed first via TryClose_EX18021, then the new side is opened at market. Entry is suppressed on the same bar as the previous entry to avoid double-fires (g_last_entry_bar guard), and a one-attempt retry with 150ms sleep handles requotes and price-changed errors before the order is declared a hard fail.
Position management runs every tick. ManageExits() walks through all positions belonging to this magic and applies four layers in order. First, break-even: once price reaches +1R, the stop is ratcheted to the entry price. Second, partial TP: at +1R, 50% of the position is closed (one-shot per ticket, tracked in g_partial_done_tickets with a 64-ticket cap). Third, ATR trail: the stop follows price at 2.0×ATR(14) behind bid for longs or ahead of ask for shorts, but only forward — it never moves backward, and the minimum-stops-distance check prevents the trail from sitting too close to current price. Fourth, time exit: any position older than 100 bars is force-closed.
After the iteration, OppositeAndRegimeExit() runs a single pass. It calls CurrentTrend() (the same UT Bot walk, but with no flip detection — it just reports the current trend) and DetectRegime(). If the trend has flipped against an open position, the position is closed — this is the second, more aggressive exit on top of the per-tick trail. If the regime is now CHOPPY, RANGE, or COMPRESS, all positions are closed regardless of trend, because UT Bot flips generate noise in flat markets and the trail alone cannot react fast enough.
Loss tracking happens in OnTradeTransaction. After every deal that exits a position with negative realized P&L (profit + swap + commission), g_consec_losses increments. When it hits COOLDOWN_AFTER_LOSS (3), g_cooldown_until is set three bars into the future and the counter resets. A profitable deal zeroes the counter. The kill switch input is a manual close-all: setting it true causes every tick to call DoKillSwitch() and flatten the book, bypassing all other logic.
The OnTester() function reports a custom optimization criterion: (net × profitFactor) / (1 + |balance drawdown|), with a 30-trade minimum. This rewards raw return, penalizes drawdown, and refuses to score any backtest with fewer than 30 trades, which prevents overfitting to small samples during MetaTrader's strategy tester.
InpDryRun defaults to true, which means the EA logs the entry intent with full parameter snapshot but does not call Buy() or Sell(). Flip it to false to go live. The whole stack is portable: the inputs include a higher-timeframe selector (1 to 7 for M1 to D1, default 8 maps to H1 via MapTimeframeInt), the regime inputs are tunable, and the trail parameters can be retuned for different ATR behavior on different instruments. The trade comment is hard-coded to "Psgrowth.com Expert_18021" and the magic is 22218021, so multiple instances can run on the same account against different symbols without colliding.
Strategy Deep Dive
The strategy is a port of the UT Bot Alert indicator from TradingView Pine, with its ATR trailing stop walked forward across 250 closed bars on every new-bar decision tick. The 8-state regime classifier (ADX, ATR percentile, Bollinger width) gates which signals are eligible; CHOPPY regimes are blocked entirely while STRONG_TREND and WEAK_TREND both allow entries. The OnTester custom criterion (net × PF) / (1 + |DD|) with a 30-trade floor is built specifically to favor strategies that produce many trades and tolerate reasonable drawdown, rather than chasing a single large win. A configurable capital cap (InpCapitalCapAmount, default 0 = disabled) and a $50 equity floor prevent the EA from trading when account size is too small or when the operator wants to constrain risk. No-trade filters include the kill switch, the 35-point spread cap, the 3×ATR news-bar detector, the Friday-21:00 weekend proximity block, the Sat/Sun block, and the three-loss cooldown.
EX18021 fires a long signal when the close of the last closed bar moves above the UT Bot trail while the prior bar's close was at or below it; a short signal is the mirror. The trail itself is computed by walking forward across 250 closed bars using a 2.0×ATR(10) buffer with the canonical Pine-script long-continuation, short-continuation, and flip rules. After the signal fires, the regime must not be CHOPPY, the last close must be on the correct side of the H1 EMA(50), and spread must be below 35 points before the order is sent.
The primary exit is the take-profit at 2.0×SL distance, with a one-shot 50% partial close at +1R. The stop trails at 2.0×ATR(14) behind bid or ahead of ask, never moving backward, and is also lifted to break-even at +1R. An opposite trend flip on the UT Bot, a regime change to CHOPPY/RANGE/COMPRESS, or a 100-bar age limit each force a full close.
Stop is set at 1.5×ATR(14) from entry at order send, with a minimum of the broker's stops level or 5 points, whichever is larger. The stop is then lifted to break-even at +1R and trails forward at 2.0×ATR(14) without ever stepping backward.
Take-profit is set at 2.0×SL distance, giving a 1:2 risk-reward at order send. Half the position is closed at +1R as a partial TP, and the remaining half runs to the full TP or one of the trail/exit rules.
EX18021 is designed for USDJPY on M15 with M5 and H1 in the supported range. Recommended balance starts at $100 for a single-magic deployment, though the capital cap is opt-in. Run it on a low-spread broker (InpMaxSpreadPts = 35) and keep the server time in sync with your broker's quotes; the 6 to 21 server-time session gate targets the Asia-London overlap and the London-New York overlap, which carry USDJPY's deepest liquidity.
Strategy Logic
Pipsgrowth EX18021 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218021
Version: 2.00
BRIEF:
UT Bot Alert ATR trailing-stop trend-follow EA. Each closed bar the trail is walked forward using the canonical Pine port; signal fires on trend flip. Layered with ADX+ATR-pctile+ BB-width REGIME gate, HTF-EMA CONFIRM, full NO-TRADE filter, CAPITAL-ALLOCATION CAP, ATR SL/TP, break-even + partial TP + ATR trail, opposite-flip & regime-change exit, time-based exit, news-window skip, spread filter, magic-isolated daily-loss, OnTester custom criterion. All inlined from primitives. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
ADXATRATRUTBBHTFEMA
KEY FUNCTIONS:
NormPrice()ClampVol()MinStopsDist()SpreadPoints()InSession()IsNewBar()PartialAlreadyDone()MarkPartialDone()EffectiveCapital()RealizedPnLToday()CoreSignal()CurrentTrend()- ...and 13 more
INTERNAL CONSTANTS (1 total):
TRAIL_SYNC_LOOKBACK= 250 // ===================GLOBALS/HANDLES==============================
INPUT PARAMETERS (18 total across 6 groups):
- [=== Identity ===]
InpMagic=22218021// Magic number (id) - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_18021" // Trade comment - [=== Identity ===]
InpDryRun=true// Dry-run: no real sends - [=== Identity ===]
InpKillSwitch=false// Kill switch (closes all on tick) - [=== Identity ===]
InpMaxSpreadPts=35.0// Max spread (points) - [=== Signal: UT Bot
ATRTrailing Stop ===]InpATRPeriod= 10 // UT BotATRperiod (bars) - [=== Signal: UT Bot
ATRTrailing Stop ===]InpKeyValue=2.0// UT Bot sensitivity (xATR) - [=== Regime ===]
InpADXMin=20.0// MinADXfor trend regime - [=== Regime ===]
InpATRPctLookback= 60 //ATRpercentile lookback (bars) - [=== Confirm &
HTF===]InpHTF= 8 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) //HTFtrend time-frame - [=== Confirm &
HTF===]InpHTFEMA= 50 //HTFEMAperiod (bars) - [=== Risk &
Sizing(Capital Allocation Cap) ===]InpCapitalCapAmount=0.0// Capital cap amount ($ equity) - [=== Risk &
Sizing(Capital Allocation Cap) ===]InpCapitalCapFloor=50.0// Capital cap floor ($) - [=== Risk &
Sizing(Capital Allocation Cap) ===]InpRiskPercent=0.5// Risk per trade (% of eff cap) - [=== Risk &
Sizing(Capital Allocation Cap) ===]InpDailyLossPct=3.0// Daily loss limit (% eff cap) - [=== Exit / Manage ===]
InpATRSLMult=1.5// SL distance (xATR) - [=== Exit / Manage ===]
InpRRTP=2.0// TP distance (x SL distance) - [=== Exit / Manage ===]
InpATRTrailMult=2.0// In-tradeATRtrail (xATR)
// Pipsgrowth EX18021 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// UT Bot Alert ATR trailing-stop trend-follow EA. Each closed bar the trail is walked forward using the canonical Pine port; signal fires on trend flip. Layered with ADX+ATR-pctile+ BB-width REGIME gate, HTF-EMA CONFIRM, full NO-TRADE filter, CAPITAL-ALLOCATION CAP, ATR SL/TP, break-even + partial TP + ATR trail, opposite-flip & regime-change exit, time-based exit, news-window skip, spread filter, magic-isolated daily-loss, OnTester custom criterion. All inlined from primitives. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: ADX, ATR, ATRUT, BB, HTFEMA
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 | 22218021 | Magic number (id) |
| InpTradeComment | "Psgrowth.com Expert_18021" | Trade comment |
| InpDryRun | true | Dry-run: no real sends |
| InpKillSwitch | false | Kill switch (closes all on tick) |
| InpMaxSpreadPts | 35.0 | Max spread (points) |
| InpATRPeriod | 10 | UT Bot ATR period (bars) |
| InpKeyValue | 2.0 | UT Bot sensitivity (x ATR) |
| InpADXMin | 20.0 | Min ADX for trend regime |
| InpATRPctLookback | 60 | ATR percentile lookback (bars) |
| InpHTF | 8 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend time-frame |
| InpHTFEMA | 50 | HTF EMA period (bars) |
| InpCapitalCapAmount | 0.0 | Capital cap amount ($ equity) |
| InpCapitalCapFloor | 50.0 | Capital cap floor ($) |
| InpRiskPercent | 0.5 | Risk per trade (% of eff cap) |
| InpDailyLossPct | 3.0 | Daily loss limit (% eff cap) |
| InpATRSLMult | 1.5 | SL distance (x ATR) |
| InpRRTP | 2.0 | TP distance (x SL distance) |
| InpATRTrailMult | 2.0 | In-trade ATR trail (x ATR) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18021 USDJPY UT Bot — ATR trailing-stop trend follow, 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>
CTrade g_trade;
CPositionInfo g_pos;
CSymbolInfo g_sym;
CAccountInfo g_acc;
//=================== INPUTS (18 total) =============================
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 "=== Identity ==="
input long InpMagic = 22218021; // Magic number (id)
input string InpTradeComment = "Psgrowth.com Expert_18021"; // Trade comment
input bool InpDryRun = true; // Dry-run: no real sends
input bool InpKillSwitch = false; // Kill switch (closes all on tick)
input double InpMaxSpreadPts = 35.0; // Max spread (points)
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.
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.