Pipsgrowth EX16044 Trend
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX16044 MA_Trend_2 — MA trend-following EA, full 12-layer stack.
Overview
Pipsgrowth EX16044 Trend is a single-indicator trend-following EA that trades in the direction of one Linear Weighted Moving Average. Everything else in the source — the risk manager, the trailing stop, the close-opposite switch, the only-one-position lock — is a wrapper around the central question this EA asks on every fresh bar: is the current Ask above or below the value of the LWMA one bar ago? When Ask > ma[1], the EA sets m_need_open_buy = true; when Bid < ma[1], m_need_open_sell = true. The MA is read from a single iMA handle (handle_iMA) built once in OnInit, configured by Inp_MA_period, Inp_MA_ma_period (default 12), Inp_MA_ma_shift (default 3), Inp_MA_ma_method = MODE_LWMA, and Inp_MA_applied_price mapped to PRICE_WEIGHTED through the MapAppliedPriceInt helper. The MA is built on a separately configurable timeframe (Inp_MA_period is the trader-facing code 0–7, decoded by MapTimeframeInt to M1, M5, M15, M30, H1, H4, or D1, with code 0 defaulting to H1), so the chart timeframe the EA runs on and the timeframe the MA evaluates can be decoupled — an M5 chart can take its signal from an H1 LWMA, which is the entire point of the design.
The signal evaluation is locked to a new-bar tick only. OnTick starts with the transaction state machine (m_waiting_transaction + m_waiting_order_ticket + m_transaction_confirmed), processes any pending open leg with the OnlyOne/CloseOpposite logic, and only then checks the time_0 == PrevBars guard. When a new bar opens, RefreshRates() is called, FreezeStopsLevels computes a 1.1×-of-broker-freeze/stops buffer, Trailing() runs, iGetArray pulls three values from the iMA buffer (ma[0], ma[1], ma[2]), and the comparison fires. ma[1] is the value the LWMA had at the close of the just-completed bar — using ma[1] rather than ma[0] means the signal is based on the previous bar's MA, not the value still being painted during the in-progress bar. That single decision is what makes the EA's entries a closed-bar system rather than a live-tick system.
Risk and trade construction is delegated to OpenPosition, OpenBuy, and OpenSell. When IntLotOrRisk == risk, the source instantiates a CMoneyFixedMargin object in OnInit, calls m_money.Percent(InpVolumeLorOrRisk) — default 3.0% of free margin — and then asks m_money.CheckOpenLong / CheckOpenShort to compute a position size that risks exactly that fraction on the InpStopLoss distance. When IntLotOrRisk == lot, the EA sends a flat InpVolumeLorOrRisk lots regardless of stop distance. The size is checked against the symbol's LotsLimit (a hard broker cap), validated through FreeMarginCheck > MarginCheck, and only then sent through m_trade.Buy / m_trade.Sell with the SL and TP prices computed in OpenPosition. The freeze-and-stops level guard in FreezeStopsLevels bumps the SL inward to price±level and the TP outward to price±level if the configured InpStopLoss / InpTakeProfit would violate the broker's minimum distance — a real safety feature on symbols with non-zero SYMBOL_TRADE_STOPS_LEVEL.
Trailing runs on every tick after the new-bar pass, not on bar close. The Trailing() loop walks all positions on the symbol with the EA's magic and, for each BUY, only ratchets the SL up (never down) when the current price has moved more than ExtTrailingStop + ExtTrailingStep past entry and the existing SL is still below the new target. For each SELL, the same ratchet runs in the mirror direction. ExtTrailingStop is the InpTrailingStop input scaled by m_adjusted_point (which is point × 10 on 3- and 5-digit symbols, point × 1 on 2- and 4-digit symbols), and ExtTrailingStep is the same scaling applied to InpTrailingStep. The actual broker-side modification is done by TryModify_EX16044, a 3-attempt retry helper that re-fires on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, TRADE_RETCODE_PRICE_OFF, or TRADE_RETCODE_PRICE_CHANGED with a 100 ms sleep between attempts. Two near-twin helpers, TryClose_EX16044 and TryClosePartial_EX16044, wrap the same retry discipline around position-close calls (200 ms sleep) but are only invoked from the ClosePositions path when InpCloseOpposite is enabled. All three helpers are defined at the end of the file; in the live open path, the bare m_trade.Buy / m_trade.Sell is used directly because the order-confirmation logic lives in OnTradeTransaction instead.
Three operating-mode switches are exposed under the Trading Options group. InpTypeTraiding selects buy-only, sell-only, or both directions. InpOnlyOne = true turns the EA into a one-position-at-a-time system: when m_need_open_buy fires and an opposite position exists, the EA opens a buy only if count_buys+count_sells == 0; if anything is open, m_need_open_buy is reset and no new order is sent. InpCloseOpposite = true, when combined with the open signal, calls ClosePositions on the opposite side before opening the new one. InpReverse flips the signal — buy when price is below the MA, sell when above — turning the trend follower into a contrarian. None of these flags are visible in the live comparison unless they are turned on; the default InpTypeTraiding = buy_sell, InpOnlyOne = false, InpCloseOpposite = false, InpReverse = false is a pure two-direction trend follower that will pyramid in the direction of the LWMA.
OnTester is not present in the source — there is no custom OnTester function, so the strategy tester will use the standard trade-statistics generator. There is no global drawdown cap, no equity-curve stop, no daily-loss limiter, and no news filter; the only money-management boundary is the CMoneyFixedMargin percent-per-trade sizing and the broker's LotsLimit. The order confirmation flow is the closest thing to a capital guard: m_need_open_buy / m_need_open_sell are gated by m_waiting_transaction, which is set to true the moment an OrderSend is acknowledged by the trade server (ResultRetcode == 10009), and only released when OnTradeTransaction receives a DEAL_ADD transaction matching the expected m_waiting_order_ticket. That handshake prevents the EA from firing a second open-order call before the first one has been confirmed as a deal.
What the backtest looks like in practice: the EA will produce long, slow trending runs in the direction of the LWMA and choppy, mean-reverting losses in ranging conditions. The default 50/140 SL/TP pair on H1 is roughly 5/14 pips on a 5-digit gold quote (5-point and 14-point if m_adjusted_point is point×10), which gives a 1:2.8 reward-to-risk ratio per trade. With the trailing stop disabled (InpTrailingStop = 0), exits are entirely SL/TP-driven. With trailing on at 15/5, the EA will lock profits on the first move past 20 pips in the favorable direction and continue ratcheting every 5 additional pips. A session filter is not present — the EA will open on the open of any timeframe bar regardless of the broker's local time, so traders who want London- or New-York-only behavior need to schedule the chart accordingly or add an external session guard. Pair is set by the chart symbol; the EA's logic is pair-agnostic and works on FX majors, gold, and other instruments provided the symbol's minimum lot, lot step, freeze, and stops levels are broker-defined.
Strategy Deep Dive
The EA instantiates a single iMA indicator in OnInit with the trader's timeframe code routed through MapTimeframeInt, then sits idle in OnTick until a new bar opens. The new-bar guard (PrevBars vs time_0) suppresses all signal logic on in-progress bars; on bar close, the iGetArray helper pulls three MA values, the close-based ma[1] is compared to current Ask and Bid, and a directional flag is raised. The order is then staged through the m_need_open_buy / m_need_open_sell + m_waiting_transaction handshake so that only one OrderSend can be in flight at a time, with OnTradeTransaction releasing the gate when the broker confirms the deal. Every tick — including ticks where no signal is generated — Trailing() walks the EA's open positions and ratchets the SL when the favorable move exceeds the trailing distance plus step, with the actual broker-side modification wrapped in a 3-attempt retry helper that recovers from requotes and timeouts.
Each new bar on the chart timeframe, the EA reads the LWMA value at the previous bar (ma[1]) and compares it to the current Ask and Bid. If Ask > ma[1] the EA sets m_need_open_buy = true; if Bid < ma[1] it sets m_need_open_sell = true. The MA is computed on a separately configurable timeframe (default H1) and uses the LWMA smoothing method with default period 12, shift 3, and PRICE_WEIGHTED applied price.
Exits are SL/TP driven by default, with an optional ratcheting trailing stop. Once a position is in profit by more than InpTrailingStop + InpTrailingStep pips (default 15 + 5 = 20 pips), Trailing() ratchets the SL up by 5-pip steps on every favorable tick. When InpCloseOpposite is enabled and a new signal fires against the current position, ClosePositions flattens the existing position first before opening the new one.
InpStopLoss defaults to 50 pips, applied at order open via m_trade.Buy / m_trade.Sell and visible in the OpenPosition function as price ± ExtStopLoss. FreezeStopsLevels bumps the SL inward to the broker's minimum distance if the configured distance is below SYMBOL_TRADE_STOPS_LEVEL × 1.1.
InpTakeProfit defaults to 140 pips, giving roughly a 1:2.8 reward-to-risk ratio against the 50-pip SL. The TP is sent on the original order rather than attached after fill, and FreezeStopsLevels pushes the TP outward to the broker's minimum distance if needed.
Run this on a $100+ account on XAUUSD M5 (or H1), with the default H1 LWMA(12) shift-3 weighted price feeding signals. The 50/140 pip SL/TP pair needs a low-spread ECN or RAW broker on gold; a 3-pip spread on a 5-digit quote is roughly half the SL distance and will erode the 1:2.8 RR quickly on M5. Use InpTypeTraiding = buy-only or sell-only if you want to keep the EA out of one direction entirely, and pair the EA with a London- or New-York-session filter at the chart level if you want to avoid the Asian session's MA chops.
Strategy Logic
Pipsgrowth EX16044 Trend — Strategy Logic Analysis (from .mq5 source)
Family: Trend
Magic: 22216044
Version: 2.00
BRIEF:
MA Trend 2 EA trades in the direction of a moving average crossover. Uses LWMA on configurable timeframe with SL, TP, trailing stop, and risk-based or fixed lot money management. Supports buy-only, sell-only, or both directions. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
OnTradeTransaction()RefreshRates()CheckVolumeValue()FreezeStopsLevels()OpenPosition()OpenBuy()OpenSell()PrintResultTrade()iGetArray()Trailing()PrintResultModify()ClosePositions()- ...and 4 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (18 total across 5 groups):
- [=== Stop & Trailing ===]
InpStopLoss= 50 // Stop Loss, in pips (1.00045-1.00055=1 pips) - [=== Stop & Trailing ===]
InpTakeProfit= 140 // Take Profit, in pips (1.00045-1.00055=1 pips) - [=== Stop & Trailing ===]
InpTrailingStop= 15 // TrailingStop(min distance from price to Stop Loss, in pips - [=== Stop & Trailing ===]
InpTrailingStep= 5 // Trailing Step, in pips (1.00045-1.00055=1 pips) - [=== Money Management ===]
IntLotOrRisk= risk // Money management: Lot OR Risk - [=== Money Management ===]
InpVolumeLorOrRisk=3.0// The value for "Money management" - [=== MA Settings ===] Inp_MA_period = 0 //
Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // MA: timeframe - [=== MA Settings ===] Inp_MA_ma_period = 12 // MA: averaging period
- [=== MA Settings ===] Inp_MA_ma_shift = 3 // MA: horizontal shift
- [=== MA Settings ===] Inp_MA_ma_method =
MODE_LWMA// MA: smoothing type - [=== MA Settings ===] Inp_MA_applied_price = 7 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // MA: type of price
- [=== Trading Options ===]
InpTypeTraiding=buy_sell// Type traiding - [=== Trading Options ===]
InpOnlyOne=false// Only one positions - [=== Trading Options ===]
InpReverse=false// Reverse - [=== Trading Options ===]
InpCloseOpposite=false// Close opposite - [=== Trading Options ===]
InpPrintLog=false//Printlog - [=== Identity ===]
InpMagicNumber=22216044// Magic Number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_16044" // TradeComment
// Pipsgrowth EX16044 Trend — Execution Flow (from source analysis)
// Family: Trend
// MA Trend 2 EA trades in the direction of a moving average crossover. Uses LWMA on configurable timeframe with SL, TP, trailing stop, and risk-based or fixed lot money management. Supports buy-only, sell-only, or both directions. 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 |
|---|---|---|
| InpStopLoss | 50 | Stop Loss, in pips (1.00045-1.00055=1 pips) |
| InpTakeProfit | 140 | Take Profit, in pips (1.00045-1.00055=1 pips) |
| InpTrailingStop | 15 | Trailing Stop (min distance from price to Stop Loss, in pips |
| InpTrailingStep | 5 | Trailing Step, in pips (1.00045-1.00055=1 pips) |
| IntLotOrRisk | risk | Money management: Lot OR Risk |
| InpVolumeLorOrRisk | 3.0 | The value for "Money management" |
| Inp_MA_period | 0 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // MA: timeframe |
| Inp_MA_ma_period | 12 | MA: averaging period |
| Inp_MA_ma_shift | 3 | MA: horizontal shift |
| Inp_MA_ma_method | MODE_LWMA | MA: smoothing type |
| Inp_MA_applied_price | 7 | Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // MA: type of price |
| InpTypeTraiding | buy_sell | Type traiding |
| InpOnlyOne | false | Only one positions |
| InpReverse | false | Reverse |
| InpCloseOpposite | false | Close opposite |
| InpPrintLog | false | Print log |
| InpMagicNumber | 22216044 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_16044" | Trade Comment |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX16044 MA_Trend_2 — MA trend-following EA, full 12-layer stack."
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\DealInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Expert\Money\MoneyFixedMargin.mqh>
CPositionInfo m_position; // trade position object
CTrade m_trade; // trading object
CSymbolInfo m_symbol; // symbol info object
CAccountInfo m_account; // account info wrapper
CDealInfo m_deal; // deals object
COrderInfo m_order; // pending orders object
CMoneyFixedMargin *m_money;
//+------------------------------------------------------------------+
//| Enum Lor or Risk |
//+------------------------------------------------------------------+
enum ENUM_LOT_OR_RISK
{
lot=0, // Constant lot
risk=1, // Risk in percent for a deal
};
//+------------------------------------------------------------------+
//| Enum Type Traiding |
//+------------------------------------------------------------------+
enum ENUM_TYPE_TRADING
{
buy = 0, // Only BUY
sell = 1, // Only SELL
buy_sell = 2, // BUY and SELL
};
//--- input parameters
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_APPLIED_PRICE MapAppliedPriceInt(int ap)
{
switch(ap)
{
case 1: return PRICE_CLOSE;
case 2: return PRICE_OPEN;
case 3: return PRICE_HIGH;
case 4: return PRICE_LOW;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.