P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18103 TrendFollow

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

Pipsgrowth.com EX18103 RSI_EMA_Reversal — RSI reversal with EMA slope filter and trailing stop, full 12-layer stack.

Overview

EX18103 TrendFollow is a two-indicator reversal system designed for XAUUSD on the M1–H1 band. It pairs a 19-period RSI with a 140-period EMA and looks for reversion trades in two extreme zones: long entries fire when the previous bar's RSI dipped to 22 or below, short entries fire when it reached 93 or above. Both thresholds sit far out on the RSI scale — the 22/93 pair is roughly twice as selective as the textbook 30/70 boundaries, so signals only emerge from genuine capitulation, not ordinary pullbacks. The classification as 'TrendFollow' is the project taxonomy; the actual code is a mean-reversion system, and the EMA filter reinforces that by closing positions whenever the trend gets too directional.

The entry logic is bar-by-bar, gated by a custom cooldown. On the first tick of each new bar on the configured time frame (default BarTimeFrame=5 = PERIOD_H1), the EA copies two RSI values from the iRSI(19) handle, then checks them against the previous call's stored RSI held in previousRSIDef. A long fires when currentRSI is above 22 and previousRSIDef was at or below 22. A short fires when currentRSI is below 93 and previousRSIDef was at or above 93. After any order, a 209-second cooldown blocks re-entry; combined with the new-bar gate, the system can take at most one trade per new bar, then waits roughly 3.5 minutes before another is permitted. The order tickets themselves are sent as market orders with 0/0 SL/TP brackets via trade.Buy() and trade.Sell() with the magic set to 22218103 and a 3-point slippage tolerance.

Once a position is open, the EA watches RSI for a symmetrical exit: longs close when RSI climbs to 86, shorts close when RSI falls to 10. Those targets sit 64 and 83 RSI-points away from the entry thresholds respectively, which gives the trade room to mean-revert before the exit is triggered. The protective stop is not a fixed pips number — it's a 295-point trailing stop managed by ApplyTrailingStop(), which iterates the open positions each tick, looks up point size and digit count for the symbol, and ratchets the SL toward (but never against) price once profit exceeds 295 points. The trailing distance is wide on purpose: 295 points is roughly $2.95 on a 0.01-lot XAUUSD position, so the stop is only moved after the trade has produced several dollars of profit, then it locks in progressively more of that profit as price advances. The trailing routine relies on TryModify_EX18103, which wraps trade.PositionModify in a three-attempt retry loop with 100ms sleeps for requote and timeout errors.

The signature design choice is the EMA-based 'no-trade' gate. After loading the 140-period EMA buffer, the EA computes two derived quantities: emaSlope = (currentEMA - previousEMA) * 100 and priceToEmaDistance = (close - currentEMA) * 10. If either exceeds its threshold (105 and 165 respectively) in absolute value, the strategy treats the market as too directional and forcibly closes any open position, then skips new entries until the slope and distance cool off. The intent is to keep the reversal logic from catching a falling knife in a strong trend. Note that both inputs are scaled — emaSlopeThreshold=105 actually represents a 1.05-unit raw move in the EMA across one bar, and emaDistanceThreshold=165 represents 16.5 units of separation between price and EMA. Both are large enough that the gate only fires on clearly directional bars, not minor fluctuations.

Time and day filters are also hard-coded into the entry path. WeekDays_Check() reads the server's day-of-week from the input boolean flags, with default settings: only Tuesday, Wednesday, and Thursday are enabled — Sunday, Monday, Friday, and Saturday are all false. Combined with the hour window (server time 7:00 to 18:59, exclusive on both ends via the tradingHourTwoBegin=6, tradingHourTwoEnd=19 check), the EA is only active during the overlap of midweek European morning and the U.S. session open. The first hour window configured in the inputs (tradingHourOneBegin=24 to tradingHourOneEnd=22) is dead code: currentHour < 22 && currentHour > 24 is always false because 24 is end-of-day and 22 precedes it. Outside the active window, OnTick() calls Close_Position_MN() to flatten any open position and returns. This means a position opened at 17:55 will be force-closed by the hour filter at 18:00, even if the RSI exit hasn't fired.

A few design notes worth surfacing for traders. The trade tickets carry no SL/TP — the only protective mechanism is the trailing stop, and only after profit exceeds 295 points. Lot size is fixed at 0.01; there is no risk-percent sizing and no balance-based scaling, so position sizing is constant regardless of account equity. Magic number 22218103 is hard-coded into the MagicNumber input. The functions TryClose_EX18103, TryClosePartial_EX18103, and TryModify_EX18103 are wired into the trade path with 200ms/100ms retry loops for requote and timeout errors; only TryClose_EX18103 and TryModify_EX18103 are called in the live code path (no partial-close use). The 12-layer marketing claim in the header is aspirational — in the actual code, SIGNAL + ENTRY + EXIT are implemented, plus a NO-TRADE gate (the EMA trend filter, hour filter, day filter, cooldown) and a partial MANAGE (the trailing stop). There is no risk-percent sizing, no balance-scaling CAP, no news filter, no regime classifier, no partial-close scaling, and no OnTester pass.

