P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18036 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18036 HAS — Heikin-Ashi Smoothed trend-follow EA, self-contained, broker-portable.

Overview

Pipsgrowth EX18036 TrendFollow turns a smoothed-candle pattern into a structured trend trade on XAUUSD at the M5 cadence. The signal core is the Heikin-Ashi Smoothed construction, not a plain Heikin-Ashi overlay. The EA first runs four independent SMMA(InpMaPeriod=6) passes on OHLC separately, then feeds the smoothed open, high, low, and close into the standard Heikin-Ashi recursion: haClose = (o+h+l+c)/4, haOpen = (prevHaOpen + prevHaClose)/2. Because the inputs are pre-smoothed, every HAS bar filters out a layer of one-tick noise and leaves a slower, structurally meaningful candle sequence behind. The signal in HasSignal() is a pure color-flip: a bar that prints green (haClose > haOpen) after a red bar returns +1 with confidence 65; the mirror red-after-green returns -1 with the same confidence. When there is no flip but the closed bar shows a strong body — body/range above 0.7 — the EA treats the move as a continuation, returns +1/-1 with confidence 55, and still proceeds. Anything else returns 0 and the EA sits out that bar.

A trade never opens on signal alone. TryEntry() re-checks the no-trade gate (NoTrade()) and then asks HtfTrendAgrees() whether price is on the right side of the H1 EMA(50). A long signal needs bid above the H1 EMA(50); a short signal needs bid below. This higher-timeframe agreement is what filters HAS flips that occur against the dominant multi-hour trend. Only after both pass does the EA build the order. The SL distance is InpAtrSlMult × ATR(14) (default 2.0), and the TP is InpRR × slDist (default 1.5), which gives the 1:1.5 reward-to-risk geometry the strategy is built around. Sizing flows through CalcLot() against effective capital, then is rounded down to the symbol's volume step and clamped to the broker min/max.

Risk management is layered. The capital cap, with InpCapAmount=0 in the default profile, returns full account equity as effective capital; the InpCapFloor=$50 stops new entries when equity drops below that line. RealizedPnLSince() scans the deal history for the past 24 hours and past 7 days to enforce InpDailyLossPct=3% and InpWeeklyLossPct=6%. A loss counter g_consecLosses increments in OnTradeTransaction() whenever a closing deal for this magic comes back negative; at three in a row NoTrade() returns 'cooldown after losses' and the EA flat-lines entries until the next non-loss resets the count. The max-concurrent gate is InpMaxConcurrent=3 and PyramidAllowed() is compiled but disabled by default (InpPyramidEnabled=false), so on a clean chart this EA is strictly a one-position-per-direction, max-three bot. The session gate runs from InpSessionStart=7 to InpSessionEnd=20 in broker time, with the weekend block, a 60-point spread cap on the XAUUSD quote, and the global kill switch as the final three no-trade filters.

The regime layer is the most demanding part of the code. RegimeClassify() pulls ADX(14), ATR(14), and BB(20,2) buffers, then runs a 50-bar ATR percentile back-window to score how stretched current volatility is. Bollinger width is compared bar-to-bar (current vs prior) to detect expansion or compression. The state machine has seven outcomes: STRONG_TREND when ADX is at or above 25 and ATR-percentile is at or above 60; WEAK_TREND when ADX is at or above 20; COMPRESS when Bollinger width is contracting against the prior bar and ATR-percentile is below 30; EXPAND when width is expanding and ATR-percentile is at or above 60; BREAKOUT when width is expanding without the high-vol tag; CHOPPY when ADX drops below 15; and RANGE as the fallback. Only CHOPPY is hard-blocked by the entry gate — the other states trade, but the comment line in the header calls out that regime transitions are intended to be observed rather than always hard-blocked. The seven-state classifier gives the EA room to act across both high-conviction trends and quiet ranges without forcing a single state, which is the point of the per-state design.

