Pipsgrowth EX16003 Trend
MT5 Expert Advisor (Open Source) · XAUUSD, EURUSD, GBPUSD, USDJPY · M5, M15
Pipsgrowth.com EX16003 UT_Bot_Alerts — ATR trailing stop crossover EA, full 12-layer stack.
Overview
EX16003 UT Bot Alerts is a single-indicator trend follower that ports the UT Bot concept from TradingView Pine Script into MetaTrader 5. The whole entry decision rests on one relationship: where price sits relative to a moving trailing stop whose distance from price scales with the Average True Range. When price crosses above that trailing stop, the EA opens a buy; when it crosses below, it opens a sell. There is no second filter, no confirmation oscillator, no multi-timeframe agreement. The trade is a pure function of the ATR trailing line and which side of it the most recent bar closed on.
The trailing stop itself is built inside CalculateUTBot(). The function pulls a single ATR value with period InpATRPeriod (default 10) and multiplies it by InpKeyValue (default 1.0) to get nLoss. The EA then evaluates the closed bar (shift 1) and the bar before that (shift 2) against the previously stored trailing stop. Four cases follow the original Pine Script logic exactly: if both current and previous prices are above the previous trailing stop, the new stop ratchets up to the max of (previous stop, current price minus nLoss). If both are below, it ratchets down to the min of (previous stop, current price plus nLoss). If only the current price is above, the stop resets to current price minus nLoss — this is the bullish flip case. If only the current price is below, the stop resets to current price plus nLoss — the bearish flip case. The g_pos state variable tracks which side the trend is currently considered to be on (1, -1, or 0 for FLAT).
The entry signal is the actual crossover, not just the trend state. signal = 1 fires when previous price was at or below the previous trailing stop and current price is above the current trailing stop. signal = -1 fires when previous price was at or above the previous stop and current price is below. The line that drives this is drawn on the chart in DrawTrailingStopLine() as a horizontal OBJ_HLINE — lime when g_pos == 1, red when g_pos == -1, yellow when flat — so the user can see in real time what the EA is reacting to.
The source price that drives both the trailing stop and the crossover is selectable. With InpUseHeikinAshi = false (the default), the EA uses the regular close of the chart. With InpUseHeikinAshi = true, GetSourcePrice() returns the Heiken Ashi close calculated as the average of open, high, low, and close of that bar. Heiken Ashi smooths the noise in the trailing stop, reduces whipsaw crossovers, and is a common pairing with UT Bot on noisier assets like XAUUSD M5.
Position management runs every tick through ManageOpenPositions() and is built as three independent stages that activate in sequence as profit grows. Stage 1 (Breakeven) fires when profit reaches InpBEStart (default 200 points). The stop moves to entry plus InpBEOffset (default 30 points), locking in a small profit. Stage 2 (Trailing) activates at InpTrailStart (default 300 points) and parks the stop at current price minus InpTrailDistance (default 150 points), never back below entry. Stage 3 (Tighten) activates at InpTightenStart (default 600 points) and tightens the stop further to price minus InpTightenDist (default 80 points). The new SL is the maximum of all active stages for buys, the minimum for sells, and only moves in the protective direction — never loosening. This is a fixed-step ratchet, not a Chandelier or ATR-based trail.
The pyramid option is off by default. When InpAllowPyramid = true, the EA can add up to InpMaxPyramid (default 3) positions in the same direction. ManagePyramiding() enforces two strict gates before adding: every existing position in the direction must have its stop at least InpMinSecuredProfit (default 100 points) into profit, and the current price must be at least InpPyramidDistance (default 300 points) beyond the most recent entry. The all-secured rule means the EA will not pyramid into a losing basket — it waits until the prior position is at breakeven-plus before scaling in. This is the safer of the two pyramid flavors, but the default-off setting reflects a single-position intent.
Drawdown protection is a hard circuit breaker. CheckDrawdownLimits() runs every tick and computes two numbers: the daily loss as a percentage of the balance at session start (g_dailyStartBalance is reset at 00:00 server in CheckNewDay()), and the equity drawdown as a percentage of the all-time peak equity. If either exceeds its limit — InpMaxDailyLoss (default 3.0%) or InpMaxEquityLoss (default 10.0% from peak) — the EA sets g_ddLimitHit = true, optionally closes all positions if InpCloseOnDDLimit = true (the default), fires an Alert, and refuses to open new positions for the rest of the day. The flag only resets at the next CheckNewDay pass.
Lot sizing has two modes via the LOT_MODE_FIXED / LOT_MODE_RISK enum. Default is risk-based: CalculateLotSize() reads the current balance, multiplies by InpRiskPercent (default 0.5%), divides by the per-point SL value, and floors the result to the broker's lot step. The result is then clamped to [vol_min, vol_max, InpMaxLotSize=5.0]. OrderCalcMargin is called before every send to refuse the order if free margin is insufficient. The retry loop in OpenPosition() makes up to 3 attempts, refreshing the price, SL and TP on each retry, and breaks out on any retcode other than REQUOTE / PRICE_CHANGED / PRICE_OFF / TIMEOUT.
Initial stop loss is fixed at InpStopLoss (default 500 points, 5 pips on 5-digit XAUUSD or 50 pips on EURUSD). Take profit is fixed at InpTakeProfit (default 1500 points, 15 pips on XAUUSD or 150 pips on EURUSD), giving a 1:3 reward-to-risk ratio. Set InpTakeProfit to 0 to disable the TP and let trades run to SL or reverse-signal exit. The time filter, when enabled, restricts trading to server hours InpStartHour (default 8) through InpEndHour (default 20), blocks Saturday and Sunday, and force-closes all positions on Friday at InpFridayCloseHour (default 20). When the time filter is off, the EA trades whenever the market is open and the spread is within InpMaxSpread (default 300 points).
What to expect in backtest: a choppy market produces frequent flip-flop entries that each get stopped at 500 points, so the equity curve on a ranging pair is mostly flat with occasional deep drawdowns when volatility expands. The trailing stop is what makes the strategy net-positive on trending pairs — XAUUSD M5 in a directional session will often let the BE/Trail/Tighten stack run the position into the 1500-point TP. The strategy works best on a single symbol per chart, on an ECN or RAW-spread broker where the 300-point cap does not filter out normal hours, and on a server where the M5 bar close aligns with a relatively quiet spread regime.
Strategy Deep Dive
Each new M5 bar, CalculateUTBot() pulls one ATR(10) value, multiplies it by InpKeyValue (default 1.0) to get nLoss, then advances the persistent g_xATRTrailingStop by one of four Pine-Script-derived rules depending on whether the current and previous bar closes sit above, below, or across the previous stop. A signal = 1 fires when the previous close was at or below the prior stop and the current close is above the new stop; signal = -1 on the mirror. OnTick wraps the signal through a chain of gates — CheckSpread against InpMaxSpread (300 points), CheckTimeFilter (optional 8-20 server window with Friday close at 20), CheckDrawdownLimits (3% daily / 10% equity from peak trip) — then either reverses via ClosePositionsByType() and opens the new direction with OpenPosition(), or adds a pyramid layer via ManagePyramiding() if all existing positions in the direction are already secured by at least 100 points and the price is 300 points beyond the last entry. Every tick, ManageOpenPositions() walks the three-stage ratchet (BE at 200pt → entry+30, Trail at 300pt → price-150, Tighten at 600pt → price-80) over each open ticket. The trailing stop is also drawn as a horizontal HLINE on the chart for visual confirmation, and a 220x160 corner panel shows the current trend, spread, position counts, P/L, and DD status.
Entries are triggered by a single crossover between the most recent bar's source price and the dynamically computed ATR trailing stop. A buy fires when the previous bar closed at or below the prior trailing stop and the current bar closes above the new trailing stop (computed as nLoss = InpKeyValue * ATR(10) away from price); a sell fires on the mirror condition. The source price is either the regular close or, if InpUseHeikinAshi = true, the Heiken Ashi close, which smooths out chop and reduces false flips on XAUUSD M5.
Exits run on a three-stage ratchet: breakeven at 200 points of profit (sliding SL to entry +30), trailing at 300 points (price −150 points), tightening to 80 points at 600 points of profit. A reverse crossover — current bar closing back across the trailing stop — closes the open position via ClosePositionsByType() and opens the new direction in the same tick. Initial fixed take profit at 1500 points is the other exit path; setting it to 0 leaves trades to run to SL or reverse-signal.
Every order is opened with a fixed InpStopLoss of 500 points (5 pips on 5-digit XAUUSD, 50 pips on EURUSD), placed by OpenPosition() based on the current Ask/Bid at the moment of execution. The stop is then progressively ratcheted by ManageOpenPositions to breakeven, then a trail at price−150, then a tightened 80-point stop once profit exceeds 600 points, never moving backward.
Default take profit is InpTakeProfit = 1500 points (15 pips on 5-digit XAUUSD, 150 pips on EURUSD) for a fixed 1:3 reward-to-risk ratio, applied at entry. Setting InpTakeProfit to 0 disables it, leaving the position to close on the BE/Trail/Tighten stack, the fixed SL, or a reverse UT Bot crossover.
Best run on XAUUSD M5, EURUSD M5, GBPUSD M5, or USDJPY M5, on an ECN or RAW-spread broker where the 300-point InpMaxSpread cap does not filter out normal-session quotes. Minimum recommended balance is $100 (with the default 0.5% risk, that yields a 0.01-lot position at the 500-point stop on XAUUSD), and risk is rated MEDIUM because the ATR trailing stop does most of the work — there is no daily-trade cap, no regime filter, and the pyramid path can stack 3 positions in a runaway move.
Strategy Logic
Pipsgrowth EX16003 Trend — Strategy Logic Analysis (from .mq5 source)
Family: Trend
Magic: 22216003
Version: 2.00
BRIEF:
UT Bot Alerts EA — converted from Pine Script, uses ATR- based dynamic trailing stop for signal generation. BUY when price crosses above ATR trailing stop, SELL when below. Supports Heiken Ashi, BE, trailing, DD protection. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
SetProperFillingMode()GetSourcePrice()CalculateUTBot()DrawTrailingStopLine()ClosePositionsByType()CheckSpread()CheckTimeFilter()CheckDrawdownLimits()CheckNewDay()CalculateLotSize()NormalizeLot()OpenPosition()- ...and 10 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (40 total across 9 groups):
- [=== Trade Execution ===]
InpMagicNumber=22216003// Magic Number - [=== Trade Execution ===]
InpSlippage= 30 // MaxSlippage(points) - [=== Trade Execution ===]
InpMaxSpread= 300 // MaxSpread(points, 0=disable) - [=== Trade Execution ===]
InpMaxRetries= 3 // Order Retry Attempts - [=== Trade Execution ===]
InpTradeComment= "Psgrowth.com Expert_16003" // TradeComment - [=== Money Management ===]
InpLotMode=LOT_MODE_RISK// Lot Sizing Mode - [=== Money Management ===]
InpFixedLotSize=0.01// Fixed Lot Size - [=== Money Management ===]
InpRiskPercent=0.5// RiskPercent(%) - [=== Money Management ===]
InpMaxLotSize=5.0// Maximum Lot Size - [=== SL/TP Settings ===]
InpStopLoss= 500 // StopLoss(points) - [=== SL/TP Settings ===]
InpTakeProfit= 1500 // TakeProfit(points, 0=disable) - [=== Strategy: UT Bot ===]
InpKeyValue=1.0// KeyValue(Sensitivity, 1-3) - [=== Strategy: UT Bot ===]
InpATRPeriod= 10 //ATRPeriod - [=== Strategy: UT Bot ===]
InpUseHeikinAshi=false// Use Heiken Ashi Candles - [=== Time Filter ===]
InpUseTimeFilter=false// Enable Time Filter - [=== Time Filter ===]
InpStartHour= 8 // StartHour(Server Time) - [=== Time Filter ===]
InpEndHour= 20 // EndHour(Server Time) - [=== Time Filter ===]
InpTradeFriday=true// Trade on Friday - [=== Time Filter ===]
InpFridayCloseHour= 20 // Friday: Close All After Hour - [=== Trade Management ===]
InpUseBreakeven=true// Enable Breakeven - [=== Trade Management ===]
InpBEStart= 200 // BEStart(points profit) - [=== Trade Management ===]
InpBEOffset= 30 // BEOffset(points above entry) - [=== Trade Management ===]
InpUseTrailing=true// Enable Trailing Stop - [=== Trade Management ===]
InpTrailStart= 300 // TrailStart(points profit) - [=== Trade Management ===]
InpTrailDistance= 150 // TrailDistance(points) - [=== Trade Management ===]
InpUseTighten=true// Enable Tighten SL - [=== Trade Management ===]
InpTightenStart= 600 // TightenStart(points profit) - [=== Trade Management ===]
InpTightenDist= 80 // TightenDistance(points) - [=== Pyramid Settings ===]
InpAllowPyramid=false// Allow Pyramid Positions - [=== Pyramid Settings ===]
InpMaxPyramid= 3 // Max Pyramid Levels - [=== Pyramid Settings ===]
InpPyramidDistance= 300 // Min Distance BetweenEntries(points) - [=== Pyramid Settings ===]
InpMinSecuredProfit= 100 // Min Secured Profit BeforeNext(points) - [=== Drawdown Protection ===]
InpUseDDProtection=true// Enable Drawdown Protection - [=== Drawdown Protection ===]
InpMaxDailyLoss=3.0// Max Daily Loss % (0=disabled) - [=== Drawdown Protection ===]
InpMaxEquityLoss=10.0// Max Equity Loss % fromPeak(0=disabled) - [=== Drawdown Protection ===]
InpCloseOnDDLimit=true// Close All When DD Limit Hit - [=== Display ===]
InpShowPanel=true// Show Info Panel - [=== Display ===]
InpPanelX= 10 // Panel X Position - [=== Display ===]
InpPanelY= 30 // Panel Y Position - [=== Display ===]
InpDrawTrailLine=true// DrawATRTrailing Stop Line
// Pipsgrowth EX16003 Trend — Execution Flow (from source analysis)
// Family: Trend
// UT Bot Alerts EA — converted from Pine Script, uses ATR- based dynamic trailing stop for signal generation. BUY when price crosses above ATR trailing stop, SELL when below. Supports Heiken Ashi, BE, trailing, DD protection. 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
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 |
|---|---|---|
| InpMagicNumber | 22216003 | Magic Number |
| InpSlippage | 30 | Max Slippage (points) |
| InpMaxSpread | 300 | Max Spread (points, 0=disable) |
| InpMaxRetries | 3 | Order Retry Attempts |
| InpTradeComment | "Psgrowth.com Expert_16003" | Trade Comment |
| InpLotMode | LOT_MODE_RISK | Lot Sizing Mode |
| InpFixedLotSize | 0.01 | Fixed Lot Size |
| InpRiskPercent | 0.5 | Risk Percent (%) |
| InpMaxLotSize | 5.0 | Maximum Lot Size |
| InpStopLoss | 500 | Stop Loss (points) |
| InpTakeProfit | 1500 | Take Profit (points, 0=disable) |
| InpKeyValue | 1.0 | Key Value (Sensitivity, 1-3) |
| InpATRPeriod | 10 | ATR Period |
| InpUseHeikinAshi | false | Use Heiken Ashi Candles |
| InpUseTimeFilter | false | Enable Time Filter |
| InpStartHour | 8 | Start Hour (Server Time) |
| InpEndHour | 20 | End Hour (Server Time) |
| InpTradeFriday | true | Trade on Friday |
| InpFridayCloseHour | 20 | Friday: Close All After Hour |
| InpUseBreakeven | true | Enable Breakeven |
| InpBEStart | 200 | BE Start (points profit) |
| InpBEOffset | 30 | BE Offset (points above entry) |
| InpUseTrailing | true | Enable Trailing Stop |
| InpTrailStart | 300 | Trail Start (points profit) |
| InpTrailDistance | 150 | Trail Distance (points) |
| InpUseTighten | true | Enable Tighten SL |
| InpTightenStart | 600 | Tighten Start (points profit) |
| InpTightenDist | 80 | Tighten Distance (points) |
| InpAllowPyramid | false | Allow Pyramid Positions |
| InpMaxPyramid | 3 | Max Pyramid Levels |
| InpPyramidDistance | 300 | Min Distance Between Entries (points) |
| InpMinSecuredProfit | 100 | Min Secured Profit Before Next (points) |
| InpUseDDProtection | true | Enable Drawdown Protection |
| InpMaxDailyLoss | 3.0 | Max Daily Loss % (0=disabled) |
| InpMaxEquityLoss | 10.0 | Max Equity Loss % from Peak (0=disabled) |
| InpCloseOnDDLimit | true | Close All When DD Limit Hit |
| InpShowPanel | true | Show Info Panel |
| InpPanelX | 10 | Panel X Position |
| InpPanelY | 30 | Panel Y Position |
| InpDrawTrailLine | true | Draw ATR Trailing Stop Line |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX16003 UT_Bot_Alerts — ATR trailing stop crossover EA, full 12-layer stack."
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| ENUMS |
//+------------------------------------------------------------------+
enum ENUM_LOT_MODE
{
LOT_MODE_FIXED = 0, // Fixed Lot Size
LOT_MODE_RISK = 1 // Risk % of Balance
};
//+------------------------------------------------------------------+
//| INPUT GROUP: Trade Execution |
//+------------------------------------------------------------------+
input group "=== Trade Execution ==="
input int InpMagicNumber = 22216003; // Magic Number
input int InpSlippage = 30; // Max Slippage (points)
input int InpMaxSpread = 300; // Max Spread (points, 0=disable)
input int InpMaxRetries = 3; // Order Retry Attempts
input string InpTradeComment = "Psgrowth.com Expert_16003"; // Trade Comment
//+------------------------------------------------------------------+
//| INPUT GROUP: Money Management |
//+------------------------------------------------------------------+
input group "=== Money Management ==="
input ENUM_LOT_MODE InpLotMode = LOT_MODE_RISK; // Lot Sizing Mode
input double InpFixedLotSize = 0.01; // Fixed Lot Size
input double InpRiskPercent = 0.5; // Risk Percent (%)
input double InpMaxLotSize = 5.0; // Maximum Lot Size
//+------------------------------------------------------------------+
//| INPUT GROUP: Stop Loss & Take Profit |
//+------------------------------------------------------------------+
input group "=== SL/TP Settings ==="
input int InpStopLoss = 500; // Stop Loss (points)
input int InpTakeProfit = 1500; // Take Profit (points, 0=disable)
//+------------------------------------------------------------------+
//| INPUT GROUP: UT Bot Strategy |
//+------------------------------------------------------------------+
input group "=== Strategy: UT Bot ==="
input double InpKeyValue = 1.0; // Key Value (Sensitivity, 1-3)
input int InpATRPeriod = 10; // ATR Period
input bool InpUseHeikinAshi = false; // Use Heiken Ashi Candles
//+------------------------------------------------------------------+
//| INPUT GROUP: Time Filter |
//+------------------------------------------------------------------+
input group "=== Time Filter ==="
input bool InpUseTimeFilter = false; // Enable Time Filter
input int InpStartHour = 8; // Start Hour (Server Time)
input int InpEndHour = 20; // End Hour (Server Time)
input bool InpTradeFriday = true; // Trade on Friday
input int InpFridayCloseHour = 20; // Friday: Close All After HourFull 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.