What to expect in backtest: the 22/93 RSI zones are rare events, so trade frequency will be low — likely a handful of setups per week on H1 XAUUSD, more on M1. The 295-point trailing stop is wide in dollar terms but tight in the 19-period RSI context, and the 209-second cooldown prevents rapid re-entries when the same RSI extreme fires across consecutive bars. The Tue-Thu-only day filter is the largest source of trade reduction: about 43% of the week is simply skipped. Combined, the system should produce sparse, mean-reversion-style trades that close either on the RSI target or on the trailing stop, with the EMA trend gate acting as a defensive flatten during strong directional moves.

Strategy Deep Dive

EX18103 boots two indicators on OnInit() — an iRSI(19) and an iMA(EMA, 140) — and releases both on OnDeinit(). OnTick() opens with a new-bar gate keyed on the configured BarTimeFrame, so the heavy logic only runs once per bar instead of every tick; within that one execution, the EA copies two RSI values and the prior call's stored RSI into previousRSIDef, then runs the day, hour, cooldown, and trend-strength checks before reaching the entry block. Long and short entries both use a 1-bar RSI crossover against extreme thresholds (22 for longs, 93 for shorts) and are dispatched as market orders with no SL/TP via trade.Buy() / trade.Sell(). Every tick — even on bars that fail the new-bar gate — the trailing stop loop iterates the open positions, computes symbol-specific point and digit, and pushes the SL tighter as price moves in the trade's favor. The retry helpers TryClose_EX18103 and TryModify_EX18103 wrap the CTrade calls in 200ms/100ms retry loops to absorb requote and timeout errors before falling through.

Entry Signal

On the first tick of each new bar on the configured time frame, EX18103 reads two RSI(19) values and compares them to its extreme thresholds. A long entry fires when the current RSI is above 22 and the previous call's stored RSI (previousRSIDef) was at or below 22; a short entry fires when the current RSI is below 93 and previousRSIDef was at or above 93. A 209-second cooldown blocks the next entry after every fill, and the new-bar gate means at most one entry can fire per bar. Trades only open on Tuesday, Wednesday, or Thursday, between 07:00 and 18:59 server time, and only when the EMA(140) slope and price-to-EMA distance are below their trend gates.

Exit Signal

Open positions are watched each tick for the symmetrical RSI exits: longs close when RSI reaches 86, shorts close when RSI drops to 10. The protective mechanism is a 295-point trailing stop managed by ApplyTrailingStop(), which ratchets the SL toward price once profit exceeds 295 points and never moves it backwards. The day and hour filters also force a flatten — any position still open at 19:00 server time, or any day outside Tue-Thu, is closed by Close_Position_MN(). There are no fixed pips SL/TP attached at entry; only the RSI exit and the trailing stop can take a position off.

Stop Loss

No fixed stop is attached at order open — the trade tickets are sent with 0/0 SL/TP brackets via trade.Buy() and trade.Sell(). The protective stop is a 295-point trailing stop that only engages once price has moved 295 points in profit, then locks in progressively more of the profit. The EMA trend gate is an additional defensive layer: if |emaSlope| exceeds 105 or |priceToEmaDistance| exceeds 165, the EA forcibly closes any open position.

Take Profit

Profit-taking is RSI-driven, not pips-driven. Long positions close when RSI climbs to 86, short positions close when RSI drops to 10. There is no fixed-pips take-profit attached to the order ticket itself; the trailing stop can also realize profit along the way. The hour filter (19:00 server time cutoff) and day filter (Tue-Thu only) act as implicit TPs by flattening the position at the end of the active window.

Best For

Minimum recommended balance: $100 (the fixed 0.01 lot size keeps margin usage low on retail accounts). The strategy is built for XAUUSD on the M1-H1 band — at H1 the 22/93 RSI zones are rare, generating a few setups per week; at M1 the same zones fire more often and the 209-second cooldown becomes the main throttle. Broker setup should target an ECN or raw-spread account with low latency, since the trailing stop re-prices every tick and the RSI exits depend on accurate tick prints; the 3-point slippage tolerance is tight by default. The Tue-Thu day filter and 07:00-19:00 server-time window mean traders running on UTC-offset servers (e.g., GMT+2 or GMT+3) should align their local session with the European + early U.S. overlap.

Strategy Logic

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

Family: TrendFollow Magic: 22218103 Version: 2.00

