P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18087 TrendFollow

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

Pipsgrowth.com EX18087 ExpertMAPSAR — MA signal with PSAR trailing, full 12-layer stack.

Overview

Pipsgrowth EX18087 is a thin, deliberately minimal trend-following expert for MT5 that leans entirely on MetaQuotes' standard CExpert library. The .mq5 file at the source-of-truth level reveals its real architecture: it instantiates one signal module (CSignalMA), one trailing module (CTrailingPSAR), and one money module (CMoneyNone), then delegates every tick to the base CExpert engine through ExtExpert.OnTick(). Despite the header's reference to a "12-layer stack," the actual implementation is small, readable, and built on well-known library primitives — the kind of EA a developer can audit in a single sitting.

The entry layer is a moving-average signal. The user-configurable inputs drive signal.PeriodMA(12), signal.Shift(6), signal.Method(MODE_SMA), and signal.Applied(g_Inp_Signal_MA_Applied), where the applied price defaults to PRICE_CLOSE through the int-to-ENUM_APPLIED_PRICE mapping (value 1 = close, 2 = open, 3 = high, 4 = low, 5 = median, 6 = typical, 7 = weighted). What the CExpert framework does on top of these settings is the classic MA cross: it compares the MA value at the configured shift against price, and when the relationship flips it issues a long or short signal. The 6-bar shift is unusually large — most M5 setups use shift 0 or 1 — which gives the entry layer a deliberately delayed, anti-whipsaw posture. With shift=6 on an M5 bar, the EA evaluates MA-vs-price using a candle that closed half an hour ago, so it will routinely miss the first impulsive leg of a move and only engage once the new direction is already several bars old. That conservatism is the defining character of EX18087's entry engine: a slow SMA(12) with a 6-bar shift, not a fast EMA cross.

The exit layer is where EX18087 differs from most of the corpus. There is no fixed take-profit, no fixed stop-loss, no breakeven ratchet, no time-stop, and no per-trade TP/SL bracket at all. Instead the EA relies entirely on the Parabolic SAR trailing stop defined by CTrailingPSAR, configured with step = 0.02 and maximum = 0.2. PSAR in trailing mode works as a moving stop-loss: the SAR dot is recomputed every tick, the dot sits below price in an uptrend (or above price in a downtrend), and the EA continuously tightens the position's stop to that dot. When price finally violates the SAR (the dot flips to the other side of price), the trailing module closes the position. The 0.02 / 0.2 step/maximum pair is the standard MetaTrader PSAR default — sensitive enough to lock meaningful profit on gold's 30–60 point M5 swings, loose enough to give a real trend room to breathe. The result is a pure trend-runner: enter on a slow MA cross, ride as long as PSAR stays on the correct side, exit when PSAR flips.

The money layer is CMoneyNone, which means there is no built-in risk percent, no fixed-lot override, no lot cap, and no balance-based scaling. Trades open at the broker's default lot, which on most MT5 ECN setups is 0.01 for micro accounts and 0.10 or 1.00 for standard accounts. The risk profile is therefore entirely a function of position size, and EX18087 itself does not protect the account beyond what the trailing stop provides. A trader wiring this up to a $100 account on XAUUSD at 0.01 lot is exposed to roughly $1 per point of gold — at 30 points of adverse excursion (well within a normal M5 PSAR cycle on gold), that is $30 of risk per trade, and on a quiet day the account can absorb that easily. A trader on the same $100 account running 1.00 lot is exposed to $100 per point, which a single PSAR flip will blow through. The risk input is therefore not a setting inside the EA — it is the choice of trade volume on the broker side. Anyone testing EX18087 should treat lot size as the most important risk dial they have, because the EA does not regulate it.

The code includes three retry wrappers — TryClose_EX18087, TryClosePartial_EX18087, and TryModify_EX18087 — that loop up to three times on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED with 200ms backoff on close attempts and 100ms backoff on modify attempts. These are defined at the bottom of the file and are exposed for any caller that wants to override the CExpert base class behaviour, but the base CExpert engine does not call them by default. In practice they are scaffolding rather than active code paths; the EA's actual close and modify traffic flows through CExpert's own PositionClose and PositionModify machinery. This is the cleanest possible structure for an EA that wants to be auditable: every behaviour the user sees at runtime is implemented in two library classes, and the wrapper functions are present but dormant unless someone wires them up.

