P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18023 TrendFollow

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

Pipsgrowth.com EX18023 UT Bot EA — ATR trailing-stop trend follow, full 12-layer stack.

Overview

Pipsgrowth EX18023 TrendFollow is a UT Bot Alert implementation rebuilt from the canonical TradingView Pine port and ported into a single-instrument MT5 Expert Advisor. The strategy treats the market as a sequence of trailing-stop flips: each completed bar the EA walks a stop forward through the recent ATR-scaled envelope around price, and when the close of the most recent bar punches through that envelope on the opposite side, a trend flip fires. The whole rest of the file is dedicated to deciding whether that flip is worth trading and to managing the resulting position through to a clean exit. The EA is hardwired to magic 22218023, defaults to USDJPY, and ships in v2.00 with no martingale, no grid layer, and no pyramid — what you see in the source is the entire strategy, no hidden branches.

The signal core lives in CoreSignal(). On every closed bar the function copies N+1 closes and N+1 ATR(10) values into as-series arrays, seeds a running trail variable with the oldest close, and then iterates forward through 250 bars (the TRAIL_SYNC_LOOKBACK constant). At each bar the EA computes a no-loss envelope of InpKeyValue × ATR(10) (the default sensitivity is 2.0 × ATR). If both the current close and the prior close are above the trail, the trail ratchets up to max(trail, close − nLoss). If both are below, the trail ratchets down. If the bars disagree, the trail resets to close ± nLoss. After the forward walk the EA captures the trail value at bar 1 (last closed) and bar 2 (the one before), classifies each bar's trend as +1 / −1 / 0 by comparing close to trail, and returns +1 if bar 1 is bullish and bar 2 was not bullish — the canonical trend flip. Confidence is computed as 100 × |close[1] − trail1| / nLoss1, capped at 100. A CurrentTrend() helper runs the same forward walk without the flip logic and is used by the exit path. InpATRPeriod default 10 makes the envelope tighter than the usual ATR(14); a lower value trades more flips, a higher value filters for larger swings.

A higher-timeframe confirmation sits between CoreSignal and the order ticket. ConfirmEntry() copies the close value of the H1 EMA(50) (InpHTF=8 maps through MapTimeframeInt to PERIOD_H1 — values 1–7 also resolve to M1/M5/M15/M30/H1/H4/D1 respectively, anything else falls to H1), then blocks any long whose bar-1 close is below that H1 EMA and any short whose bar-1 close is above it. The spread cap InpMaxSpreadPts=35.0 and the session window SESSION_START_HOUR=6 / SESSION_END_HOUR=21 are also enforced inside this confirm step. This is the layer that drops counter-trend signals during strong H1 moves and that prevents the EA from acting during the Asian dead zone or the Friday 21:00 weekend window.

The regime classifier feeds the no-trade gate and the exit logic. DetectRegime() pulls ADX(14), ATR(14), and the upper, lower, and middle Bollinger Band (20, 2.0) on the closed bar, then computes an ATR-percentile rank by counting how many of the last InpATRPctLookback=60 ATR(14) values are smaller than or equal to the current ATR. The function emits one of seven enum states: REG_STRONG_TREND when ADX≥30, REG_WEAK_TREND when ADX≥InpADXMin=20, REG_EXPAND when the ATR-percentile is above 70 AND the current BB width is at least 15% wider than the prior bar, REG_COMPRESS when the ATR-percentile is below 25, REG_BREAKOUT when the BB width is below 0.0015 with ADX rising into the prior bar, and REG_RANGE as the default. Insufficient data returns REG_CHOPPY, which is treated as a hard block. Inside OppositeAndRegimeExit() a flip into REG_CHOPPY, REG_RANGE, or REG_COMPRESS force-closes any open position — the same classifier is used on the way in (via NoTradeBlock) and on the way out.

The no-trade gate that runs before any order is sent has nine explicit checks, each with its own reason string that gets logged. In order: kill switch is on, spread is above the 35-point cap, the current server hour is outside the 6–21 window, the regime came back as CHOPPY, the last closed bar's range is more than 3× the current ATR(14) (a news-spike / big-candle guard), there is an active cooldown after three consecutive losses, effective capital fell below the $50 floor, the realized P&L today has already eaten InpDailyLossPct=3% of effective capital, or the position count is at MAX_OPEN_TRADES=1. Each block is logged with the regime enum and the signal confidence so the user can see why the EA is sitting still.