BRIEF: RSI + EMA reversal strategy that buys on oversold crossover and sells on overbought crossover, filtered by EMA slope and price-to-EMA distance. Includes trailing stop, cooldown, day-of- week filter, and trading hour windows. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • WeekDays_Init()
  • WeekDays_Check()
  • Close_Position_MN()
  • ApplyTrailingStop()
  • TimeHour()
  • TryClose_EX18103()
  • TryClosePartial_EX18103()
  • TryModify_EX18103()

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (20 total across 2 groups):

  • [=== Trade Management ===] MagicNumber = 22218103 // Magic Number
  • [=== Trade Management ===] InpTradeComment = "Psgrowth.com Expert_18103" // Trade Comment
  • [=== Trade Management ===] rsiPeriod = 19 // RSI period
  • [=== Trade Management ===] overboughtLevel = 93 // Overbought level (RSI > 70 for sell)
  • [=== Trade Management ===] oversoldLevel = 22 // Oversold level (RSI < 30 for buy)
  • [=== Trade Management ===] lotSize = 0.01 // Trade lot size
  • [=== Trade Management ===] slippage = 3 // Slippage for orders
  • [=== Trade Management ===] cooldownSeconds = 209 // Cooldown period in seconds
  • [=== Trade Management ===] TimeFrame1 = 1 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // RSI Timeframe
  • [=== Trade Management ===] TimeFrame2 = 1 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // EMA Timeframe
  • [=== Trade Management ===] BarTimeFrame = 5 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // EMA Timeframe
  • [=== Trade Management ===] emaPeriod = 140 // EMA period
  • [=== Trade Management ===] emaSlopeThreshold = 105 // EMA slope threshold for trend strength
  • [=== Day Filter ===] Sunday = false // Sunday
  • [=== Day Filter ===] Monday = false // Monday
  • [=== Day Filter ===] Tuesday = true // Tuesday
  • [=== Day Filter ===] Wednesday = true // Wednesday
  • [=== Day Filter ===] Thursday = true // Thursday
  • [=== Day Filter ===] Friday = false // Friday
  • [=== Day Filter ===] Saturday = false // Saturday
Pseudocode
// Pipsgrowth EX18103 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// RSI + EMA reversal strategy that buys on oversold crossover and sells on overbought crossover, filtered by EMA slope and price-to-EMA distance. Includes trailing stop, cooldown, day-of- week filter, and trading hour windows. 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:
M1H1

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
MagicNumber22218103Magic Number
InpTradeComment"Psgrowth.com Expert_18103"Trade Comment
rsiPeriod19RSI period
overboughtLevel93Overbought level (RSI > 70 for sell)
oversoldLevel22Oversold level (RSI < 30 for buy)
lotSize0.01Trade lot size
slippage3Slippage for orders
cooldownSeconds209Cooldown period in seconds
TimeFrame11Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // RSI Timeframe
TimeFrame21Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // EMA Timeframe
BarTimeFrame5Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // EMA Timeframe
emaPeriod140EMA period
emaSlopeThreshold105EMA slope threshold for trend strength
SundayfalseSunday
MondayfalseMonday
TuesdaytrueTuesday
WednesdaytrueWednesday
ThursdaytrueThursday
FridayfalseFriday
SaturdayfalseSaturday
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18103.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18103 RSI_EMA_Reversal — RSI reversal with EMA slope filter and trailing stop, full 12-layer stack."

#include <Trade\Trade.mqh>

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_TIMEFRAMES g_TimeFrame1 = PERIOD_H1;
ENUM_TIMEFRAMES g_TimeFrame2 = PERIOD_H1;
ENUM_TIMEFRAMES g_BarTimeFrame = PERIOD_H1;
input group "=== Trade Management ==="
input int MagicNumber = 22218103;    // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_18103"; // Trade Comment
input int rsiPeriod = 19;           // RSI period
input int overboughtLevel = 93;     // Overbought level (RSI > 70 for sell)
input int oversoldLevel = 22;       // Oversold level (RSI < 30 for buy)
input double entryRSIBuySpread = 0;
input double entryRSISellSpread = 0;
input double lotSize = 0.01;        // Trade lot size
input int slippage = 3;            // Slippage for orders
input int cooldownSeconds = 209;   // Cooldown period in seconds
input int TimeFrame1 = 1; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // RSI Timeframe
input int TimeFrame2 = 1; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // EMA Timeframe
input int BarTimeFrame = 5; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // EMA Timeframe
input int emaPeriod = 140;           // EMA period
input double emaSlopeThreshold = 105; // EMA slope threshold for trend strength
input double exitBuyRSI = 86;
input double exitSellRSI = 10;
input double TrailingStop  = 295;
input double emaDistanceThreshold = 165;
input int tradingHourOneBegin = 24;
input int tradingHourOneEnd = 22;
input int tradingHourTwoBegin = 6;
input int tradingHourTwoEnd = 19;

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;

Full source code available on download

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

Tags:ex18103trendfollowpipsgrowthfreemt5xauusd

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