In OnInit the code follows the canonical CExpert setup sequence: initialize the ExtExpert, create a CSignalMA, call signal.PeriodMA / Shift / Method / Applied, validate signal settings, create a CTrailingPSAR, call trailing.Step / Maximum, validate trailing settings, create a CMoneyNone, validate money settings, then call ExtExpert.InitIndicators(). On any initialization failure the EA returns a negative code (-1 through -11 depending on the layer) and prints a labeled error string. The four event handlers — OnTick, OnTrade, OnTimer, OnDeinit — are all one-liners that forward to ExtExpert. There is no custom OnTimer code, no news filter, no time-window filter, no regime classifier, no spread gate, no pyramid logic, no dashboard, no OnTester optimization function. What runs at runtime is exactly what the input panel advertises: an MA(12, SMA, close, shift 6) signal with PSAR(0.02, 0.2) trailing, no SL, no TP, no money management, no time filter.

The operating picture is therefore straightforward. EX18087 will hold positions through M5 noise as long as PSAR stays put; it will exit on a PSAR flip with whatever profit or loss the trailing allowed; and it will re-enter on the next MA cross without any session restriction. The XAUUSD M5 default in the database matches the M5 bias of the 6-bar shift, but the header explicitly notes the EA is portable to FX majors and other metals. On EURUSD M5 the same logic plays out at a smaller per-point scale, the PSAR dot is tighter in absolute pips, and the 6-bar shift is more meaningful because EURUSD M5 ranges are narrower than gold's. On H1 the shift becomes 6 hours of delay, which is a serious commitment to late entries. The most useful parameter to tweak in a live forward-test is the MA period — dropping it from 12 to 8 or 10 speeds up entries and produces more signals at the cost of more PSAR-flip noise; raising it to 20 or 30 produces sparser but more durable trends. Everything else in the input panel is a library default and changing it (e.g. PSAR step/maximum, applied price) is meaningful only if the trader has a clear reason to deviate from the MetaTrader standard.

The bottom line: EX18087 is a deliberately compact, library-based trend runner for traders who want a clean, auditable CExpert implementation rather than a custom-coded monolith. Its edge comes from the MA-signal/PSAR-trailing pair working together — the slow MA with its 6-bar shift suppresses whipsaws, and the PSAR trailing captures trends while clipping drawdowns. It does not manage risk, does not filter sessions, does not scale positions, and does not protect against broker-side events beyond the CExpert base class's defaults. It is best deployed on instruments with strong intraday trends (gold M5, FX majors M5), on accounts where the user has chosen a lot size that matches their own risk tolerance, and within a broker environment where the CExpert base class can operate without micro-lot rounding artefacts.

Strategy Deep Dive

The OnInit sequence instantiates three MetaTrader library objects — CSignalMA, CTrailingPSAR, and CMoneyNone — wires them into a CExpert base class, validates each layer's settings, and returns INIT_SUCCEEDED or a negative code identifying which layer failed. On every tick, OnTick forwards to ExtExpert.OnTick(), which lets the library evaluate the MA(12, SMA, close, shift 6) signal at the close of the prior 6th bar and, when the MA-vs-price relationship flips, opens a position whose stop is initially seeded by the SAR dot. The PSAR trailing module then runs every tick, recomputing the dot and tightening the position's stop to it; when price finally violates the dot the trailing module closes the trade. There is no custom timer code, no news filter, no time-window filter, no spread gate, no pyramid logic, and no dashboard — every observable behavior at runtime is implemented in those two library classes plus the no-op money module. The three retry wrappers at the bottom of the file (TryClose_EX18087, TryClosePartial_EX18087, TryModify_EX18087) loop up to three times on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED with 200ms or 100ms backoff and are exposed for any caller that wants to override the CExpert base class, but the CExpert framework does not invoke them by default.

Entry Signal

Entry is generated by the standard MetaTrader CSignalMA module configured at PeriodMA=12, Shift=6, Method=MODE_SMA, and Applied=PRICE_CLOSE. The CExpert base class compares the SMA(12) value at the 6-bar shift against current price and issues a long or short signal when the MA-vs-price relationship flips, which produces deliberately late, anti-whipsaw entries half an hour after a new M5 trend has started. With shift=6 on M5 the signal evaluates using a candle that closed 30 minutes ago, so the EA misses the impulsive first leg of any move and only engages once the direction is already established.

