P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18084 TrendFollow

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

Pipsgrowth.com EX18084 XAUUSD_M5_HA_SuperTrend_EA — Heiken Ashi + EMA + SuperTrend + Volume confluence, full 12-layer stack.

Overview

Heiken Ashi candles are a smoothed representation of price that strips the small-body noise of regular OHLC bars. Pipsgrowth EX18084 leans on that smoothed view to find directional opportunities on XAUUSD M5, then asks two other indicators to confirm the move before any order is sent. The result is a small, transparent trend-following EA — roughly 650 lines of MQL5 — that runs without any external indicator file.

The signal engine has three checks that must all pass on the same closed bar. First, the EA looks for a "strong" Heiken Ashi candle: a bullish bar whose open sits on the low of the bar (no lower wick) and closes above the open, or the mirror bearish bar (no upper wick, close below open). That wick-tightness test is what filters out the indecisive HA candles that often mark local tops and bottoms. The HA arrays are built inline from MqlRates — no iCustom handle is created for Heiken Ashi — and the wick check is performed in OnTick() itself with MathAbs(g_haOpen[1] - g_haLow[1]) < _Point for bullish bars.

Second, an in-process SuperTrend walks 200 bars of ATR(InpSupertrendPeriod = 10) and rebuilds the trend line at the current bar with multiplier InpSupertrendFactor = 3.0. The function tracks the upper and lower bands with the standard ratchet rule — a band cannot widen against the prevailing trend — and flips the trend direction when close crosses through the opposite band. The signal code only takes long trades when g_stTrend == 1 and short trades when g_stTrend == -1. ATR comes from a single iATR handle, so there is no second indicator file either.

Third, an EMA(50) on close provides a slow directional filter. Long signals require ask > ema, short signals require bid < ema. The EMA is read from a single iMA handle into a 3-bar buffer, and only bar 1 (the just-closed bar) is consumed.

Two extra gates sit on top of the three-pillar core. The volume filter, when enabled (InpUseVolumeFilter = true), sums tick volume over the last 20 bars, computes the average, and demands that the current bar's volume reach at least InpMinVolumeRatio = 1.2× that average. A weak-volume breakout is rejected before any order is built. The spread filter reads (ask - bid) / _Point and rejects ticks where spread exceeds InpMaxSpread = 200 points — wide enough to allow most gold brokers, tight enough to block news-time spikes on the M5 chart. The session filter, finally, restricts trading to two server-time windows: 08:00–12:00 and 14:00–18:00 (both windows can be toggled independently). These default server hours cover the London morning and the New York open, the two windows when XAUUSD typically has its cleanest directional moves.

The stop loss is anchored to the Heiken Ashi candle structure rather than to a fixed point distance. For a long trade, the EA reads the HA Low of the bar at shift InpSLCandleLookback (default 1, the just-closed bar) and subtracts InpSLBufferPoints = 50 points. The intent is that the SL sits just under the natural HA support of the signal candle. If the HA array is too short, the EA falls back to a fixed distance of InpStopLoss = 500 points, which on a 5-digit XAUUSD broker equals 50 pips. The take profit is the same fixed value for both branches: InpTakeProfit = 1500 points, a 1:3 risk-to-reward ratio against the fixed-point SL. Risk is sized by CalculateLotSize(): when InpRiskPercent is positive (default 1.0%), the lot is computed from balance * riskPercent / (slPoints * tickValue * point / tickSize), then floored to the broker's volume step, then capped at the symbol max volume and at InpMaxLotSize = 1.0. A free-margin check further clips the lot if the order would consume more than 80% of free margin. Set InpRiskPercent to 0 and the EA falls back to InpFixedLot = 0.01.

Three independent trade-protectors run on every tick, before the new-bar gate fires. The first, ManageTrailingStop, ratchets the stop tighter once price has moved InpTrailStart = 300 points in profit: the new SL is set to bid (or ask for shorts) minus InpTrailDistance = 200 points, and the modify is sent only if the new SL is on the correct side of the current SL and above the open price. The second, ManageBreakeven, moves the stop to open + InpBEProfit = 50 points once price has moved InpBEStart = 200 points in profit, eliminating the loss case. The third, ManageProfitLock, jumps the stop to open + InpLockBuffer = 100 points once price has moved InpLockTrigger = 400 points, locking in a small risk-free cushion and giving the trade room to run to TP. The TP itself is never modified by any of the three managers, so the 1:3 risk-to-reward target stays intact.

Pyramiding is off by default (InpEnablePyramid = false) but supported. When enabled, the IsPyramidSafe() check only allows an additional entry if all existing same-magic, same-symbol positions have an SL that is at least InpMinSLProfit = 150 points in profit. A second condition caps the total open count at InpMaxPyramidLevels = 3. The EA also blocks simultaneous buy-and-sell exposure: in OnTick() it tracks two flags (buyPositionOpen and sellPositionOpen) and refuses to send a new order in a direction that already has an open position, unless the pyramid check clears it.

