P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18075 TrendFollow

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

Pipsgrowth.com EX18075 TrendFollow — EMA cross + SuperTrend, full 12-layer stack.

Overview

Pipsgrowth EX18075 TrendFollow waits for an EMA(9) / EMA(21) crossover on the most recent closed bar, then asks an inline SuperTrendATR(10) multiplied by 3.0 against the HL2 midpoint — to confirm the direction. If the fast line crossed up and SuperTrend reads +1, the EA looks for a long; cross down with SuperTrend at -1 sets up a short. That two-condition agreement is the heart of the engine: a single EMA cross without SuperTrend backing produces no signal at all.

Layer two is the regime classifier inside UpdateRegime(). It pulls ATR over a 100-bar lookback to compute a percentile rank, fetches ADX(14), and reads Bollinger band width from a 20-period, 2.0-deviation envelope. The eight possible states (CHOPPY, COMPRESS, RANGE, WEAK_TREND, STRONG_TREND, EXPAND, BREAKOUT) are then pruned by the gating rule that follows: CHOPPY (ADX<15), COMPRESS (band width below 0.0005), and RANGE all return false from UpdateRegime(), so no signal ever leaves that function when the market is mean-reverting or low-energy. The EA only trades STRONG_TREND, WEAK_TREND, EXPAND, and BREAKOUT — its way of saying it is not interested in flat or contracting conditions.

If a signal survives the regime filter, it still has to clear ConfirmPasses(), a 2-of-4 voting block. The four votes are: the close of the last closed bar must agree with the higher-timeframe EMA(50) direction (configurable through InpHTF and InpHTFEMA, default H1); the close must sit inside the Bollinger envelope (so the entry is not chasing a candle that has already blown through a band); the candle's own close-to-close direction must agree with the signal; and the current spread must be no more than 1.5× the rolling 10-bar average spread. Two of those four must be true, otherwise the trade is skipped. The source header mentions an RSI filter, but the implementation replaces it with the Bollinger-position check (the inline comment in ComputeSignal notes "use BB position as proxy"), so a position is rejected whenever the close is outside the bands.

The no-trade gate in NoTradePasses() is the safety net. It checks the kill switch, the cooldown timer that arms after InpCooldownLosses consecutive losses (default 3, locks for one hour), the daily 3% and weekly 6% loss caps in dollar terms, the 35-point spread cap, the 07:00–21:00 server-time session, the 30-minute news block around midnight (plus Friday 22:00 onwards and the full weekend), and the broker margin mode (only hedging or netting accounts are accepted). On top of that, EntryPasses() adds a per-bar duplicate guard so the EA cannot fire twice on the same closed bar, and a max-concurrent check of 3 positions.

Sizing uses fixed-fractional risk off the effective capital. With InpRiskPercent at 0.5, the EA risks half a percent of equity on each new position, converts the ATR(10)-based stop distance into ticks, divides the risk dollar amount by the per-tick dollar value, and rounds the result down to the broker's lot step. The capital cap (InpCapitalCapAmount, default 0 = off) provides an additional ceiling when the trader wants to risk only a slice of the account; the InpCapitalCapFloor of 50 dollars then blocks any new entries once equity drops below that level. Sizing respects the broker's minimum lot, and the OrderCalcMargin pre-check refuses the send if free margin is insufficient.

Exits are layered. ManageExits() runs on every tick. For each open position it computes the current R-multiple (price progress divided by the initial stop distance), then applies the partial-TP rule (50% off at 1R by default), the break-even move (SL to open price at 1R), and the ATR trail (2.0× ATR behind price, forward-only ratchet, also gated on R >= 1). A 200-bar time stop forces a close if the trade has been open through that many bars of the working timeframe (about 16.7 hours on M5). On top of those rules, the opposite-signal exit closes any position whose direction disagrees with the freshest signal, and the regime-change exit wipes the book when the market slides into CHOPPY or RANGE.

