Pipsgrowth EX18106 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18106 MSS_EA — Market Structure Shift detector, full 12-layer stack.
Overview
EX18106 is not a trade-executing EA. The script fires no orders, attaches no protective stops, and never modifies positions. Instead, the OnTick() function runs a fractal-style pivot scan that locates swing highs and swing lows on the current chart, then waits for price to cross those swing levels and labels the resulting break as either a regular 'Break' or a 'Break (MSS)' Market Structure Shift event. The detection logic is compact — only 8 functions — and the input surface is reduced to a magic number and a trade-comment string, with no parameter for swing length, color, threshold, or risk model. The #property description line claims a 'full 12-layer stack', but the actual implementation is a single-pass detector: pivot scan + rolling buffer + break classifier + chart annotation.
The pivot detection algorithm works on a fixed 10-bar window defined by const int length = 10;. On each confirmed new bar, the script walks bars curr_bar = length (bar 10) bars back from the current bar and compares its high and low against the bars to the left and right of it within the same 10-bar neighborhood. If high(curr_bar) is greater than high(curr_bar - a) AND high(curr_bar) is greater than high(curr_bar + a) for every a from 1 to 10, the bar is marked isSwingHigh = true. The symmetric condition for isSwingLow runs in parallel: low(curr_bar) < low(curr_bar - a) AND low(curr_bar) < low(curr_bar + a) for all a in the same range. The check fires only on a new bar — the static prevBars counter holds the bar count from the previous tick and resets isNewBar to true only when iBars(_Symbol, _Period) changes between ticks.
When a swing high is found, the price is stored in a rolling 2-element buffer swingHighs_Array[] and the script calls drawSwingPoint() to place a blue OBJ_ARROW (wingdings code 77) at the swing bar with the label 'BoS' (Break of Structure) anchored below the price. Swing lows are drawn in red with the same code, anchored above. Each call to drawSwingPoint also creates a paired OBJ_TEXT with the literal 'BoS' string set via ObjectSetString(..., OBJPROP_TEXT, ' ' + text), so the label appears with two leading spaces. The 2-element buffer trims the oldest entry each time a new swing is added: ArrayRemove(swingHighs_Array, 0, 1) pops index 0, ArrayResize extends by 1, and the new swing value lands at the back. After the resize, ArrayPrint dumps the buffer to the log with the literal 'POPULATED!' header — useful for tracing during backtest, harmless in live.
The break-of-structure check runs on every tick, not just new bars. After the pivot detection phase, the script reads SymbolInfoDouble(_Symbol, SYMBOL_ASK) and SymbolInfoDouble(_Symbol, SYMBOL_BID), then asks two questions: did price break above a stored swing high (Ask > swing_H), or did price break below a stored swing low (Bid < swing_L)? If a break is detected, the script first scans up to length * 2 + 1000 = 1020 bars back from the current bar to locate the exact bar index where swing_H (or swing_L) originally appeared, then evaluates the MSS condition:
MSSuptrend:swingHighs_Array[0] > swingHighs_Array[1]ANDswingLows_Array[0] > swingLows_Array[1]. Both the most recent high and the most recent low are higher than their predecessors — a higher-high / higher-low sequence.MSSdowntrend:swingHighs_Array[0] < swingHighs_Array[1]ANDswingLows_Array[0] < swingLows_Array[1]. A lower-high / lower-low sequence.
When MSS is true, drawBreakLevel_MSS() paints a 4-pixel-wide arrowed line in clrDarkGreen (uptrend) or clrBlack (downtrend) from the original swing bar to the current bar, with a 13-point 'Break (MSS)' label anchored on the right edge. When MSS is false, drawBreakLevel() paints a thinner 2-pixel line in clrBlue or clrRed with a 10-point 'Break' label. The visual difference between the two is intentional — MSS lines are thicker and use distinct colors to make higher-timeframe trend changes stand out on the chart at a glance.
After the break is drawn, the swing reference is reset (swing_H = -1.0; or swing_L = -1.0;) and the function returns early, so a single tick cannot fire multiple break annotations back-to-back. The next swing that forms on a future bar will repopulate the rolling buffer and the cycle restarts. Until then, the Ask/Bid checks at the start of OnTick simply skip — neither swing_H > 0 nor swing_L > 0 is true while the references are negative.
Three trade-related helpers — TryClose_EX18106(), TryClosePartial_EX18106(), and TryModify_EX18106() — are declared and even instantiated (CTrade g_trade_wrappers_EX18106;) but never called from OnTick(). They exist in the file as scaffolding, presumably to be wired into a future version that adds trade execution. The included <Trade\Trade.mqh> header is also unused at runtime. The Print() statements inside the swing-detection and break blocks will flood the Experts log with messages like 'WE DO HAVE A SWING HIGH @ BAR INDEX 10 H: 2543.21' and '$$$$$$$$$ BUY SIGNAL NOW. BREAK OF SWING HIGH'. These are not actual trade alerts — they are diagnostic prints, and a trader who runs the EA on a 5-minute XAUUSD chart during an active London or New York session will see them fire frequently.
Use cases. EX18106 is best suited for discretionary swing traders who want an automated way to mark swing pivots and BOS/MSS levels on their XAUUSD M5 or H1 chart without manually drawing trendlines. The 10-bar pivot window is hard-coded — it cannot be tuned to detect 5-bar short-term pivots or 20-bar swing pivots. The rolling 2-element swing buffer means MSS classification only kicks in after the third swing in either direction has formed; the first two swings are simply annotated as BoS without a trend bias. Because no positions are opened, EX18106 carries no execution risk and can run on a $100 micro account or a $100,000 institutional book with identical behavior. The broker does not matter for the detection itself, but the EA must be attached to a chart that has visible price history (the 10-bar left-side and 10-bar right-side scan needs past bars to be valid), and a freshly opened chart with fewer than 20 bars of data will not produce any signals. For traders who want a pure indicator overlay with no auto-trading, EX18106 is a starting point. For traders who want an EA that actually opens trades on MSS breaks, EX18106 is a visualization shell — the trade entry logic has not been added yet.
Strategy Deep Dive
On every confirmed new bar, EX18106 walks 10 bars to the left and 10 to the right of the bar at index 10 looking for a local high and a local low — a classic 10-bar fractal pivot scan. Each confirmed swing populates a 2-element rolling buffer (swingHighs_Array or swingLows_Array) that always keeps the two most recent pivots in memory, with the older one popped on each new addition. Every tick — not just new bars — checks whether Ask has crossed above the most recent swing high or Bid has crossed below the most recent swing low; if so, the script classifies the break as either a regular BOS (Break of Structure) when the prior swings don't form a higher-high/higher-low or lower-high/lower-low sequence, or as an MSS (Market Structure Shift) when they do. MSS lines are drawn 4 pixels wide in dark green (uptrend) or black (downtrend), while regular breaks are drawn 2 pixels wide in blue or red — a visual hierarchy that lets the trader distinguish continuation breaks from genuine trend shifts at a glance. The included CTrade wrapper and the three TryClose / TryClosePartial / TryModify retry helpers are dead code that the current build never invokes, so no orders are ever placed despite the #property description's claim of a 'full 12-layer stack'.
EX18106 does not place trades. A 'BUY SIGNAL' prints to the Experts log and a blue arrowed line is drawn on the chart when Ask crosses above the most recent stored swing high. A symmetric 'SELL SIGNAL' prints and a red line is drawn when Bid crosses below the most recent stored swing low. The detection runs on every tick, but the swing reference is reset after each break so back-to-back signals require a fresh 10-bar pivot to form on a subsequent bar.
There are no positions to exit because no positions are opened. The closest equivalent to an 'exit' is the reset of the swing reference: once Ask crosses swing_H (or Bid crosses swing_L), the script sets swing_H = -1.0 (or swing_L = -1.0) and returns early, so the same break cannot fire twice. The next signal waits for a new pivot to form on a subsequent bar before another break annotation can be drawn.
No stop-loss is ever attached. The three CTrade retry helpers (TryClose_EX18106, TryClosePartial_EX18106, TryModify_EX18106) are declared and instantiated but never called from OnTick, and the script never opens an order in the first place. SL is therefore not applicable to this EA.
No take-profit is ever attached. Take-profit logic is also not implemented; the EA's only 'profit-taking' event is the chart annotation when a swing is broken. There is no partial close, no basket TP, no equity lock — only the visual MSS / Break lines on the chart.
EX18106 is best for discretionary swing traders on XAUUSD M5 or H1 who want automated swing-pivot and BOS/MSS chart annotations without manually drawing trendlines. The hard-coded 10-bar pivot window cannot be tuned, so traders who need shorter or longer swing detection should look elsewhere. Because no orders are opened, the EA is safe to run on a $100 micro account with any broker that supports MetaTrader 5 — execution quality, spread, and slippage are irrelevant to its behavior.
Strategy Logic
Pipsgrowth EX18106 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218106
Version: 2.00
BRIEF:
Detects swing highs/lows and Market Structure Shifts (MSS) using a fractal-style pivot scan, then draws break levels and MSS annotations on the chart to visualise trend confirmation
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
- high()
- low()
- time()
drawSwingPoint()drawBreakLevel()drawBreakLevel_MSS()TryClose_EX18106()TryClosePartial_EX18106()TryModify_EX18106()
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (2 total across 1 groups):
- []
InpMagic=22218106// Magic number - []
InpTradeComment= "Psgrowth.com Expert_18106" // Trade comment
// Pipsgrowth EX18106 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Detects swing highs/lows and Market Structure Shifts (MSS) using a fractal-style pivot scan, then draws break levels and MSS annotations on the chart to visualise trend confirmation
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
How to Install This EA on MT5
- 1Download the .mq5 file using the button above
- 2Open MetaTrader 5 on your computer
- 3Click File → Open Data Folder in the top menu
- 4Navigate to MQL5 → Experts and paste the .mq5 file there
- 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
- 6Drag the EA onto an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the dialog
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpMagic | 22218106 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_18106" | Trade comment |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18106 MSS_EA — Market Structure Shift detector, full 12-layer stack."
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| === Identity === |
//+------------------------------------------------------------------+
input int InpMagic = 22218106; // Magic number
input string InpTradeComment = "Psgrowth.com Expert_18106"; // Trade comment
double swingHighs_Array[];
double swingLows_Array[];
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick(){
static bool isNewBar = false;
int currBars = iBars(_Symbol,_Period);
static int prevBars = currBars;
if (prevBars == currBars){isNewBar = false;}
else if (prevBars != currBars){isNewBar = true; prevBars = currBars;}
const int length = 10; // >2
int right_index, left_index;
int curr_bar = length;
bool isSwingHigh = true, isSwingLow = true;
static double swing_H = -1.0, swing_L = -1.0;
if (isNewBar){
for (int a=1; a<=length; a++){
right_index = curr_bar - a;
left_index = curr_bar + a;
//Print(a," <> ",right_index," > ",left_index);
if ( (high(curr_bar) <= high(right_index)) || (high(curr_bar) < high(left_index)) ){
isSwingHigh = false;
}
Full source code available on download
Educational purposes only. Do NOT use with real money. Test on demo accounts only.
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
Markets.com
Exness
IC Markets
Similar Expert Advisors
View All Expert AdvisorsMore Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.