All order operations go through a 3-attempt retry loop. The three TryClose_EX18084, TryClosePartial_EX18084, and TryModify_EX18084 helpers each retry on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, TRADE_RETCODE_PRICE_OFF, and TRADE_RETCODE_PRICE_CHANGED, sleeping 200 ms between attempts for closes and 100 ms for modifies, before giving up.

What this EA does not have is also worth noting. There is no higher-timeframe confirmation, no news filter, no OnTester() pass, and no chart-side info panel. The risk management is per-trade only — there is no global daily-drawdown kill switch inside the code. For traders who want a small, readable trend system that does exactly what its inputs say and nothing more, EX18084 fits that niche. For traders who want a multi-layer stack with a kill switch and a richer filter chain, the larger-family EAs in this catalog carry that load.

Strategy Deep Dive

On every incoming tick, three trade-protectors iterate the open positions for the EA's magic and tighten the stop under their own conditions: ManageTrailingStop after 300 points of profit with 200-point trail distance, ManageBreakeven to open+50 after 200 points, and ManageProfitLock to open+100 after 400 points. A new-bar gate then blocks all further work until a fresh M5 bar opens; session and spread filters (200-point cap) follow before any indicator math runs. With those clear, the EA rebuilds the Heiken Ashi arrays via CalculateHeikenAshi(10) and walks 200 bars of ATR(10) inside CalculateSuperTrend(0) to update g_stTrend and g_stValue. The signal core reads the closed HA bar (no lower wick + close>open for longs, no upper wick + close<open for shorts), checks SuperTrend direction, then checks the ask/bid position relative to the EMA(50) value, and finally runs the volume filter (current volume >= 1.2× the 20-bar average). When everything aligns and no open position in that direction exists (or the pyramid check clears), trade.Buy or trade.Sell is sent with the HA-anchored SL and the fixed 1500-point TP — CalculateLotSize sizes the order at 1% balance risk with a margin-aware floor and a 1.0-lot ceiling.

Entry Signal

On a new M5 bar, a long signal fires when the just-closed Heiken Ashi candle has no lower wick and closes above its open, the inline SuperTrend is bullish (g_stTrend == 1), and ask sits above the EMA(50) trend line. The short side mirrors that — a no-upper-wick bearish HA bar with SuperTrend at -1 and bid below EMA(50). A volume gate further requires the current bar's tick volume to reach at least 1.2× the 20-bar average before any order is sent, and a 200-point spread cap blocks the entry at the same step.

Exit Signal

Positions exit on the fixed 1500-point take profit (a 1:3 risk-to-reward target against the default 500-point SL) or on the HA-anchored stop loss. Three one-way ratchets protect profits: a trailing stop kicks in after 300 points of profit with a 200-point trail distance, breakeven moves SL to open+50 points after 200 points, and a profit lock jumps SL to open+100 points after 400 points. There is no opposite-signal exit — the EA simply blocks a duplicate entry in the same direction when a position is already open.

Stop Loss

Stop loss is anchored to the Heiken Ashi candle structure: for a long trade the SL sits at the HA Low of the lookback bar (default 1) minus a 50-point buffer, with a 500-point fixed-distance fallback if the HA array is unavailable. The three trade-protectors then move that stop in only one direction — breakeven at +200 points, profit lock at +400 points, and trailing ratchet at +300-point trigger — and never loosen it.

Take Profit

Take profit is a fixed 1500 points (a 1:3 risk-to-reward against the 500-point default SL), placed at the moment of entry and never modified by the trailing, breakeven, or profit-lock managers. This gives every trade an identical distance-to-target and identical R:R ratio regardless of where the HA-anchored stop actually lands.

Best For

Minimum recommended balance: $100. Best suited for XAUUSD on the M5 chart during the default 08:00–12:00 and 14:00–18:00 server-time windows (covering London morning and the New York open, when gold typically trends cleanly). A low-spread ECN broker is recommended because the EA applies a tight 200-point spread cap and uses inline indicator math, so a wide-spread retail account will see most of its signals blocked. Pyramid mode is off by default; traders who want to scale into trends can flip InpEnablePyramid = true, but should size risk conservatively because the HA-anchored stop can sit closer than the 500-point fixed fallback on trend bars.

Strategy Logic

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

Family: TrendFollow Magic: 22218084 Version: 2.00

