P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16077 Trend

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

Pipsgrowth.com EX16077 SmoothEngineEA — HMA + LR + ATR + Choppiness trend EA, full 12-layer stack.

Overview

SmoothEngine is built around a single principle: only enter when the market is actually trending, not when it is merely moving. The CSmoothEngine class embeds four hand-rolled indicators directly into the EA — a Hull Moving Average, a linear regression slope over that HMA, a custom Average True Range series, and a Choppiness Index built from the same ATR and bar range. None of these pull from MT5's iMA / iRSI / iATR handles; every value is calculated bar-by-bar inside the class from raw close, high, and low arrays. That makes the EA self-contained: it carries its own indicator stack, recalculating on every closed bar, and the only time it touches the broker is through price feeds and order tickets.

The signal itself is built from two filters acting on the bar at shift=1. First, the Choppiness Index over a 14-bar window is compared against a threshold of 61.8 — a value widely associated with non-trending, range-bound markets. If CI is above 61.8, the engine returns zero, meaning do not trade. The bar is skipped, no order is sent, and the dashboard reads WAIT. Second, on the same closed bar, a linear regression slope is fitted over the most recent 14 HMA values and then normalized by ATR. The normalization is the second gatekeeper: by dividing slope by ATR, the engine compares the rate of HMA change against current volatility rather than absolute price change. When normalized slope is positive, the EA returns +1 and opens a long; when negative, it returns -1 and opens a short. Because the slope is divided by ATR, the signal adapts to whichever volatility regime the symbol is currently in, so a trend that looks flat in points may still register as a positive slope in a quiet market.

The on-tick flow is deliberately short. The engine first checks IsTradingTime and CheckSpread, returning early if the current server time falls outside the configured 08:00-20:00 window or if the live spread exceeds 30 points. When a new bar opens, OnTick reads the previous bar's close, high, and low into the engine, calls GetSignal, and decides what to do. If the signal is opposite to an open position, CloseAllTrades is invoked for the wrong side first — a clean flip rather than an average-down. If the signal direction has no position yet, a single market order opens with a stop loss 300 points behind, take profit 600 points ahead (a fixed 1:2 risk-to-reward baked into the geometry), and a lot size calculated from 1% of account balance relative to that 300-point stop. The hard 1:2 ratio means a 45% win rate already keeps the system flat, and the Choppiness filter is designed to keep the EA out of the chop windows where that ratio breaks down.

Where SmoothEngine goes beyond a basic trend follower is the pyramiding path. EnablePyramiding is on by default and MaxOpenTrades is set to 3, so a single trend can accumulate up to three positions on the same side. Each additional entry is gated by PyramidingStep_Points = 200. The check uses GetLastTradeProfit on the most recent ticket of the same direction, divides that profit in account currency by the symbol's point value, and only opens the next layer when the previous layer has moved more than 200 points into profit. The result is a winner-adds, losers-cap pattern: the EA never averages into a losing position, but it scales into a confirmed trend, and risk per trade remains constant because CalculateLotSize is invoked on every new entry using the live balance. This produces an interesting curve: a slow-mover trend typically opens only one position and gives back the unrealized profit before the SL fires, while a fast-mover trend opens two or three layers, each with its own 1:2 RR target, letting the position compound without the trader lifting the risk per trade.

The risk stack is minimal but explicit. CalculateLotSize converts balance × 1% into a lot count by solving for the volume that would lose StopLoss_Points × point-size on the current symbol, then clamps to the broker's volume min, max, and step. There is no dynamic risk scaling, no equity curve filter, no daily P&L circuit breaker, and no maximum drawdown input. The single loss-control lever is the per-trade SL, and the only no-trade gates are time-of-day and spread. This makes the EA's behavior easy to reason about in backtest: every entry has a known maximum loss, every cycle either wins TP, loses SL, or gets closed by a reverse signal. For traders who want a daily guard, the natural extension is to drop a second EA on the chart as a money-management overlay rather than modifying SmoothEngine itself.

