P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18005 TrendFollow

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

Pipsgrowth.com EX18005 TrendlineCrossAlert — Trendline cross EA (manual + auto regression), full 12-layer stack.

Overview

Pipsgrowth EX18005 TrendlineCrossAlert does not invent patterns; it waits for price to cross a trendline, exactly the way a discretionary trader would draw one on a chart, then executes through the same risk and regime gates the rest of the TrendFollow family uses. The feature that separates it from a generic crossover EA is that the trendline is either computed inline from the last N closed bars using a least-squares linear regression, or read directly from chart objects the operator has drawn themselves (HLINE or OBJ_TREND). When both are active, the manually drawn line wins, so the trader can override the algorithmic baseline with their own view of where the market is breaking.

The automatic trendline is built on the fly by the function TrendlineSignal(). It pulls the last InpAutoTrendlineBars closed bars (default 50, so roughly four hours of M5 price), feeds close values and bar indices into the standard slope/intercept formula (slope = (N·Σxy − Σx·Σy) / (N·Σx² − (Σx)²), intercept = (Σy − slope·Σx) / N), and projects the line value at bar[1] and bar[2]. A bullish cross requires close2 ≤ lineAt2 and close1 > lineAt1; a bearish cross is the mirror. The function also walks the chart's OBJ_HLINE and OBJ_TREND objects, keeps the one whose value at bar[1] sits within 1% of the current close, and substitutes it as the active line — that is the manual override. If InpAutoTrendlineBars is set to 0 and InpUseManualLines is true, the regression is skipped entirely and the EA waits for the operator's own line to be broken.

Confidence is not a fixed number. It is calculated as min(100, ADX(14)[0] × 2) and floored at 10, so a quiet market with ADX around 15 yields a 30-confidence signal while a strong trend with ADX 45 yields 90. The signal only reads bar 1 and bar 2, which means it can only fire on a closed bar — no intrabar flicker triggers an entry.

Before any order is sent, DetectRegime() runs on every tick. It reads ATR(14), computes a percentile against the last 50 values, and combines the result with ADX(14) into a four-state classifier. REG_STRONG_TREND requires ADX ≥ InpADXMinTrend (20) and ATR percentile above 0.5. REG_WEAK_TREND fires when ADX ≥ 18. REG_RANGE trips when ATR percentile is below 0.25. Everything else falls into REG_CHOPPY and is hard-blocked. The indicators that feed this classifier are created in OnInit(): iATR(14), iADX(14), iBands(20, 2.0), and iMA(50) on PERIOD_H4 — note that the higher timeframe here is H4, not H1, so the trend agreement is read on a slower cycle than some of the other family members.

ConfirmEntry() then adds two more gates. The H4 EMA(50) must agree with trade direction (price above the EMA for longs, below for shorts), and the implied R:R must clear InpRRMin (1.5). At the default ATR multipliers of 1.5× for the stop and 3.0× for the target, the design ratio is 1:2, which is comfortably above the 1.5 floor.

CanTradeNow() is the no-trade gate. It refuses entry on: kill switch active, CHOPPY regime, capital floor breach (effective capital below InpCapitalCapFloor of 50 USD), spread over 50 points, server hour outside 7-20, weekends, daily realized loss at or above 3% of effective capital, weekly realized loss at or above 6%, active cooldown, or position count at the cap. The realized PnL trackers RealizedToday() and RealizedThisWeek() walk the history deals filtered to this magic only — no other EA's trades are counted in the daily or weekly ledger.

The cooldown mechanism is wired into OnTrade() rather than OnTick(). After a closing deal with negative net PnL, g_consecutiveLosses increments; once it hits InpCooldownAfterLosses (3), g_cooldownUntil is set to TimeCurrent() plus three bars of PeriodSeconds, which works out to 15 minutes on M5 or 3 hours on H1, the counter resets, and the EA logs the cooldown window. A winning trade resets the counter immediately. This is faster than the same-bar cooldown you sometimes see in cheaper EAs because it fires the moment a deal closes, not on the next bar open.

Risk and sizing are deliberately simple. CalcLots() divides EffCapital() × (InpRiskPercent / 100) (default 0.5% of equity, capped at InpCapitalCapAmount when set) by the per-lot loss at the ATR-derived stop distance, then runs the raw value through NormVol() which floors to the lot step and clamps to the symbol's min and max. Effective capital is min(account equity, InpCapitalCapAmount), so you can hard-cap a prop-firm allocation at any dollar figure without rewriting the EA.

The stop is computed at order time as ATR(14) × InpATRMultSL (1.5× by default), then the resulting distance is checked against the broker's stops level via StopsPoints() — if the distance is below the floor, the stop is widened by one point beyond the floor. The target is ATR(14) × InpATRMultTP (3.0×), giving a 1:2 R:R unless the multipliers are changed. OrderCalcMargin() pre-checks margin before the order is sent, and the trade object retries once on requote, price-changed, or timeout before giving up.