BRIEF: Self-contained Heiken Ashi + EMA + SuperTrend + Volume confluence system for XAUUSD M5. Enters on strong HA candles confirmed by EMA trend and SuperTrend direction, with volume filter, session filter, spread filter, trailing, breakeven, profit lock and safe pyramiding. Full 12-layer stack. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • CalculateHeikenAshi()
  • CalculateSuperTrend()
  • CalculateLotSize()
  • IsWithinTradingSession()
  • IsSpreadOK()
  • IsNewBar()
  • CountOpenTrades()
  • IsPyramidSafe()
  • ManageTrailingStop()
  • ManageBreakeven()
  • ManageProfitLock()
  • TryClose_EX18084()
  • ...and 2 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (36 total across 11 groups):

  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18084" // Trade Comment
  • [=== Identity ===] InpMagicNumber = 22218084 // Magic Number
  • [=== Risk Management ===] InpRiskPercent = 1.0 // Risk % of Balance per Trade
  • [=== Risk Management ===] InpFixedLot = 0.01 // Fixed Lot (if Risk=0)
  • [=== Risk Management ===] InpMaxLotSize = 1.0 // Max Lot Size (Hard Limit)
  • [=== Time Management ===] InpEnableSession1 = true // Enable Session 1
  • [=== Time Management ===] InpSession1Start = 8 // Session 1 Start Hour
  • [=== Time Management ===] InpSession1End = 12 // Session 1 End Hour
  • [=== Time Management ===] InpEnableSession2 = true // Enable Session 2
  • [=== Time Management ===] InpSession2Start = 14 // Session 2 Start Hour
  • [=== Time Management ===] InpSession2End = 18 // Session 2 End Hour
  • [=== Indicator Settings ===] InpEMAPeriod = 50 // EMA Period for Trend Filter
  • [=== Indicator Settings ===] InpSupertrendPeriod = 10 // SuperTrend ATR Period
  • [=== Indicator Settings ===] InpSupertrendFactor = 3.0 // SuperTrend ATR Multiplier
  • [=== Heiken Ashi Settings ===] InpHASmoothing = 1 // HA Smoothing Period (1=standard)
  • [=== Volume Filter ===] InpUseVolumeFilter = true // Enable Volume Filter
  • [=== Volume Filter ===] InpVolumePeriod = 20 // Volume Average Period
  • [=== Volume Filter ===] InpMinVolumeRatio = 1.2 // Min Volume Ratio vs Average
  • [=== Stop Loss & Take Profit ===] InpStopLoss = 500 // Stop Loss (Points)
  • [=== Stop Loss & Take Profit ===] InpTakeProfit = 1500 // Take Profit (Points)
  • [=== Stop Loss & Take Profit ===] InpSLCandleLookback = 1 // SL Candle Lookback (HA-based SL)
  • [=== Stop Loss & Take Profit ===] InpSLBufferPoints = 50 // SL Buffer (Points) beyond candle
  • [=== Trailing & Breakeven ===] InpUseTrailing = true // Enable Trailing Stop
  • [=== Trailing & Breakeven ===] InpTrailStart = 300 // Trail Start (Points)
  • [=== Trailing & Breakeven ===] InpTrailDistance = 200 // Trail Distance (Points)
  • [=== Trailing & Breakeven ===] InpUseBreakeven = true // Enable Breakeven
  • [=== Trailing & Breakeven ===] InpBEStart = 200 // Breakeven Trigger (Points)
  • [=== Trailing & Breakeven ===] InpBEProfit = 50 // Breakeven Lock Profit (Points)
  • [=== Profit Lock ===] InpUseLockProfit = true // Enable Profit Locking
  • [=== Profit Lock ===] InpLockTrigger = 400 // Lock Trigger (Points)
  • [=== Profit Lock ===] InpLockBuffer = 100 // Lock Buffer (Points)
  • [=== Safe Pyramid Settings ===] InpEnablePyramid = false // Enable Pyramiding
  • [=== Safe Pyramid Settings ===] InpMaxPyramidLevels = 3 // Max Pyramid Positions
  • [=== Safe Pyramid Settings ===] InpMinSLProfit = 150 // Min SL in Profit (Points) for Pyramid
  • [=== Spread Filter ===] InpEnableSpreadFilter = true // Enable Spread Filter
  • [=== Spread Filter ===] InpMaxSpread = 200 // Max Spread (Points)