Exit Signal

Exit is handled entirely by the CTrailingPSAR trailing module with Step=0.02 and Maximum=0.2. Every tick, the SAR dot is recomputed and the position's stop is tightened to that dot; when price finally violates the SAR (the dot flips to the other side of price), the trailing module closes the position. There is no fixed TP, no fixed SL bracket, no breakeven ratchet, no time-stop, and no opposite-signal exit — the PSAR flip is the only exit path.

Stop Loss

There is no per-trade stop-loss bracket on entry — SL is dynamic and managed exclusively by the CTrailingPSAR trailing stop, which tightens the position's stop to the SAR dot on every tick. The risk per trade is therefore determined by the distance from entry to the SAR at the moment of entry, and an adverse PSAR flip can produce a loss equal to roughly that initial SAR distance.

Take Profit

There is no fixed take-profit — TP is implicit and emerges when the PSAR trailing stop is ratcheted up (for longs) or down (for shorts) by a sufficient M5 swing. The realized profit on any closed trade equals the high-water-mark of price minus the SAR-tightened stop at the moment of the PSAR flip, which on XAUUSD M5 typically captures 30–60 point swings.

Best For

Best deployed on a $100+ XAUUSD M5 or H1 chart on a low-spread ECN broker, with the user explicitly choosing a fixed lot that matches their own risk tolerance (the EA does not manage lot size via CMoneyNone). Ideal for traders who want a clean, auditable CExpert library implementation with a slow SMA(12) / shift=6 entry filter and PSAR trailing, and who are comfortable sizing the risk themselves rather than handing it to a money-management module. Less suitable for accounts that need automated risk percent or session filtering, since the EA has no built-in time filter and no balance-based lot scaling.

Strategy Logic

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

Family: TrendFollow Magic: 22218087 Version: 2.00

BRIEF: MA signal with Parabolic SAR trailing using the standard CExpert library. Trend-follow entries on MA, PSAR manages exit. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • OnTrade()
  • OnTimer()
  • TryClose_EX18087()
  • TryClosePartial_EX18087()
  • TryModify_EX18087()

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (3 total across 3 groups):

  • [=== Identity ===] Expert_MagicNumber = 22218087 // Magic number
  • [=== Signal (MA) ===] Inp_Signal_MA_Applied = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
  • [=== Trailing (Parabolic SAR) ===] Inp_Trailing_ParabolicSAR_Maximum = 0.2 // +------------------------------------------------------------------+
Pseudocode
// Pipsgrowth EX18087 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// MA signal with Parabolic SAR trailing using the standard CExpert library. Trend-follow entries on MA, PSAR manages exit. 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
Expert_MagicNumber22218087Magic number
Inp_Signal_MA_Applied1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
Inp_Trailing_ParabolicSAR_Maximum0.2+------------------------------------------------------------------+
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18087.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18087 ExpertMAPSAR — MA signal with PSAR trailing, full 12-layer stack."
//+------------------------------------------------------------------+
//| Include                                                          |
//+------------------------------------------------------------------+
#include <Expert\Expert.mqh>
#include <Expert\Signal\SignalMA.mqh>
#include <Expert\Trailing\TrailingParabolicSAR.mqh>
#include <Expert\Money\MoneyNone.mqh>
//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
//--- inputs for expert
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_APPLIED_PRICE g_Inp_Signal_MA_Applied = PRICE_CLOSE;
input group "=== Identity ==="
input string             Inp_Expert_Title                 ="Pipsgrowth.com Expert_18087";
input string             InpTradeComment                  ="Psgrowth.com Expert_18087";
input long               Expert_MagicNumber               =22218087; // Magic number
bool                     Expert_EveryTick                 =false;
//--- inputs for signal
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_APPLIED_PRICE g_Inp_Signal_MA_Applied = PRICE_CLOSE;
input group "=== Signal (MA) ==="
input int                Inp_Signal_MA_Period             =12;
input int                Inp_Signal_MA_Shift              =6;
input ENUM_MA_METHOD     Inp_Signal_MA_Method             =MODE_SMA;
input int Inp_Signal_MA_Applied = 1; // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
//--- inputs for trailing
ENUM_APPLIED_PRICE MapAppliedPriceInt(int ap)
{

Full source code available on download

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

Tags:ex18087trendfollowpipsgrowthfreemt5xauusd

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