Position management runs every tick through ManageOpenPositions(). There are four exit paths, applied in this order: a 200-bar time stop, a regime-change exit (CHOPPY or RANGE closes the position outright), a one-shot break-even at 1R that moves the stop to entry plus or minus one point and only ever ratchets in the favorable direction, and a partial close of 50% at exactly 1R (so the partial fires the same tick as the break-even). The ATR trail kicks in at 1R and runs at ATR(14) × InpTrailATRMult (2.0× by default) from the current bid/ask, also only ever moving the stop favorably. Every modify and partial close is wrapped in TryModify_EX18005() and TryClosePartial_EX18005() — both retry up to 3 times on requote, timeout, price-off, or price-changed with 200ms sleeps.

There is no explicit basket target layer; the per-trade 1:2 R:R plus the partial-at-1R do the heavy lifting. There is no active news filter as code, but the NEWS_WINDOW_MIN constant is reserved (default ±30 min) for future use. The dry-run switch (InpDryRun = true by default) prints the intended order to the log without sending it, which is the safest way to validate that the trendline signal is firing where you expect before flipping to live.

The OnTester() formula is (STAT_PROFIT × STAT_PROFIT_FACTOR) / (1.0 + STAT_BALANCE_DD), returning 0 if the test has fewer than 30 trades or a degenerate PF or DD. The optimizer is therefore biased toward high-PF, low-DD, profitable configurations, and the 30-trade minimum prevents overfitting on a handful of lucky setups.

For live deployment, the trade-off to understand is that this EA does nothing on a market without a trendline break. If the regression slope is approximately zero, no cross can form and you will see long stretches of inactivity — that is by design. The EA is built for the trader who wants to be in only when a structural level gives way, not when a noisy oscillator flickers. Set InpAutoTrendlineBars higher (80 to 100) on noisier symbols like XAUUSD M5 to smooth the regression; drop it to 25-30 on H1 where the bars are fewer and the slope is more meaningful. Manual lines are useful for marking news-event highs and prior-day levels — the EA will trade the first clean break of any chart object that ends up within 1% of recent price.

Strategy Deep Dive

On each tick, DetectRegime() classifies the market from ADX(14) and ATR(14) percentile into one of four states — STRONG_TREND, WEAK_TREND, RANGE, or CHOPPY — and CHOPPY is hard-blocked before anything else runs. TrendlineSignal() then either fits a least-squares regression across the last InpAutoTrendlineBars closed bars to produce an automatic trendline, or reads the chart for an HLINE/OBJ_TREND object within 1% of recent price, with manual taking priority; a clean break of that line on the last closed bar (bar[2] ≤ line and bar[1] > line, or the mirror) is the entry trigger, gated further by H4 EMA(50) agreement and a 1.5 minimum R:R. TryEntry() sizes the order at 0.5% risk of effective capital against an ATR(14) × 1.5 stop with a 3.0× ATR target, retries once on requote/timeout, and ManageOpenPositions() takes over every tick: regime changes to CHOPPY or RANGE close the trade outright, the 200-bar time stop kicks in for aged positions, break-even ratchets the stop at 1R, the 50% partial close fires on the same tick, and the 2.0× ATR trail walks the stop in the favorable direction only — every modify and close call wrapped in a 3-retry helper that pauses 200ms on transient retcode errors. The cooldown is wired into OnTrade(): three consecutive losses with this magic trigger a 3-bar pause (15 min on M5, 3 hr on H1) before any new entry is allowed.

Entry Signal

A long fires when the bar[1] close crosses above the projected trendline value at bar[1] while the bar[2] close was at or below the line at bar[2] — a strict closed-bar break, never an intrabar tick. The trendline itself is built two ways: an inline least-squares regression across the last InpAutoTrendlineBars closed bars (50 by default, so ~4 hours of M5), or a manually drawn HLINE/OBJ_TREND chart object whose value at bar[1] sits within 1% of the recent close, with manual taking priority over auto. The signal must clear the four-state regime gate (CHOPPY is hard-blocked; STRONG_TREND needs ADX(14) ≥ 20 plus ATR(14) percentile > 0.5, WEAK_TREND needs ADX ≥ 18, RANGE is allowed but tagged), pass the H4 EMA(50) directional check, and produce an R:R above 1.5 before TryEntry() sizes the order at 0.5% risk of effective capital with a 1.5× ATR stop and a 3.0× ATR target.

Exit Signal