Position sizing follows the standard risk-per-stop formula. EffectiveCapital() returns account equity unless InpCapitalCapAmount is set, in which case it caps the equity at that dollar figure — a $200 account with InpCapitalCapAmount=100 trades as if it were a $100 account for both sizing and daily loss computation. CalcLots() then divides InpRiskPercent=0.5% of effective capital by the per-lot loss at the stop distance, where the stop is InpATRSLMult=1.5 × ATR(14) on the closed bar (floored against the broker stops-level distance). The lot is clamped to the symbol lot step and to g_vol_min. The take-profit is computed as InpRRTP=2.0 × the stop distance — a fixed 1:2 R:R structure. OrderCalcMargin is called before send; if free margin is insufficient, the entry is skipped with a log line. The opposite-side position close is part of TryEntry(): if a BUY signal fires while a SELL magic 22218023 position is open, that position is closed first via TryClose_EX18023, then the BUY is sent. This is the canonical UT Bot flip behavior — the EA does not hold both directions at once.

Trade management runs on every tick through ManageExits(). The flow is: read the closed-bar ATR(14), compute slDist = ATR × 1.5 and the open P&L in R-multiples, then step through four exit paths in order. (1) Break-even at +1R: if curSL is below the entry price, push it to entry (broker-stops-level permitting). (2) One-shot 50% partial at +1R: if PartialAlreadyDone() returns false for the ticket, close 50% of the position and mark the ticket done. (3) ATR trail at InpATRTrailMult=2.0 × ATR(14): for longs, set the new stop to bid − trailDist if it is above the current stop; for shorts, set the new stop to ask + trailDist if it is below the current stop. (4) Time exit at MAX_BARS_IN_TRADE=100 bars: count bars between the position's open time and the current time, force-close if it hits the cap. After the per-position loop, OppositeAndRegimeExit() makes a second pass: any position whose side disagrees with CurrentTrend() is closed (the UT Bot flip fired the other way), and any position held while the regime is now CHOPPY / RANGE / COMPRESS is closed. The retry helpers TryClose_EX18023, TryClosePartial_EX18023, and TryModify_EX18023 each loop up to three times on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED with 100–200 ms sleeps — standard PipsGrowth retry plumbing.

The MT5 Strategy Tester is fed a custom fitness function: (net_profit × profit_factor) / (1 + |balance_dd|), with a hard minimum of 30 trades. A high-PF low-DD result scores best; a profitable run with a high DD or low PF will be de-prioritized in the optimizer. The default input set is engineered for the M15 chart — TRAIL_SYNC_LOOKBACK=250 bars of memory gives the trail plenty of time to settle into the live envelope. The InpDryRun=true default sends Print() statements instead of real orders, so the first week should be journal-only on a demo account, watching the PrintFormat log lines for the regime, confidence, and SL/TP distances that would have been used. Once the user is comfortable with the behavior, flipping InpDryRun=false is the only change required to go live.

Strategy Deep Dive

On every tick ManageExits() reads ATR(14) on the closed bar, walks the open position list, and runs the break-even / partial / ATR-trail / time-exit pipeline; a second pass closes on opposite UT Bot flip or regime change. Once a new bar opens, CoreSignal() runs the 250-bar forward walk of the UT Bot envelope, captures trail at bar 1 and bar 2, returns the trend-flip signal and a 0–100 confidence. The no-trade gate then checks kill switch, spread ≤ 35 points, session 6–21 server, regime not CHOPPY, big-candle (>3× ATR), cooldown-after-3-losses, $50 capital floor, 3% daily realized loss, and the single-position cap; the H1 EMA(50) confirm adds HTF agreement, then TryEntry() closes any opposing magic position before sizing the lot at 0.5% risk and sending the order.

Entry Signal