Position management runs on every tick. ManageExits() walks the open positions in reverse and applies four layers in order. First, an opposite-signal close — when the latest closed-bar HAS flips the other way, the EA calls TryClose_EX18036() with a three-attempt retry loop (200ms backoff on requote, timeout, price-off, or price-changed). Second, a break-even: once profit distance exceeds 1R, the stop ratchets to open+2pt via TryModify_EX18036() (3 attempts, 100ms backoff). Third, an ATR trail: as price moves in profit, the stop is re-anchored to current minus/plus InpTrailAtrMult × ATR(14) (default 2.5×), always forward-only, never back. Fourth, a hard TP close when price hits the take-profit level. There is no time-based exit in ManageExits — the trade is held until SL, TP, trail, BE-anchored stop, or an opposite HAS flip. The retry helper loops are narrow: TryClosePartial_EX18036() and TryModify_EX18036() both retry three times on the same price-side retcodes; the rest of the stack assumes the broker's first response is canonical.

On the practical side, the OnTester() function evaluates a backtest with the formula (netProfit × profitFactor) / (1 + relativeDrawdownPercent) and discards any run with fewer than 30 trades, which means a tester pass with five or ten well-shaped trades cannot game the score. Order comments hardcode 'Psgrowth.com Expert_18036', filling mode is auto-detected between FOK, IOC, and RETURN, and OrderCalcMargin runs before the send so the EA refuses to open a position it cannot afford. The recommended deployment is a low-spread ECN or RAW account on XAUUSD with the default input set; the 60-point spread gate makes a wide-spread dealing desk a non-starter. The 7-20 server-time session is broad enough to cover London through the New York morning, and the $50 capital floor plus the loss-count cooldown together put a hard ceiling on how many bad entries can stack in a single trading day.

Strategy Deep Dive

The indicator stack on init is nine handles: iADX(14), iATR(14), iBands(20,2), four iMA(6, SMMA) passes on OHLC, and one iMA(50, EMA) on the H1 timeframe. On every tick, OnTick refreshes rates, calls CalcHAS(100) to rebuild 100 bars of Heikin-Ashi Smoothed from the four smoothed OHLC primitives, and walks HasSignal() to score the latest closed bar as flip (conf 65), strong-continuation (conf 55), or no-signal (0). ManageExits runs first to apply opposite-signal close, break-even at +1R, and the 2.5×ATR forward trail. On a new bar, TryEntry re-checks the no-trade gate (killswitch, 60-point XAUUSD spread cap, 7-20 server session, weekend block, regime≠CHOPPY, capital floor, daily/weekly realized PnL, 3-loss cooldown, max 3 concurrent), confirms H1 EMA(50) agreement, computes the 2.0×ATR SL and 1.5R TP, sizes the lot from effective capital, runs OrderCalcMargin, and sends the order with one retry on requote/timeout. The regime layer RegimeClassify runs in the same no-trade path and uses a 50-bar ATR-percentile back-window plus bar-to-bar Bollinger width comparison to assign one of seven states; only CHOPPY hard-blocks. Order fills auto-detect between FOK, IOC, and RETURN; TryClose, TryClosePartial, and TryModify each retry three times on the same price-side retcodes with 200ms or 100ms backoff. OnTester scores (net × PF) / (1 + DD%) and discards runs with fewer than 30 trades.

Entry Signal

Entry is triggered by a Heikin-Ashi Smoothed (HAS) color flip on the last closed bar — green-after-red returns +1 and red-after-green returns -1, each with confidence 65. When the bar is not a flip but the body/range ratio exceeds 0.7, the EA treats it as a strong continuation and returns ±1 with confidence 55. TryEntry() then requires the bid to be on the correct side of the H1 EMA(50) before sending the order, and the trade only opens if the no-trade gate (spread, session, weekend, regime, daily/weekly loss, cooldown, concurrent) is clear.

Exit Signal

Exits are evaluated on every tick inside ManageExits(). An opposite HAS color flip calls TryClose_EX18036 with a 3-attempt retry loop on requote/timeout/price-off/price-changed. Profit-take runs at the static TP level set at entry (1.5R distance). The break-even ratchet fires once when price reaches +1R and moves the stop to open+2 points. The ATR(14)×2.5 trail forward-only re-anchors the stop as price moves in profit, never backward. There is no time-based exit — positions are held until SL, TP, trail, BE stop, or a HAS flip the other way.

Stop Loss

Per-trade stop loss is 2.0×ATR(14) from the entry price (InpAtrSlMult default), and is then sent through RespectStops() so the final SL is never closer than the broker's SYMBOL_TRADE_STOPS_LEVEL in points. The hard fail-safe beyond the per-trade SL is the InpCapFloor=$50 capital floor plus the 3% daily and 6% weekly realized-loss limits — once any of these trips, NoTrade() returns and no new entries are allowed until the next session or capital recovery.