ManageOpenPositions() runs every tick and walks four exit paths in this order: a 200-bar time stop that closes the position outright, a regime change to CHOPPY or RANGE that does the same, a one-shot break-even at 1R that moves the stop to entry ± 1 point and only ever ratchets in the favorable direction, and a 50% partial close that fires the same tick as the break-even. After 1R, an ATR(14) × 2.0 trailing stop walks the stop in the favorable direction only via TryModify_EX18005() — every modify and close call is wrapped in a 3-retry helper that pauses 200ms on requote, timeout, price-off, or price-changed.

Stop Loss

Initial stop is ATR(14) × InpATRMultSL (default 1.5×) clamped above the broker's stops-level minimum via StopsPoints(), and ratchets to entry ± 1 point at 1R of profit (break-even). From 1R onward, the trailing stop at ATR(14) × InpTrailATRMult (default 2.0×) walks the stop in the favorable direction only — every modify retries up to 3 times on requote, timeout, or price-changed via TryModify_EX18005(), and a 200-bar time stop closes any position that lingers too long.

Take Profit

Take profit is ATR(14) × InpATRMultTP (default 3.0×), giving a 1:2 R:R against the 1.5× ATR stop. A 50% partial close fires the moment price moves 1R (PARTIAL_PCT = 50), and the remaining half is then managed by the trailing stop until either the 200-bar time stop or the full TP level is hit.

Best For

Minimum recommended balance: $100, best run on XAUUSD M5-H1 with a low-spread broker that keeps point spreads under 50 (5 pips on gold) and a server on GMT+0/+1/+2 so the 7-20 server-hour window catches the London and early New York sessions. Suited for MEDIUM-risk traders who want to combine discretionary chart levels (draw your own HLINE/OBJ_TREND and let the EA trade the first clean break) with an algorithmic regression baseline — the InpCapitalCapAmount cap and InpCapitalCapFloor of $50 make it a clean fit for prop-firm evaluation accounts where protecting a hard equity ceiling matters more than scaling up, and the 0.5% per-trade risk with a 1:2 R:R default profile is friendly to accounts that cannot tolerate a large drawdown from a single bad day.

Strategy Logic

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

Family: TrendFollow Magic: 22218005 Version: 2.00

BRIEF: Trade price crosses of trendlines — monitors manually- drawn HLINE/OBJ_TREND objects plus an inline automatic trendline (least-squares linear regression over N closed bars). Wrapped in ADX+ATR-pctile+BB-width regime gate, HTF trend confirm, spread/session/news no-trade filters, ATR-based SL/TP, break-even + partial TP + ATR trailing, capital allocation cap. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • EffCapital()
  • NormPrice()
  • NormVol()
  • DayStart()
  • RealizedToday()
  • RealizedThisWeek()
  • CopyBufSafe()
  • StopsPoints()
  • TrendlineSignal()
  • ConfirmEntry()
  • CanTradeNow()
  • CalcLots()
  • ...and 7 more

INTERNAL CONSTANTS (6 total):

  • PARTIAL_PCT = 50 // % closed at TP1
  • NEWS_WINDOW_MIN = 30 // +/- minutes around manual news time
  • SESSION_START_HOUR = 7 // broker server time
  • TRAIL_START_R = 1.0 // start trailing after 1R
  • MAX_HEAT_PCT = 6.0 // max portfolio heat %
  • REGIME_EXIT_ADX = 15 // exit if ADX falls below this