A long entry fires when CoreSignal() returns +1 (the bar-1 close is above the UT Bot trail computed from ATR(10) × 2.0, AND the bar-2 trend was not +1), the H1 EMA(50) confirm agrees, the regime is not CHOPPY, and the no-trade gate clears. Shorts are the mirror. The trail sync walks forward over 250 closed bars (TRAIL_SYNC_LOOKBACK) before judging the flip.

Exit Signal

Positions close on whichever fires first: an opposite UT Bot trend flip (CurrentTrend() flips sign on a closed bar), a regime change into CHOPPY / RANGE / COMPRESS, the 100-bar time cap, or the broker hitting SL or TP. The trailing stop ratchets at 2.0 × ATR(14) on every tick once the position is in profit.

Stop Loss

Initial stop is InpATRSLMult = 1.5 × ATR(14) on the closed bar, floored against the broker stops-level distance. Break-even fires once at +1R MFE, lifting the stop to entry. The 2.0 × ATR(14) trail then ratchets the stop in the profitable direction on every tick.

Take Profit

Fixed take-profit at 2.0 × the stop distance (1:2 R:R) is sent with the order via InpRRTP = 2.0. In addition, a one-shot 50% partial close fires at +1R MFE and locks half the position; the remaining half is left to trail or hit TP.

Best For

Best deployed on USDJPY M15 (the default chart for magic 22218023) with a minimum $100 account. The $50 capital floor and 0.5% per-trade risk keep drawdowns contained on small balances, and the 35-point spread cap means a low-spread ECN or standard account is required for live use. The 6–21 server session covers the full London-through-NY overlap for most broker timezones; the M5 and H1 charts also work, though the 100-bar time exit and the 250-bar trail sync will scale accordingly.

Strategy Logic

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

Family: TrendFollow Magic: 22218023 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:

  • ADX
  • ATR
  • ATRUT
  • BB
  • HTFEMA

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 = 22218023 // Magic number (id)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18023" // 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 ATR Trailing Stop ===] InpATRPeriod = 10 // UT Bot ATR period (bars)
  • [=== Signal: UT Bot ATR Trailing Stop ===] InpKeyValue = 2.0 // UT Bot sensitivity (x ATR)
  • [=== Regime ===] InpADXMin = 20.0 // Min ADX for trend regime
  • [=== Regime ===] InpATRPctLookback = 60 // ATR percentile lookback (bars)
  • [=== Confirm & HTF ===] InpHTF = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend time-frame
  • [=== Confirm & HTF ===] InpHTFEMA = 50 // HTF EMA period (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 (x ATR)
  • [=== Exit / Manage ===] InpRRTP = 2.0 // TP distance (x SL distance)
  • [=== Exit / Manage ===] InpATRTrailMult = 2.0 // In-trade ATR trail (x ATR)
Pseudocode
// Pipsgrowth EX18023 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

Optimized Brokers:
ExnessIC Markets
Optimized Symbols:
USDJPY
Optimized Timeframes:
M15M5H1

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
InpMagic22218023Magic number (id)
InpTradeComment"Psgrowth.com Expert_18023"Trade comment
InpDryRuntrueDry-run: no real sends
InpKillSwitchfalseKill switch (closes all on tick)
InpMaxSpreadPts35.0Max spread (points)
InpATRPeriod10UT Bot ATR period (bars)
InpKeyValue2.0UT Bot sensitivity (x ATR)
InpADXMin20.0Min ADX for trend regime
InpATRPctLookback60ATR percentile lookback (bars)
InpHTF8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend time-frame
InpHTFEMA50HTF EMA period (bars)
InpCapitalCapAmount0.0Capital cap amount ($ equity)
InpCapitalCapFloor50.0Capital cap floor ($)
InpRiskPercent0.5Risk per trade (% of eff cap)
InpDailyLossPct3.0Daily loss limit (% eff cap)
InpATRSLMult1.5SL distance (x ATR)
InpRRTP2.0TP distance (x SL distance)
InpATRTrailMult2.0In-trade ATR trail (x ATR)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18023.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18023 UT Bot EA — 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            = 22218023;  // Magic number (id)
input string          InpTradeComment     = "Psgrowth.com Expert_18023"; // 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.

Tags:ex18023trendfollowpipsgrowthfreemt5usdjpy

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