P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16032 Trend

MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1

Pipsgrowth.com EX16032 DSUPERNATURAL1_UNIVERSAL_TRAILING_STOP_EA — universal trailing stop manager, full 12-layer stack.

Overview

EX16032 sits in a different category from every other EA in the EX16xxx lineup. It does not open positions, does not read indicators, does not scan for patterns, and does not gate trades by spread, session, or account equity. The entire program is a passive position manager — a utility that sits on a chart and watches every open position on the account, filters by magic number, and applies a pip-based trailing stop plus an optional chart-line virtual stop-loss and take-profit system. The header's '12-layer architecture' label describes the family template, not this EA's actual function. The wired layers in the source are two: MANAGE (the trailing stop) and EXIT (the virtual stop-loss and virtual take-profit).

The signature design choice is magic-number routing. The MagicNumbers input is a string of comma-separated longs — the default is "22216032", but the operator can pass in any number of upstream EAs at once by listing their magics: "22216001,22216002,22216024,22216030" for example. On OnInit, ParseMagicNumbers() StringSplits the string on commas, trims each token with StringTrim(), converts to long, and stores the result in the global magicNumbersArray[]. IsOurMagicNumber() then does a linear scan over the array on every position check. The intent: a single instance of EX16032 can trail positions opened by multiple signal EAs simultaneously, without ever touching positions opened by other EAs on the same account or by the same EAs running on other symbols.

The trailing stop itself runs in TrailingStop(), which OnTick calls on every price change. The function walks PositionsTotal() in reverse so removals do not disturb the loop, selects each position with positionInfo.SelectByIndex(i), and skips any position whose magic is not in the watched list. For positions that survive the filter, the logic is a textbook pip-step trail. TrailStartPips (50 pips default) is the activation distance — the position must move at least that far in profit before any trailing starts. TrailStopPips (20 pips default) is the trailing distance — once activated, the stop is held at currentPrice plus-or-minus trailStop. TrailStepPips (10 pips default) is the minimum increment — the stop is only ratcheted forward if the new stop is at least trailStep beyond the existing one, which prevents a flood of modify requests on every tick.

pipValue is computed once at OnInit as (SymbolInfoInteger(_Symbol, SYMBOL_DIGITS) % 2 == 1) ? _Point * 10 : _Point — that single expression handles 5-digit FX pairs (1.23456), 4-digit FX pairs (1.2345), 3-digit XAUUSD brokers (1234.567), and 2-digit metal quotes (1234.56) in one branch. The same EA can therefore manage a portfolio of XAUUSD positions, EURUSD positions, and XPTUSD positions without manual pip adjustments per symbol.

The math is straightforward but worth tracing. For a long: if currentPrice - openPrice >= trailStart, the trailing activates. The new stop is computed as NormalizeDouble(currentPrice - trailStop, digits). If a stop already exists, the code checks (currentPrice - trailStop) > currentStop — the new stop must be strictly tighter than the existing one. If the new stop is too close (less than trailStep away), the code bumps the new stop to currentStop + trailStep so it advances by at least one step. For a short, every comparison flips: openPrice - currentPrice >= trailStart, the new stop is currentPrice + trailStop, and the advance check is currentStop - newStop < trailStep. The modify is sent only if newStop != currentStop, going through the 3-attempt TryModify_EX16032() wrapper, which retries on REQUOTE, TIMEOUT, PRICE_OFF, and PRADE_CHANGED with 100ms backoff before giving up.

The virtual stops mechanism is the second major feature. When EnableVirtualStops is true, OnTick calls VirtualStopsDriver("listen") on every tick. The driver scans all OBJ_HLINE objects on the chart, filters to those whose name starts with # and has length at least 5, and whose color is clrRed (virtual SL) or clrBlue (virtual TP). The name is then parsed: the last 2 characters must be sl or tp, and the substring between # and sl or tp is the position ticket. The operator draws two horizontal lines named #12345678 sl (red) and #12345678 tp (blue) and the driver picks them up automatically.

The driver validates each candidate via positionInfo.SelectByTicket(ticket) and IsOurMagicNumber(positionInfo.Magic()) — a virtual stop is ignored if the position is closed, missing, or has a magic outside the watched list. For valid pairs, the driver reads the line's price, computes the polarity from position type (BUY = +1, SELL = -1), and checks if price has crossed the level. A long's virtual SL fires when level is at or below the bid; the virtual TP fires when level is at or above the bid; for shorts the comparisons flip. askbid is read from SymbolInfoDouble for the position's actual symbol, so a manager running on a multi-symbol account reads the correct bid or ask for each position.

The VirtualStopTimeout input (default 0, meaning disabled) adds a delay. If a long's bid drops to the red SL line and VirtualStopTimeout is greater than zero, the EA does NOT close immediately. Instead, it records the current TimeLocal() in the mem_to[] array indexed by ticket, prints "#<ticket> timeout of <N> seconds started", and continues. On subsequent ticks, while TimeLocal() - mem_to[index] is still within VirtualStopTimeout, the close is suppressed. Once the timeout expires, the next touch closes the position. The timeout applies only to virtual SL, not virtual TP. TryClose_EX16032 does the actual close, and on success the driver deletes both the #<ticket> sl and #<ticket> tp horizontal lines from the chart.