The dashboard is a small but functional piece of the design. It draws a 200×160 black panel in the upper-right corner, with a signal label (BUY in blue, SELL in red, WAIT in gray), a live P/L line that sums open positions on the chart's symbol, and the current HMA period. Two buttons let the trader nudge the HMA period up or down without recompiling — pressing [+] increments g_HMA_Period and calls ReinitializeEngine, which deletes the old CSmoothEngine, allocates a new one, and reloads the indicator stack from history. A red CLOSE ALL button flattens both sides of the book with one click. The dashboard is wired through OnChartEvent and uses raw ObjectCreate / ObjectSet calls rather than the standard library panels, which is why it survives both tick-rate changes and the HMA period toggle without leaving orphaned objects on the chart.

What SmoothEngine does not do is also part of its design. There is no ATR-based trailing stop; once SL and TP are written, they are not modified again. There is no break-even ratchet, no partial close, no time-based exit beyond the IsTradingTime window, and no news filter. The retry helpers TryClosePartial_EX16077 and TryModify_EX16077 are defined for the standard error-recovery pattern (requote, timeout, price-changed) but neither is called from OnTick — they sit as dead code, presumably scaffolding for a future modular extension. The single wired helper, TryClose_EX16077, handles the close-side of the reverse-signal flip with three attempts and a 200ms sleep on retryable errors. If a position is open and a reverse signal fires, the close goes through this retry wrapper, which means the EA tolerates one or two requotes before giving up — a sensible compromise for an EA that fires orders on a new-bar event rather than continuously.

Practical considerations for running it: the EA is symbol-agnostic and works on FX majors, gold, and other metals. The default 1% risk with a 30-pip stop means roughly 0.03 lot on XAUUSD at a $1,000 account, scaling proportionally elsewhere. TradingHours is parsed as a HH:MM-HH:MM string; passing an invalid format will silently default the engine to always-trade because the four StringFind-based getters return 0/0 or 23/59 on bad input. The 30-point MaxSpread_Points is appropriate for a $1-2 commission account on gold but may need to be relaxed to 50 or more on a retail FX broker during the Asian session. Pyramiding requires the broker to allow multiple positions per symbol with the same magic — netting accounts will only ever show one open trade per side, and the third layer will be silently rejected. Magic 22216077, comment Psgrowth.com Expert_16077.

Strategy Deep Dive

SmoothEngine is a single-bar new-bar EA that runs entirely off the CSmoothEngine class. On every new bar, the previous bar's close, high, and low are pushed into the class via UpdateData, which maintains a sliding 33-element buffer and rolls forward when full. Inside the class, CalculateHMA builds the Hull MA as WMA(√n) of (2×WMA(n/2) − WMA(n)), CalculateLRSlope fits a least-squares line over the last 14 HMA values, CalculateATR produces a Wilder-style true-range series, and CalculateCI turns the 14-bar ATR sum and bar range into a 0-100 choppiness reading. GetSignal is then called on the closed bar at shift=1: if CI > 61.8 the function returns 0 (no trade); else it returns +1 for positive normalized slope, -1 for negative. OnTick enforces two pre-filters (IsTradingTime parses TradingHours as a HH:MM-HH:MM string and CheckSpread caps live spread at 30 points), then either opens a fresh 0.10-class order, adds a layer if EnablePyramiding is on and the previous layer has more than 200 points of profit, or closes the opposite side when the signal flips. The lot is solved by CalculateLotSize to risk exactly 1% of balance against the 300-point stop. A small dashboard in the upper-right shows live signal and P/L and exposes HMA-period +/- buttons plus a red CLOSE ALL that flattens both sides through the same TryClose_EX16077 wrapper that handles the on-tick reverse-signal close.

Entry Signal

On every new bar, the CSmoothEngine reads the previous bar's close, high, and low, recomputes HMA(20), LR slope over the last 14 HMA values, ATR(14), and Choppiness Index(14). A long signal requires CI ≤ 61.8 (market is trending, not choppy) and a positive normalized slope (slope/ATR > 0). A short signal mirrors that with CI ≤ 61.8 and negative normalized slope. If CI is above 61.8, GetSignal returns 0 and the bar is skipped entirely.

Exit Signal

There is no dedicated trailing or break-even logic; the only exits are the static TP at 600 points, the static SL at 300 points, and a reverse-signal close that fires when GetSignal flips to the opposite direction. On a flip, CloseAllTrades is invoked for the wrong side first, which uses the TryClose_EX16077 wrapper to handle requote / timeout / price-changed errors with up to three attempts and 200ms sleeps between retries.