Take Profit

Take profit is fixed at entry at 1.5× the SL distance (InpRR=1.5 default, so 3.0×ATR(14) total for a 2.0×ATR SL). The TP is sent through RespectStops() to clear the broker stops-level floor and is never moved after entry. There is no partial-TP layer in the ManageExits path — the position is either held to the full TP, stopped at the trailing/BE stop, or closed on an opposite HAS flip.

Best For

Best deployed on a low-spread ECN or RAW XAUUSD account (the 60-point spread gate is hard-coded). Minimum recommended balance: $100 (the InpCapFloor=$50 capital floor plus the 0.5% per-trade risk needs a meaningful buffer to keep sizing off the symbol minimum lot). The 7-20 broker-time session is broad enough to cover London through early New York, so a London-open or New-York-open trader will see the full signal window. The OnTester 30-trade floor means this EA needs at least 6-10 months of M5 history for a meaningful backtest. Risk profile is medium — 1:1.5 R:R with a 2.5×ATR trail gives the trade room to breathe, but the strict 3-loss cooldown and weekly 6% loss cap mean a bad week forces the EA flat. Pairs and timeframes: the M5 XAUUSD default is the only validated profile; ATR-based SL/TP and the H1 EMA(50) confirm will not transfer cleanly to FX majors without retuning InpMaPeriod and InpAtrSlMult.

Strategy Logic

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

Family: TrendFollow Magic: 22218036 Version: 2.00

BRIEF: Heikin-Ashi Smoothed (OHLC smoothed by SMMA, recursively averaged) color flip on last closed bar. Entry gated by ADX/ ATR-percentile/BB-width regime + HTF EMA agreement + session + spread/news/floor no-trade filters. Sizing off effective_ capital (capital allocation cap). Exits: ATR-based SL, partial TP, ATR trail, break-even, regime change, opposite-signal. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • EffectiveCapital()
  • RealizedPnLSince()
  • RollDayWeek()
  • RegimeClassify()
  • CalcHAS()
  • HasSignal()
  • HtfTrendAgrees()
  • NoTrade()
  • CalcLot()
  • RespectStops()
  • DetectFilling()
  • TryEntry()
  • ...and 6 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (21 total across 7 groups):

  • [=== Identity ===] InpMagic = 22218036 // Magic number (id)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18036" // Order comment (text)
  • [=== Identity ===] InpDeviation = 20 // Slippage allowed (points)
  • [=== Control ===] InpDryRun = true // Dry-run mode (bool, no live orders)
  • [=== Control ===] InpKillSwitch = false // Global kill switch (bool)
  • [=== Capital Allocation Cap ===] InpCapAmount = 0.0 // Cap amount (account equity $)
  • [=== Capital Allocation Cap ===] InpCapFloor = 50.0 // Floor below which no new entries ($)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective cap)
  • [=== Risk & Sizing ===] InpDailyLossPct = 3.0 // Daily loss limit (% of effective cap)
  • [=== Risk & Sizing ===] InpWeeklyLossPct = 6.0 // Weekly loss limit (% of effective cap)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 3 // Max concurrent positions (count)
  • [=== Risk & Sizing ===] InpCooldownLoss = 3 // Losses before cooldown (count)
  • [=== Signal (HAS) ===] InpMaPeriod = 6 // HAS smoothing period (bars)
  • [=== Signal (HAS) ===] InpMaMethod = MODE_SMMA // HAS smoothing MA method
  • [=== Exits ===] InpAtrSlMult = 2.0 // SL distance = mult * ATR (x)
  • [=== Exits ===] InpRR = 1.5 // Reward:Risk for TP (x)
  • [=== Exits ===] InpBreakEvenR = 1.0 // Move to BE at +R (x)
  • [=== Exits ===] InpTrailAtrMult = 2.5 // ATR trailing multiplier (x)
  • [=== Scaling & Session ===] InpPyramidEnabled = false // Pyramid on profit (bool)
  • [=== Scaling & Session ===] InpSessionStart = 7 // Session start hour (broker time)
  • [=== Scaling & Session ===] InpSessionEnd = 20 // Session end hour (broker time)
