Pipsgrowth EX18090 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18090 KA-Gold Bot — Keltner breakout gold trend-follow, full 12-layer stack.
Overview
Pipsgrowth EX18090 ("KA-Gold Bot") trades XAUUSD with a 3-of-3 trend-following entry that requires a Keltner-channel breakout, an EMA200 regime gate, and a same-bar EMA10 cross through the channel boundary. The EA is bar-driven: OnTick() refreshes the three indicator buffers, runs UpdateOrders() and TrailingStop(), and only calls OpenTrades() when iTime() on bar 0 has changed. There is no tick-by-tick reentry, so entries are deterministic and slippage is bounded to one new bar.
The custom Keltner channel is built in CalculateSignal() from three independent measurements. The middle line is the standard iMA(50) EMA on close. The upper and lower bands are then computed as middle +/- findAvg(50, shift), where findAvg() walks the last 50 completed bars and averages the per-bar (high - low) range. The result is a Keltner variant whose width scales with the symbol's own recent range rather than with a fixed ATR multiplier, which keeps the breakout threshold self-adjusting on gold's volatility cycle. The function evaluates the band twice: once at shift=1 (the closed bar) and once at shift=2 (the bar before that), so two consecutive readings of the channel are available for the cross logic.
A long setup needs all three of these conditions to hold on the same closed bar: (1) iClose(1) sits above the upper Keltner band, meaning the close itself broke out rather than merely tagging the line; (2) iClose(1) is above EMA200(1), filtering the trade to a confirmed long-term trend; and (3) EMA10 crossed through the upper band between bar 2 and bar 1 (EMA10[2] < upper[2] AND EMA10[1] > upper[1]). The third condition is the trigger that distinguishes a real breakout from a slow drift: a fast EMA crossing the channel during the same bar the close is above it is a strong momentum signature. Sells are the mirror: close below the lower band, close below EMA200, and EMA10 crossed through the lower band from above.
Risk brackets are symmetric and 1:1: InpSL_Pips and InpTP_Pips both default to 500 points on gold (a 1:1 reward-to-risk bracket). Both are converted to price through Pips2Double, which the EA derives from the symbol's digits (3 or 5 digit brokers get a 10x multiplier on the _Point unit so that 500 user pips means 5.00 of price on 2-decimal gold). TP can be disabled by setting InpTP_Pips=0, in which case the trade becomes a pure trailing-managed runner; the trailing function checks this flag with if(InpTP_Pips != 0) newTP = m_position.TakeProfit() and otherwise passes 0 to the modify, leaving whatever the broker has stored. With defaults, the bot is a 1:1 bracket system; the trailing only matters once TP is removed or scaled out.
Trailing logic in TrailingStop() uses a one-shot trigger and then a stepped ratchet. Each side has a boolean flag (isSLBuyOrd_Trigger, isSLSellOrd_Trigger) that flips to true the first time Bid - PriceOpen (or PriceOpen - Ask) exceeds ExtTrailingTrigger (300 pips default). After that point, every new bar where profit is greater than ExtTrailingStop + ExtTrailingStep (300 + 100 = 400 pips) calls TryModify_EX18090 to push the SL to Bid - ExtTrailingStop. The compare m_position.StopLoss() < (Bid - (ExtTrailingStop + ExtTrailingStep)) is the one-way ratchet: SL only tightens, never loosens, and each ratchet step is exactly ExtTrailingStep (100 pips) further into profit. The flags reset in UpdateOrders() when the position closes or when an opposite position appears, so a fresh position starts the trailing cycle from zero.
The money model in CalculateVolume() is the only risk dial. When isVolume_Percent=true (the default), lot size is computed as (InpRisk * FreeMargin) / 100000, floored to the nearest multiple of Inpuser_lot (default 0.01). The result is then clamped to LotsMax / LotsMin. With InpRisk=1.0 and a $1,000 account the formula yields a fraction of a standard lot; the floor to Inpuser_lot (0.01) means anything below that snaps up to the broker minimum. This is not a true percent-of-balance risk model in the SL-distance sense — it does not size off the stop distance — it sizes off free margin only. Traders expecting Kelly-style risk should set isVolume_Percent=false and use Inpuser_lot directly.
Three no-trade gates run before the entry call. CheckSpreadAllow() rejects when acSpread (raw point spread, not pips) exceeds InpMax_spread=65; on a 2-decimal gold feed that allows roughly 6.5 pips, which is permissive for M5 trend-following. CheckVolumeValue() validates the lot against SYMBOL_VOLUME_MIN, SYMBOL_VOLUME_MAX, and the volume step. CheckMoneyForTrade() runs OrderCalcMargin to ensure the lot has enough free margin for a hypothetical fill. CheckStopLoss() then confirms that |price - SL| and |price - TP| are both outside the broker's SYMBOL_TRADE_STOPS_LEVEL, which avoids the TRADE_RETCODE_INVALID_STOPS rejection on brokers with a freeze zone. The InpTimeFilter, when true, restricts entries to 02:30 - 21:00 server time — that window covers Asia-open through the NY close and is intentionally broad; the only days excluded are the rollover gap (22:00-02:30) and weekends.
The execution helpers TryClose_EX18090, TryClosePartial_EX18090, and TryModify_EX18090 are wired as standard 3-attempt wrappers that retry only on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED with a 200ms sleep (100ms for modify) and break out on any other retcode. The partial-close and close helpers exist but are not actually called from the EA's main flow — OpenTrades() uses m_trade.Buy / m_trade.Sell directly with a single attempt, and TrailingStop() routes every modify through TryModify_EX18090. So in practice the resilience layer is asymmetric: modifications are retried, entries are not. On a noisy news tick that whiffs the entry, the trade is simply missed on that bar and the next bar gets a fresh attempt.
A note on the source: the SELL branch in CalculateSignal() reads result = true rather than result = ORDER_TYPE_SELL, which compiles to the integer 1 — and ORDER_TYPE_SELL is also 1 in ENUM_ORDER_TYPE, so the EA works by accident. If a future refactor changes the enum values, the sell side would silently start emitting order types that no condition ever reaches. This is a code-smell worth flagging if you ever fork the bot.
On a strategy-style summary: this is a momentum-continuation, not a mean-reversion, EA. The Keltner+EMA10 cross is a high-conviction breakout pattern that fires rarely — typically a handful of times per week on XAUUSD M5 — and the 1:1 bracket plus stepped trail is built to let winners run when TP is disabled and to lock quickly when TP is on. Set InpTP_Pips=0 and the trailing takes over; keep InpTP_Pips=500 for a faster, bracket-only behavior. The EMA200 filter alone rules out roughly half the candles on gold's chop regime, so the win rate is the function of gold's trending periods, not the EA's logic. Backtests will look best across sustained trends (2020 summer, 2022 Q1, 2024 spring) and worst during the tight $30 ranges that print 50+ false breakouts in a row.
For live deployment: any ECN/STP broker with raw spreads under 50 points on XAUUSD will keep CheckSpreadAllow() open most of the time. The 500/500 point bracket is wide enough that micro-lot accounts ($100-300) are workable, though slippage on the entry will be a larger percentage of profit. Run on a VPS with sub-100ms broker latency for the trailing to actually move inside the same bar as the trigger; on a home connection the 300-pip trigger ratchet can be missed by a full bar, which changes the geometry of the trade.
Strategy Deep Dive
OnTick() loads three EMA buffers (10, 200, and the 50-period Keltner middle), runs UpdateOrders() to clear the trailing-trigger flags and detect an open position, then calls TrailingStop() which walks all positions with this magic and ratchets any triggered position's SL via TryModify_EX18090. CalculateSignal() then evaluates the Keltner band at shifts 1 and 2, computes the upper/lower limits using findAvg()'s 50-bar high-low range, and only signals when the close is outside the band, the close is on the right side of EMA200, and EMA10 has crossed through the band. OpenTrades() is gated on a new bar (iTime change), on the InpTimeFilter window 02:30-21:00 server, and on CheckSpreadAllow / CheckVolumeValue / CheckStopLoss / CheckMoneyForTrade passing — only then does m_trade.Buy or m_trade.Sell fire, attaching the 500/500 bracket. CalculateVolume() sizes the lot from free margin when isVolume_Percent is true, else uses Inpuser_lot. There are 3 iMA handles, 14 functions, 20 inputs, no pyramid or martingale, one position at a time, and filling is auto-detected per symbol.
Long entry requires three conditions on the same closed M5 bar: iClose(1) above the Keltner upper band (50-EMA close +/- the 50-bar average of high-low ranges), iClose(1) above EMA200(1), and EMA10 crossing through that same Keltner upper band between bar 2 and bar 1. Sells are the strict mirror — close below the lower band, below EMA200, and EMA10 crossing through the lower band. The EA calls OpenTrades() only on a new-bar event, so entries are bar-bound and the 1:1 risk bracket is attached on fill.
Default exit is the 500/500-point symmetric TP and SL bracket (1:1 R:R). After profit crosses the 300-pip trigger, the trailing ratchet activates: every new bar where profit exceeds 400 pips pushes the SL to Bid-300 (or Ask+300 for sells) via TryModify_EX18090, one-way and never loosening. There is no opposite-signal exit — when TP is on, the trade is closed by the broker at TP, not by code.
Initial SL is a fixed 500 points below entry (InpSL_Pips default). Once profit exceeds 300 points the SL is ratcheted to Bid-300 (or Ask+300 for shorts) on each new bar where profit is greater than 400 points, and only tightens. No SL is set for hedging positions; isSLBuyOrd_Trigger / isSLSellOrd_Trigger reset on position close or flip.
TP defaults to 500 points above entry (InpTP_Pips=500) for a 1:1 R:R bracket. Setting InpTP_Pips=0 disables the broker-side TP and leaves the trade under full trailing management; the trailing ratchet still tightens the SL but does not set a new TP. With TP on, the trade is closed by the broker at the target, not by an in-code function.
Best for XAUUSD M5 traders who want a low-frequency breakout system — expect 2-5 entries per week on gold — running on a $100+ account with 1% risk per trade and a 1:1 R:R default that flips to trailing when TP is disabled. The 65-point raw spread cap and 500-point brackets need an ECN/STP broker with raw spread under 50 points; the 02:30-21:00 server-time window covers the full Asia-to-NY session, so the EA is most active during London and the New York morning. Use a VPS with sub-100ms latency so the trailing ratchet actually fires inside the trigger bar.
Strategy Logic
Pipsgrowth EX18090 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218090
Version: 2.00
BRIEF:
Gold trend-follow bot using Keltner channel breakout with EMA10/EMA200 filter, ATR-style trailing and time/session filter. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
findAvg()OpenTrades()TrailingStop()UpdateOrders()CalculateVolume()CheckSpreadAllow()CheckVolumeValue()CheckStopLoss()CheckMoneyForTrade()DayOfWeekDescription()RefreshRates()TryClose_EX18090()- ...and 2 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (20 total across 6 groups):
- [=== Indicators Settings ===]
InpKeltnerPeriod= 50 // Keltner length - [=== Indicators Settings ===]
InpEMA10= 10 //EMA1 period - [=== Indicators Settings ===]
InpEMA200= 200 //EMA2 period - [=== Trading Settings ===] Inpuser_lot =
0.01// Volume trade - [=== Trading Settings ===]
InpSL_Pips= 500 //Stoploss(in Pips) - [=== Trading Settings ===]
InpTP_Pips= 500 //TP(in Pips) (0 = No TP) - [=== Trading Settings ===]
InpMax_slippage= 3 // Maximum slippageallow_Pips. - [=== Trading Settings ===]
InpMax_spread= 65 // Maximum allowed spread (in Point) (0 = floating) - [=== Trailing Settings ===]
InpTrailingTrigger= 300 // Trailing TriggerPips(0 = Inactive) - [=== Trailing Settings ===]
InpTrailingStop= 300 // Trailing stop (in Pips) - [=== Trailing Settings ===]
InpTrailingStep= 100 // TrailingStep(in Pips) - [=== Trading Time Settings ===]
InpTimeFilter=true// Trading Time Filter - [=== Trading Time Settings ===]
InpStartHour= 2 // Start Hour - [=== Trading Time Settings ===]
InpStartMinute= 30 // Start Minute - [=== Trading Time Settings ===]
InpEndHour= 21 // End Hour - [=== Trading Time Settings ===]
InpEndMinute= 0 // End Minute - [=== Money Settings ===]
isVolume_Percent=true// Allow Volume Percent - [=== Money Settings ===]
InpRisk= 1 // Risk Percentage ofBalance(%) - [=== General Settings ===]
InpMagicNumber=22218090// Magic Number - [=== General Settings ===]
InpTradeComment= "Psgrowth.com Expert_18090" // TradeComment
// Pipsgrowth EX18090 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Gold trend-follow bot using Keltner channel breakout with EMA10/EMA200 filter, ATR-style trailing and time/session filter. 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
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 |
|---|---|---|
| InpKeltnerPeriod | 50 | Keltner length |
| InpEMA10 | 10 | EMA 1 period |
| InpEMA200 | 200 | EMA 2 period |
| Inpuser_lot | 0.01 | Volume trade |
| InpSL_Pips | 500 | Stoploss (in Pips) |
| InpTP_Pips | 500 | TP (in Pips) (0 = No TP) |
| InpMax_slippage | 3 | Maximum slippage allow_Pips. |
| InpMax_spread | 65 | Maximum allowed spread (in Point) (0 = floating) |
| InpTrailingTrigger | 300 | Trailing Trigger Pips (0 = Inactive) |
| InpTrailingStop | 300 | Trailing stop (in Pips) |
| InpTrailingStep | 100 | Trailing Step (in Pips) |
| InpTimeFilter | true | Trading Time Filter |
| InpStartHour | 2 | Start Hour |
| InpStartMinute | 30 | Start Minute |
| InpEndHour | 21 | End Hour |
| InpEndMinute | 0 | End Minute |
| isVolume_Percent | true | Allow Volume Percent |
| InpRisk | 1 | Risk Percentage of Balance (%) |
| InpMagicNumber | 22218090 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_18090" | Trade Comment |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property description "Pipsgrowth.com EX18090 KA-Gold Bot — Keltner breakout gold trend-follow, full 12-layer stack."
#property strict
#define ExtBotName "KA-Gold Bot" //Bot Name
#define Version "2.00"
//Import inputal class
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\OrderInfo.mqh>
//--- introduce predefined variables for code readability
#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)
#define Bid SymbolInfoDouble(_Symbol, SYMBOL_BID)
//--- input parameters
input group "=== Indicators Settings ==="
input int InpKeltnerPeriod = 50; //Keltner length
input int InpEMA10 = 10; //EMA 1 period
input int InpEMA200 = 200; //EMA 2 period
input group "=== Trading Settings ==="
input double Inpuser_lot = 0.01; //Volume trade
input double InpSL_Pips = 500; //Stoploss (in Pips)
input double InpTP_Pips = 500; //TP (in Pips) (0 = No TP)
input int InpMax_slippage = 3; // Maximum slippage allow_Pips.
input double InpMax_spread = 65; //Maximum allowed spread (in Point) (0 = floating)
input group "=== Trailing Settings ==="
input double InpTrailingTrigger = 300; //Trailing Trigger Pips (0 = Inactive)
input double InpTrailingStop = 300; //Trailing stop (in Pips)
input double InpTrailingStep = 100; //Trailing Step (in Pips)
input group "=== Trading Time Settings ==="
input bool InpTimeFilter = true; //Trading Time Filter
input int InpStartHour = 2; //Start Hour
input int InpStartMinute = 30; //Start Minute
input int InpEndHour = 21; //End Hour
input int InpEndMinute = 0; //End Minute
input group "=== Money Settings ==="
input bool isVolume_Percent = true; //Allow Volume Percent
input double InpRisk = 1; //Risk Percentage of Balance (%)
input group "=== General Settings ==="
input int InpMagicNumber = 22218090; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_18090"; // Trade Comment
//Local parameters
int Pips2Points; // slippage 3 pips 3=points 30=points
double Pips2Double; // Stoploss 15 pips 0.015 0.0150
int slippage;
long acSpread;
double ExtTrailingTrigger = 0.0;
double ExtTrailingStop = 0.0;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.