The cleanup path handles stale objects. If positionInfo.SelectByTicket(ticket) fails or the magic is not ours, the driver treats the object as orphaned and ObjectDelete(0, name) removes it. Otherwise the lines persist until either the close fires or the operator removes them by hand. The "set" / "modify" / "clear" / "partial" command paths in VirtualStopsDriver are alternative entry points an external script could use to programmatically create or update the lines — none are called from inside this EA, but the API is there for tooling.

The header claims a 12-layer architecture (REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester). Counting only the wired layers in the source: MANAGE is the trailing stop, EXIT is the virtual SL / TP. That is two. REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, SCALING, and OnTester are all absent. The EA has zero indicator handles — no iRSI, no iMA, no iBands, no iATR. The '12-layer stack' label in the description string is a family-template inheritance that does not describe this EA's actual function.

The seven inputs split into two groups. The Trailing Stop Parameters group is the heart: TrailStartPips=50, TrailStopPips=20, TrailStepPips=10, EnableVirtualStops=true, VirtualStopTimeout=0. The Identity group is the routing: MagicNumbers="22216032", InpTradeComment="Psgrowth.com Expert_16032". pipValue and magicNumbersArray are global-scope; trade, positionInfo, and orderInfo are the CTrade / CPositionInfo / COrderInfo objects the EA uses to talk to MT5. The helpers are minimal: ArraySearch() does a linear scan for a ulong in a ulong[], StringTrim() wraps the MQL string-trim pair, and the three TryXxx_EX16032 retry wrappers. TryClosePartial_EX16032 is defined but never referenced — dead code inherited from the family template.

The deployment context is what makes this EA useful. The strategy EAs in the EX16xxx family all open positions with hard-coded magic numbers, hard-coded SL/TP, and no trailing logic. EX16032 sits on top of them. The operator launches EX16032 on the same chart, sets MagicNumbers to the comma-separated list of EAs to manage, and EX16032 takes over the stop management: it applies a 50 / 20 / 10 pip trail to every open position whose magic is in the list, and lets the trader draw virtual TP lines on the chart that the EA will close on when price hits them. The 50-pip activation distance and 20-pip stop distance are sized for XAUUSD M5 volatility; the same values applied to a slow pair would trail too tight and clip the trend. This is a portfolio-level utility rather than a trade-entry bot: it does not generate signals, does not filter setups, does not size positions. It applies a single mechanical policy — trail with X/Y/Z pips, close at the chart's virtual TP if a line is present — to every position whose magic it has been told to watch.

Strategy Deep Dive

On every tick OnTick calls TrailingStop(), which walks PositionsTotal in reverse, filters by IsOurMagicNumber against the comma-separated MagicNumbers list, and only modifies positions whose magic is in the list. For surviving positions the trail activates at TrailStartPips profit, holds the stop TrailStopPips behind price, and advances in TrailStepPips increments via TryModify_EX16032's 3-attempt REQUOTE / TIMEOUT retry. When EnableVirtualStops is true, OnTick also calls VirtualStopsDriver("listen"), which scans all OBJ_HLINE objects on the chart for names matching #<ticket> sl (red) or #<ticket> tp (blue), validates the ticket via IsOurMagicNumber, and closes via TryClose_EX16032 when price crosses the level — with VirtualStopTimeout optionally suppressing the SL close for N seconds of sustained breach. pipValue auto-handles 5-digit FX, 3-digit XAUUSD, and 2-digit metal quotes by reading SYMBOL_DIGITS in OnInit. TryClosePartial_EX16032 is defined but never wired into any call site, and the 12-layer header claim covers only the two operational layers actually present (MANAGE and EXIT).

Entry Signal

EX16032 does not open positions. Its entry scope is the magic-number filter: when a position is opened by another EA and the position's magic matches one of the longs in the comma-separated MagicNumbers input, EX16032 takes ownership of it and begins the trailing-stop loop. The default list is the single magic 22216032; the operator extends the list to cover any number of upstream EAs by listing their magics separated by commas.

Exit Signal

Two exit paths are wired. The trailing stop in TrailingStop() sends a broker-side modify via TryModify_EX16032 (3 attempts on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED with 100ms backoff) once profit exceeds TrailStartPips and the new stop is at least TrailStepPips tighter than the current stop. The virtual stops in VirtualStopsDriver("listen") close via TryClose_EX16032 when price crosses a chart-drawn #<ticket> sl (red) or #<ticket> tp (blue) horizontal line, with VirtualStopTimeout optionally delaying the SL close for N seconds of sustained breach before the actual position close fires.

Stop Loss

The stop is a pip-step trailing stop, not a fixed per-trade SL. The trailing activates once profit exceeds TrailStartPips (50 pips default), holds the stop at TrailStopPips (20 pips) behind the current price, and only advances when the new stop is at least TrailStepPips (10 pips) past the existing one. There is no fixed per-trade stop-loss input — every managed position is trailed, never capped at a static distance.

Take Profit