INPUT PARAMETERS (20 total across 6 groups):

  • [=== Identity ===] InpMagicNumber = 22218005 // Magic number (222 + Expert ID)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18005" // Trade comment
  • [=== Identity ===] InpDryRun = true // Dry-run (no live orders) [true]
  • [=== Identity ===] InpKillSwitch = false // Global kill switch
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk % of effective capital per trade
  • [=== 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 = 1 // Max concurrent trades (portfolio)
  • [=== Risk & Sizing ===] InpMaxSymbolExposure = 1 // Max concurrent trades on this symbol
  • [=== Risk & Sizing ===] InpCooldownAfterLosses = 3 // Cooldown after N consecutive losses (bars to wait)
  • [=== Capital Allocation Cap (mandatory) ===] InpCapitalCapAmount = 0.0 // Real-money cap (account currency)
  • [=== Capital Allocation Cap (mandatory) ===] InpCapitalCapFloor = 50.0 // Floor below which no new entries
  • [=== Signal (Trendline) ===] InpAutoTrendlineBars = 50 // Bars for inline regression trendline (0=manual only)
  • [=== Signal (Trendline) ===] InpUseManualLines = true // Also monitor chart-drawn HLINE/OBJ_TREND
  • [=== Regime / Confirm ===] InpRRMin = 1.5 // Minimum reward:risk
  • [=== Regime / Confirm ===] InpADXMinTrend = 20.0 // Min ADX to allow trend entries
  • [=== Exit / Manage ===] InpATRMultSL = 1.5 // ATR multiple for initial SL
  • [=== Exit / Manage ===] InpATRMultTP = 3.0 // ATR multiple for TP target
  • [=== Exit / Manage ===] InpTrailATRMult = 2.0 // ATR multiple for trailing stop
  • [=== Exit / Manage ===] InpBreakEvenR = 1.0 // Move to break-even after N R-multiples
Pseudocode
// Pipsgrowth EX18005 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Trade price crosses of trendlines — monitors manually- drawn HLINE/OBJ_TREND objects plus an inline automatic trendline (least-squares linear regression over N closed bars). Wrapped in ADX+ATR-pctile+BB-width regime gate, HTF trend confirm, spread/session/news no-trade filters, ATR-based SL/TP, break-even + partial TP + ATR trailing, capital allocation cap. 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
InpMagicNumber22218005Magic number (222 + Expert ID)
InpTradeComment"Psgrowth.com Expert_18005"Trade comment
InpDryRuntrueDry-run (no live orders) [true]
InpKillSwitchfalseGlobal kill switch
InpRiskPercent0.5Risk % of effective capital per trade
InpDailyLossLimitPct3.0Daily loss limit % of effective capital
InpWeeklyLossLimitPct6.0Weekly loss limit % of effective capital
InpMaxConcurrent1Max concurrent trades (portfolio)
InpMaxSymbolExposure1Max concurrent trades on this symbol
InpCooldownAfterLosses3Cooldown after N consecutive losses (bars to wait)
InpCapitalCapAmount0.0Real-money cap (account currency)
InpCapitalCapFloor50.0Floor below which no new entries
InpAutoTrendlineBars50Bars for inline regression trendline (0=manual only)
InpUseManualLinestrueAlso monitor chart-drawn HLINE/OBJ_TREND
InpRRMin1.5Minimum reward:risk
InpADXMinTrend20.0Min ADX to allow trend entries
InpATRMultSL1.5ATR multiple for initial SL
InpATRMultTP3.0ATR multiple for TP target
InpTrailATRMult2.0ATR multiple for trailing stop
InpBreakEvenR1.0Move to break-even after N R-multiples
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18005.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18005 TrendlineCrossAlert — Trendline cross EA (manual + auto regression), 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>

//--- non-input tunables (constants)
#define EA_VERSION          "2.00"
#define ATR_PERIOD          14
#define ADX_PERIOD          14
#define BB_PERIOD           20
#define BB_DEVIATION        2.0
#define SLOPE_BARS          5
#define MAX_BARS_IN_TRADE   200
#define PARTIAL_PCT         50      // % closed at TP1
#define HTF_TIMEFRAME       PERIOD_H4
#define SPREAD_AVG_BARS     50
#define SLIPPAGE_POINTS     20
#define NEWS_WINDOW_MIN     30      // +/- minutes around manual news time
#define SESSION_START_HOUR  7       // broker server time
#define SESSION_END_HOUR    20
#define TRAIL_START_R       1.0     // start trailing after 1R
#define MAX_HEAT_PCT        6.0     // max portfolio heat %
#define REGIME_EXIT_ADX     15      // exit if ADX falls below this

//==================================================================
//                          INPUTS (21)
//==================================================================
input group "=== Identity ==="
input long             InpMagicNumber       = 22218005;                 // Magic number (222 + Expert ID)
input string           InpTradeComment      = "Psgrowth.com Expert_18005";  // Trade comment
input bool             InpDryRun            = true;                    // Dry-run (no live orders) [true]
input bool             InpKillSwitch        = false;                   // Global kill switch

input group "=== Risk & Sizing ==="
input double           InpRiskPercent       = 0.5;                     // Risk % of effective capital per trade
input double           InpDailyLossLimitPct = 3.0;                     // Daily loss limit % of effective capital
input double           InpWeeklyLossLimitPct= 6.0;                     // Weekly loss limit % of effective capital
input int              InpMaxConcurrent     = 1;                       // Max concurrent trades (portfolio)
input int              InpMaxSymbolExposure = 1;                       // Max concurrent trades on this symbol
input int              InpCooldownAfterLosses = 3;                     // Cooldown after N consecutive losses (bars to wait)

input group "=== Capital Allocation Cap (mandatory) ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable                   // Enable real-money equity cap
input double           InpCapitalCapAmount  = 0.0;                   // Real-money cap (account currency)
input double           InpCapitalCapFloor   = 50.0;                    // Floor below which no new entries

input group "=== Signal (Trendline) ==="
input int              InpAutoTrendlineBars = 50;                      // Bars for inline regression trendline (0=manual only)
input bool             InpUseManualLines    = true;                    // Also monitor chart-drawn HLINE/OBJ_TREND

input group "=== Regime / Confirm ==="
input double           InpRRMin             = 1.5;                     // Minimum reward:risk

Full source code available on download

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

Tags:ex18005trendfollowpipsgrowthfreemt5xauusd

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