Pseudocode
// Pipsgrowth EX18084 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Self-contained Heiken Ashi + EMA + SuperTrend + Volume confluence system for XAUUSD M5. Enters on strong HA candles confirmed by EMA trend and SuperTrend direction, with volume filter, session filter, spread filter, trailing, breakeven, profit lock and safe pyramiding. Full 12-layer stack. 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
InpTradeComment"Psgrowth.com Expert_18084"Trade Comment
InpMagicNumber22218084Magic Number
InpRiskPercent1.0Risk % of Balance per Trade
InpFixedLot0.01Fixed Lot (if Risk=0)
InpMaxLotSize1.0Max Lot Size (Hard Limit)
InpEnableSession1trueEnable Session 1
InpSession1Start8Session 1 Start Hour
InpSession1End12Session 1 End Hour
InpEnableSession2trueEnable Session 2
InpSession2Start14Session 2 Start Hour
InpSession2End18Session 2 End Hour
InpEMAPeriod50EMA Period for Trend Filter
InpSupertrendPeriod10SuperTrend ATR Period
InpSupertrendFactor3.0SuperTrend ATR Multiplier
InpHASmoothing1HA Smoothing Period (1=standard)
InpUseVolumeFiltertrueEnable Volume Filter
InpVolumePeriod20Volume Average Period
InpMinVolumeRatio1.2Min Volume Ratio vs Average
InpStopLoss500Stop Loss (Points)
InpTakeProfit1500Take Profit (Points)
InpSLCandleLookback1SL Candle Lookback (HA-based SL)
InpSLBufferPoints50SL Buffer (Points) beyond candle
InpUseTrailingtrueEnable Trailing Stop
InpTrailStart300Trail Start (Points)
InpTrailDistance200Trail Distance (Points)
InpUseBreakeventrueEnable Breakeven
InpBEStart200Breakeven Trigger (Points)
InpBEProfit50Breakeven Lock Profit (Points)
InpUseLockProfittrueEnable Profit Locking
InpLockTrigger400Lock Trigger (Points)
InpLockBuffer100Lock Buffer (Points)
InpEnablePyramidfalseEnable Pyramiding
InpMaxPyramidLevels3Max Pyramid Positions
InpMinSLProfit150Min SL in Profit (Points) for Pyramid
InpEnableSpreadFiltertrueEnable Spread Filter
InpMaxSpread200Max Spread (Points)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18084.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18084 XAUUSD_M5_HA_SuperTrend_EA — Heiken Ashi + EMA + SuperTrend + Volume confluence, full 12-layer stack."
#include <Trade/Trade.mqh>
CTrade trade;

//--- Trade Comment
input group "=== Identity ==="
input string    InpTradeComment = "Psgrowth.com Expert_18084";    // Trade Comment
input int       InpMagicNumber = 22218084;        // Magic Number

//--- Risk Management
input group "=== Risk Management ==="
input double    InpRiskPercent = 1.0;           // Risk % of Balance per Trade
input double    InpFixedLot = 0.01;             // Fixed Lot (if Risk=0)
input double    InpMaxLotSize = 1.0;            // Max Lot Size (Hard Limit)

//--- Time Filter
input group "=== Time Management ==="
input bool      InpEnableSession1 = true;       // Enable Session 1
input int       InpSession1Start = 8;           // Session 1 Start Hour
input int       InpSession1End = 12;            // Session 1 End Hour
input bool      InpEnableSession2 = true;       // Enable Session 2
input int       InpSession2Start = 14;          // Session 2 Start Hour
input int       InpSession2End = 18;            // Session 2 End Hour

//--- Indicator Settings
input group "=== Indicator Settings ==="
input int       InpEMAPeriod = 50;              // EMA Period for Trend Filter
input int       InpSupertrendPeriod = 10;       // SuperTrend ATR Period
input double    InpSupertrendFactor = 3.0;      // SuperTrend ATR Multiplier

//--- Heiken Ashi Settings
input group "=== Heiken Ashi Settings ==="
input int       InpHASmoothing = 1;             // HA Smoothing Period (1=standard)

//--- Volume Filter
input group "=== Volume Filter ==="
input bool      InpUseVolumeFilter = true;      // Enable Volume Filter
input int       InpVolumePeriod = 20;           // Volume Average Period
input double    InpMinVolumeRatio = 1.2;        // Min Volume Ratio vs Average

//--- Stop Loss & Take Profit
input group "=== Stop Loss & Take Profit ==="
input int       InpStopLoss = 500;              // Stop Loss (Points)
input int       InpTakeProfit = 1500;           // Take Profit (Points)
input int       InpSLCandleLookback = 1;        // SL Candle Lookback (HA-based SL)
input int       InpSLBufferPoints = 50;         // SL Buffer (Points) beyond candle

//--- Trailing & Breakeven
input group "=== Trailing & Breakeven ==="
input bool      InpUseTrailing = true;          // Enable Trailing Stop
input int       InpTrailStart = 300;            // Trail Start (Points)
input int       InpTrailDistance = 200;         // Trail Distance (Points)
input bool      InpUseBreakeven = true;         // Enable Breakeven
input int       InpBEStart = 200;               // Breakeven Trigger (Points)
input int       InpBEProfit = 50;               // Breakeven Lock Profit (Points)

Full source code available on download

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

Tags:ex18084trendfollowpipsgrowthfreemt5xauusd

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