Position management has a built-in retry layer. TryClose_EX18075, TryClosePartial_EX18075, and TryModify_EX18075 each loop up to three times with a 200 ms sleep on requote, timeout, price-off, or price-changed responses. PositionOpen itself gets a single additional retry on the same transient codes. The order comment is hardcoded to Psgrowth.com Expert_18075, the magic is 22218075, and InpDryRun defaults to true so the EA can be paper-tested before any live capital is exposed. OnTester() returns (net * profit_factor) / (1 + relative_drawdown_percent) with a 30-trade floor — a single composite number that weights return against drawdown.

Pyramiding is wired but switched off by default. With InpPyramidEnabled set to true, the EA allows up to 3 additional entries (hard cap 5) spaced by InpPyramidStepATR × ATR(10); with it off, OpenEntry() refuses any entry while another position from this magic is still open. The result is a single-position-at-a-time default that is consistent with the EA's risk cap, and a configurable scaling mode for users who want to lean into trends.

This is a strategy for traders who trust trend filters and want every other decision automated. The risk and confirmation parameters are tight enough that the EA is unlikely to be the source of drawdown on its own — the failure modes (whipsaw in the WEAK_TREND regime, regime mis-classification, slippage on a thin pair, broker requotes during the news window) are upstream of the code and need to be tested in a backtester with realistic spread assumptions and a 30-trade minimum before the strategy is trusted with live capital.

Strategy Deep Dive

On every tick the EA refreshes the indicator stack (EMA(9), EMA(21), ATR(10), ADX(14), Bollinger(20, 2), and a higher-timeframe EMA(50) on the chosen HTF by default H1), classifies the market into one of eight regime states, and only allows signals to proceed from STRONG_TREND, WEAK_TREND, EXPAND, or BREAKOUT. A new signal must clear a 2-of-4 confirmation vote, a per-bar duplicate guard, the cooldown timer that arms after three consecutive losses, and the daily/weekly loss caps (3% and 6% of effective capital) before the fixed-fractional sizing engine converts the 1.5× ATR(10) stop into a position size. With an open position, the management loop moves the stop to break-even at 1R, takes 50% off at 1R, trails 2.0× ATR(10) behind price, and force-closes on a regime change to CHOPPY or RANGE, an opposite signal, or the 200-bar time stop. All open, modify, and close operations have a 200 ms three-attempt retry loop on requote, timeout, price-off, and price-changed responses, and OnTester() ranks strategy candidates by (net * profit_factor) / (1 + relative_drawdown_percent) with a 30-trade floor.

Entry Signal

A long fires when the EMA(9) crosses above EMA(21) on the last closed bar while the inline SuperTrend (ATR(10) × 3.0 on HL2) sits in +1 territory; a short is the mirror. The signal then has to clear the regime classifier (one of STRONG_TREND, WEAK_TREND, EXPAND, or BREAKOUT) and pass at least two of the four confirmation votes — higher-timeframe EMA(50) agreement, close-inside-Bollinger, candle-direction agreement, and spread within 1.5× the 10-bar average.

Exit Signal

ManageExits() runs on every tick and applies a 50% partial close at 1R, a break-even move of the stop to the open price at 1R, and a 2.0× ATR(10) forward-only trailing stop. Open positions are also force-closed when a fresh opposite signal arrives, when the regime flips to CHOPPY or RANGE, or when the trade has been open for 200 bars of the working timeframe (about 16.7 hours on M5).

Stop Loss