There is no broker-side take-profit in the source — the EA only modifies the SL on trailing positions. The take-profit is implemented as virtual TP via chart horizontal lines: the operator manually places a blue horizontal line named #<ticket> tp on the chart, and VirtualStopsDriver closes the position when price crosses the line. TP distance is therefore set by the operator per position, not by an input.

Best For

Suited to XAUUSD M5 as the management chart, with H1 as a higher-frame context reference; the 50 / 20 / 10 pip trail values are sized for XAUUSD M5 volatility and will trail too tight on slower FX pairs. Minimum recommended balance $100, with $500+ preferred so the 0.10 lot upstream positions have room to move the 50-pip activation distance without margin stress. Best on a low-spread ECN or RAW broker — the virtual TP and trailing stops are both price-level-driven, so a wide-spread retail broker will both delay the trail and trigger virtual SLs on spread spikes. Designed to run alongside one or more EX16xxx signal EAs (EX16020-EX16031) by listing their magics in the MagicNumbers input; the operator draws the #<ticket> tp lines manually on the chart for each open position.

Strategy Logic

Pipsgrowth EX16032 Trend — Strategy Logic Analysis (from .mq5 source)

Family: Trend Magic: 22216032 Version: 2.00

BRIEF: Universal trailing stop EA that manages positions by magic number, with pip-based trail start/stop/step and optional virtual stop-loss/take-profit via chart horizontal lines. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • ParseMagicNumbers()
  • IsOurMagicNumber()
  • TrailingStop()
  • VirtualStopsDriver()
  • ArraySearch()
  • StringTrim()
  • TryClose_EX16032()
  • TryClosePartial_EX16032()
  • TryModify_EX16032()

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (7 total across 2 groups):

  • [=== Trailing Stop Parameters ===] TrailStartPips = 50.0 // Trail Start (pips)
  • [=== Trailing Stop Parameters ===] TrailStopPips = 20.0 // Trail Stop (pips)
  • [=== Trailing Stop Parameters ===] TrailStepPips = 10.0 // Trail Step (pips)
  • [=== Trailing Stop Parameters ===] EnableVirtualStops = true // Enable Virtual Stops
  • [=== Trailing Stop Parameters ===] VirtualStopTimeout = 0 // Virtual Stop Timeout (seconds)
  • [=== Identity ===] MagicNumbers = "22216032" // Magic Numbers to track (comma separated)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_16032" // Trade Comment
Pseudocode
// Pipsgrowth EX16032 Trend — Execution Flow (from source analysis)
// Family: Trend
// Universal trailing stop EA that manages positions by magic number, with pip-based trail start/stop/step and optional virtual stop-loss/take-profit via chart horizontal lines. 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:
XAUUSD
Optimized Timeframes:
M5H1

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
TrailStartPips50.0Trail Start (pips)
TrailStopPips20.0Trail Stop (pips)
TrailStepPips10.0Trail Step (pips)
EnableVirtualStopstrueEnable Virtual Stops
VirtualStopTimeout0Virtual Stop Timeout (seconds)
MagicNumbers"22216032"Magic Numbers to track (comma separated)
InpTradeComment"Psgrowth.com Expert_16032"Trade Comment
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16032.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16032 DSUPERNATURAL1_UNIVERSAL_TRAILING_STOP_EA — universal trailing stop manager, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>

//--- Input parameters
input group "=== Trailing Stop Parameters ==="
input double   TrailStartPips     = 50.0;            // Trail Start (pips)
input double   TrailStopPips      = 20.0;            // Trail Stop (pips)
input double   TrailStepPips      = 10.0;            // Trail Step (pips)
input bool     EnableVirtualStops = true;           // Enable Virtual Stops
input int      VirtualStopTimeout = 0;               // Virtual Stop Timeout (seconds)
input group "=== Identity ==="
input string   MagicNumbers       = "22216032"; // Magic Numbers to track (comma separated)
input string   InpTradeComment    = "Psgrowth.com Expert_16032"; // Trade Comment

//--- Global variables
double pipValue;
long   magicNumbersArray[]; // Use long for magic numbers
CTrade trade;
CPositionInfo positionInfo;
COrderInfo orderInfo;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Calculate pip value based on symbol digits
   pipValue = (SymbolInfoInteger(_Symbol, SYMBOL_DIGITS) % 2 == 1) ? _Point * 10 : _Point;
   
   // Parse magic numbers
   ParseMagicNumbers(MagicNumbers);
   
   // Validate magic numbers
   if(ArraySize(magicNumbersArray) == 0)
   {
      Print("Error: No valid magic numbers provided");
      return(INIT_PARAMETERS_INCORRECT);
   }
   
   Print("Universal Trailing Stop EA started for Magic Numbers: ", MagicNumbers);
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   Print("Universal Trailing Stop EA deinitialized. Reason: ", reason);
}

//+------------------------------------------------------------------+
//| Parse comma-separated magic numbers into array                   |
//+------------------------------------------------------------------+

Full source code available on download

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

Tags:ex16032trendpipsgrowthfreemt5xauusd

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_EX16032.mq5
File Size16.2 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100