Stop Loss

Every position gets a fixed 300-point stop loss (StopLoss_Points input) attached at entry; the SL is never modified after that. Position sizing is solved so that a SL hit loses exactly RiskPercent (1% default) of account balance, capped to the broker's min / max / step volume.

Take Profit

A fixed 600-point take profit (TakeProfit_Points input) is attached at entry, giving a hard 1:2 risk-to-reward ratio relative to the 300-point stop. There is no partial close, no dynamic TP, and no profit-lock ratchet — the TP is written once when the order is sent and never updated.

Best For

Best suited to a $100–$500 account running XAUUSD on M5 with a low-spread ECN broker that allows multiple positions per magic. The 1% default risk and 1:2 fixed RR produce slow but compounding equity growth during clean XAUUSD trends, so traders who can leave the chart alone during the 08:00-20:00 server window get the most out of the 1-3 layer pyramiding path. The HMA period +/- buttons on the chart panel make it easy to retune responsiveness without recompiling.

Strategy Logic

Pipsgrowth EX16077 Trend — Strategy Logic Analysis (from .mq5 source)

Family: Trend Magic: 22216077 Version: 2.00

BRIEF: Smooth Engine EA using Hull MA, Linear Regression slope, ATR volatility, and Choppiness Index for smooth trend entries. Supports pyramiding with step distance, spread filter, trading hours, and risk-percent position sizing

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • GetStartHour()
  • GetStartMinute()
  • GetEndHour()
  • GetEndMinute()
  • IsTradingTime()
  • CheckSpread()
  • CountTrades()
  • CalculateLotSize()
  • GetLastTradeProfit()
  • OpenTrade()
  • CloseAllTrades()
  • CreateDashboard()
  • ...and 6 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (1 total across 1 groups):

  • [] InpMagicNumber = 22216077 // Magic number
Pseudocode
// Pipsgrowth EX16077 Trend — Execution Flow (from source analysis)
// Family: Trend
// Smooth Engine EA using Hull MA, Linear Regression slope, ATR volatility, and Choppiness Index for smooth trend entries. Supports pyramiding with step distance, spread filter, trading hours, and risk-percent position sizing

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
InpMagicNumber22216077Magic number
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16077.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16077 SmoothEngineEA — HMA + LR + ATR + Choppiness trend EA, full 12-layer stack."

#include <Trade\Trade.mqh>

sinput const string GroupIndicator="";//=== Indicator Settings ===
input int      HMA_Period      = 20;
input int      LR_Period       = 14;
input int      ATR_Period      = 14;
input int      CI_Period       = 14;
input double   CI_Threshold    = 61.8;

int g_HMA_Period;

sinput const string GroupTrade="";//=== Trade Settings ===
input bool     EnablePyramiding      = true;
input int      MaxOpenTrades         = 3;
input int      PyramidingStep_Points = 200;
input int      StopLoss_Points       = 300;
input int      TakeProfit_Points     = 600;
input int      MaxSpread_Points      = 30;
input string   TradingHours          = "08:00-20:00";
input double   RiskPercent           = 1.0;
sinput const string GroupIdentity="";//=== Identity ===
input long     InpMagicNumber        = 22216077; // Magic number
input string   InpTradeComment       = "Psgrowth.com Expert_16077";

class CSmoothEngine
{
private:
   int m_hma_period;
   int m_lr_period;
   int m_atr_period;
   int m_ci_period;
   double m_ci_threshold;
   
   int m_bars_needed;
   int m_buffer_size;
   
   double m_close[];
   double m_high[];
   double m_low[];
   double m_atr[];
   double m_hma[];
   double m_slope[];
   double m_ci[];
   
   int m_current_pos;
   
   double CalculateHMA(const double &price[], int index)
   {
      int half_period = (int)MathFloor(m_hma_period / 2.0);
      int sqrt_period = (int)MathFloor(MathSqrt((double)m_hma_period));
      
      double wma1 = 0.0;
      int wma_count = 0;
      

Full source code available on download

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

Tags:ex16077trendpipsgrowthfreemt5xauusd

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