The initial stop is placed 1.5× ATR(10) away from the entry price (rounded up to 1.2× the broker's stops level if the ATR-based distance is too tight), and the EA then ratchets that stop to break-even once the trade reaches 1R and trails it 2.0× ATR(10) behind price on every tick thereafter.

Take Profit

The take-profit is set 1.5× the SL distance from entry (InpRRmin = 1.5), so the default reward-to-risk is 1:1.5 with a 50% partial close at 1R. If the trade never reaches TP, the trailing stop is the de facto exit and locks in profit as the trend extends.

Best For

Minimum recommended balance is 100 dollars — the EA's 50-dollar capital floor cuts in well below that, so the working balance should sit comfortably above the floor. Best run on XAUUSD M5 with a low-spread broker: the 35-point hard cap means anything consistently above 3.0 pips will be rejected, and the 1.5× ATR(10) stop needs a 2–3 pip average to make the 1:1.5 R:R viable. The 07:00–21:00 server-time session covers London and New York hours on most GMT+2 brokers, with a 30-minute news block around midnight and automatic Friday-evening and weekend shutdowns.

Strategy Logic

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

Family: TrendFollow Magic: 22218075 Version: 2.00

BRIEF: EMA(fast/slow) crossover on the last CLOSED bar is the core signal. A SuperTrend computed inline from ATR + HL2 must agree on side. Entries pass a 12-layer pipeline: REGIME (ADX + ATR-percentile + Bollinger width), CONFIRM (HTF EMA + RSI + spread + candle-close + min R/R), NO-TRADE gates, CAPITAL ALLOCATION CAP, fixed-fractional sizing, ATR-SL, multi-target partials, ATR trailing, break-even, regime-change exit, opposite-signal exit, time exit. Pyramid default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • UpdateRegime()
  • ComputeSignal()
  • EntryPasses()
  • ConfirmPasses()
  • NoTradePasses()
  • OpenEntry()
  • ManageExits()
  • NormalizeInitialSL()
  • RespectsStops()
  • ModifySL()
  • ClosePosition()
  • CountPositions()
  • ...and 11 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (36 total across 8 groups):

  • [=== Identity ===] InpDryRun = true // Dry-run (no real sends)
  • [=== Identity ===] InpKillSwitch = false // Kill switch (immediate stop)
  • [=== Identity ===] InpMagic = 22218075 // Magic number (unique per EA)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18075" // Order comment
  • [=== Identity ===] InpSlippagePts = 20 // Max slippage in points
  • [=== Strategy ===] InpFastEMA = 9 // Fast EMA period (bars)
  • [=== Strategy ===] InpSlowEMA = 21 // Slow EMA period (bars)
  • [=== Strategy ===] InpSTMultiplier = 3.0 // SuperTrend ATR multiplier
  • [=== Strategy ===] InpSTPeriod = 10 // SuperTrend/ATR period (bars)
  • [=== Strategy ===] InpHTFEMA = 50 // HTF EMA period (bars)
  • [=== Strategy ===] InpHTF = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF timeframe for trend agreement
  • [=== Regime ===] InpADXPeriod = 14 // ADX period (bars)
  • [=== Regime ===] InpADXMinTrend = 20.0 // ADX min for trend regime
  • [=== Regime ===] InpATRPctLookback = 100 // ATR percentile lookback (bars)
  • [=== Regime ===] InpBBWidthMin = 0.0005 // BB width min (ratio to mid) for non-squeeze
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective capital)
  • [=== Risk & Sizing ===] InpATRSLmult = 1.5 // ATR multiple for hard SL
  • [=== Risk & Sizing ===] InpRRmin = 1.5 // Minimum reward:risk for entry
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPct = 6.0 // Weekly loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 3 // Max concurrent positions (this magic/symbol)
  • [=== Risk & Sizing ===] InpCooldownLosses = 3 // Loss streak cooldown (count)
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Capital cap amount ($ equity, not notional)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor below which new entries block ($)
  • [=== Manage / Exit ===] InpBEtriggerR = 1.0 // Break-even trigger (R multiples)
  • [=== Manage / Exit ===] InpTrailATRmult = 2.0 // ATR trailing multiple
  • [=== Manage / Exit ===] InpPartialR = 1.0 // Partial-TP trigger (R multiples, 0=off)
  • [=== Manage / Exit ===] InpPartialPct = 50.0 // Partial close size (% of position)
  • [=== Manage / Exit ===] InpMaxBarsInTrade = 200 // Max bars in trade (0=off)
  • [=== Pyramid ===] InpPyramidEnabled = false // Enable pyramiding (default OFF)
  • [=== Pyramid ===] InpPyramidMaxLevels = 3 // Max pyramid levels (hard-cap 5)
  • [=== Pyramid ===] InpPyramidStepATR = 1.0 // Pyramid spacing in ATR multiples
  • [=== Execution / Session ===] InpMaxSpreadPts = 35.0 // Max spread (points)
  • [=== Execution / Session ===] InpSession = "07:00-21:00" // Trading session HH:MM-HH:MM (server time)
  • [=== Execution / Session ===] InpBlockNewsWindow = true // Block trades near midnight (proxy news)
  • [=== Execution / Session ===] InpNewsBlockMin = 30 // News-window size (minutes each side of midnight)