Pseudocode
// Pipsgrowth EX18036 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Heikin-Ashi Smoothed (OHLC smoothed by SMMA, recursively averaged) color flip on last closed bar. Entry gated by ADX/ ATR-percentile/BB-width regime + HTF EMA agreement + session + spread/news/floor no-trade filters. Sizing off effective_ capital (capital allocation cap). Exits: ATR-based SL, partial TP, ATR trail, break-even, regime change, opposite-signal. 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:
M5

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
InpMagic22218036Magic number (id)
InpTradeComment"Psgrowth.com Expert_18036"Order comment (text)
InpDeviation20Slippage allowed (points)
InpDryRuntrueDry-run mode (bool, no live orders)
InpKillSwitchfalseGlobal kill switch (bool)
InpCapAmount0.0Cap amount (account equity $)
InpCapFloor50.0Floor below which no new entries ($)
InpRiskPercent0.5Risk per trade (% of effective cap)
InpDailyLossPct3.0Daily loss limit (% of effective cap)
InpWeeklyLossPct6.0Weekly loss limit (% of effective cap)
InpMaxConcurrent3Max concurrent positions (count)
InpCooldownLoss3Losses before cooldown (count)
InpMaPeriod6HAS smoothing period (bars)
InpMaMethodMODE_SMMAHAS smoothing MA method
InpAtrSlMult2.0SL distance = mult * ATR (x)
InpRR1.5Reward:Risk for TP (x)
InpBreakEvenR1.0Move to BE at +R (x)
InpTrailAtrMult2.5ATR trailing multiplier (x)
InpPyramidEnabledfalsePyramid on profit (bool)
InpSessionStart7Session start hour (broker time)
InpSessionEnd20Session end hour (broker time)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18036.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18036 HAS — Heikin-Ashi Smoothed trend-follow EA, self-contained, broker-portable."

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>

//+------------------------------------------------------------------+
//| INPUTS (12-22 grouped)                                            |
//+------------------------------------------------------------------+
input group "=== Identity ==="
input int    InpMagic        = 22218036;      // Magic number (id)
input string InpTradeComment = "Psgrowth.com Expert_18036"; // Order comment (text)
input int    InpDeviation    = 20;            // Slippage allowed (points)

input group "=== Control ==="
input bool   InpDryRun       = true;          // Dry-run mode (bool, no live orders)
input bool   InpKillSwitch   = false;         // Global kill switch (bool)

input group "=== Capital Allocation Cap ==="
// InpCapEnabled removed — use InpCapAmount=0 to disable          // Capital cap enabled (bool)
input double InpCapAmount    = 0.0;         // Cap amount (account equity $)
input double InpCapFloor     = 50.0;          // Floor below which no new entries ($)

input group "=== Risk & Sizing ==="
input double InpRiskPercent  = 0.5;           // Risk per trade (% of effective cap)
input double InpDailyLossPct = 3.0;           // Daily loss limit (% of effective cap)
input double InpWeeklyLossPct= 6.0;           // Weekly loss limit (% of effective cap)
input int    InpMaxConcurrent= 3;             // Max concurrent positions (count)
input int    InpCooldownLoss = 3;             // Losses before cooldown (count)

input group "=== Signal (HAS) ==="
input int             InpMaPeriod = 6;        // HAS smoothing period (bars)
input ENUM_MA_METHOD  InpMaMethod = MODE_SMMA;// HAS smoothing MA method

input group "=== Exits ==="
input double InpAtrSlMult    = 2.0;           // SL distance = mult * ATR (x)
input double InpRR           = 1.5;           // Reward:Risk for TP (x)
input double InpBreakEvenR   = 1.0;           // Move to BE at +R (x)
input double InpTrailAtrMult = 2.5;           // ATR trailing multiplier (x)

input group "=== Scaling & Session ==="
input bool   InpPyramidEnabled = false;       // Pyramid on profit (bool)
input int    InpSessionStart   = 7;           // Session start hour (broker time)
input int    InpSessionEnd     = 20;          // Session end hour (broker time)

//+------------------------------------------------------------------+
//| GLOBALS                                                           |
//+------------------------------------------------------------------+
CTrade        trade;
CPositionInfo posInfo;
CSymbolInfo   symInfo;
CAccountInfo  accInfo;

// indicator handles
int h_adx    = INVALID_HANDLE;

Full source code available on download

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

Tags:ex18036trendfollowpipsgrowthfreemt5xauusd

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