Pseudocode
// Pipsgrowth EX18075 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// EMA(fast/slow) crossover on the last CLOSED bar is the core signal. A SuperTrend computed inline from ATR + HL2 must agree on side. Entries pass a 12-layer pipeline: REGIME (ADX + ATR-percentile + Bollinger width), CONFIRM (HTF EMA + RSI + spread + candle-close + min R/R), NO-TRADE gates, CAPITAL ALLOCATION CAP, fixed-fractional sizing, ATR-SL, multi-target partials, ATR trailing, break-even, regime-change exit, opposite-signal exit, time exit. Pyramid default OFF. 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
InpDryRuntrueDry-run (no real sends)
InpKillSwitchfalseKill switch (immediate stop)
InpMagic22218075Magic number (unique per EA)
InpTradeComment"Psgrowth.com Expert_18075"Order comment
InpSlippagePts20Max slippage in points
InpFastEMA9Fast EMA period (bars)
InpSlowEMA21Slow EMA period (bars)
InpSTMultiplier3.0SuperTrend ATR multiplier
InpSTPeriod10SuperTrend/ATR period (bars)
InpHTFEMA50HTF EMA period (bars)
InpHTF8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF timeframe for trend agreement
InpADXPeriod14ADX period (bars)
InpADXMinTrend20.0ADX min for trend regime
InpATRPctLookback100ATR percentile lookback (bars)
InpBBWidthMin0.0005BB width min (ratio to mid) for non-squeeze
InpRiskPercent0.5Risk per trade (% of effective capital)
InpATRSLmult1.5ATR multiple for hard SL
InpRRmin1.5Minimum reward:risk for entry
InpDailyLossLimitPct3.0Daily loss limit (% of effective capital)
InpWeeklyLossLimitPct6.0Weekly loss limit (% of effective capital)
InpMaxConcurrent3Max concurrent positions (this magic/symbol)
InpCooldownLosses3Loss streak cooldown (count)
InpCapitalCapAmount0.0Capital cap amount ($ equity, not notional)
InpCapitalCapFloor50.0Floor below which new entries block ($)
InpBEtriggerR1.0Break-even trigger (R multiples)
InpTrailATRmult2.0ATR trailing multiple
InpPartialR1.0Partial-TP trigger (R multiples, 0=off)
InpPartialPct50.0Partial close size (% of position)
InpMaxBarsInTrade200Max bars in trade (0=off)
InpPyramidEnabledfalseEnable pyramiding (default OFF)
InpPyramidMaxLevels3Max pyramid levels (hard-cap 5)
InpPyramidStepATR1.0Pyramid spacing in ATR multiples
InpMaxSpreadPts35.0Max spread (points)
InpSession"07:00-21:00"Trading session HH:MM-HH:MM (server time)
InpBlockNewsWindowtrueBlock trades near midnight (proxy news)
InpNewsBlockMin30News-window size (minutes each side of midnight)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18075.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18075 TrendFollow — EMA cross + SuperTrend, full 12-layer stack."

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

//================== INPUTS =======================================
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M5;
      case 3: return PERIOD_M15;
      case 4: return PERIOD_M30;
      case 5: return PERIOD_H1;
      case 6: return PERIOD_H4;
      case 7: return PERIOD_D1;
      default: return PERIOD_H1;
   }
}

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_TIMEFRAMES g_InpHTF = PERIOD_H1;
input group "=== Identity ==="
input bool   InpDryRun            = true;        // Dry-run (no real sends)
input bool   InpKillSwitch        = false;       // Kill switch (immediate stop)
input int    InpMagic             = 22218075;    // Magic number (unique per EA)
input string InpTradeComment       = "Psgrowth.com Expert_18075";  // Order comment
input int    InpSlippagePts       = 20;          // Max slippage in points

ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M5;
      case 3: return PERIOD_M15;
      case 4: return PERIOD_M30;
      case 5: return PERIOD_H1;

Full source code available on download

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

Tags:ex18075trendfollowpipsgrowthfreemt5xauusd

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