Pipsgrowth EX16043 Trend
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX16043 Lock_Profit — Lock profit trailing EA, full 12-layer stack.
Overview
Pipsgrowth EX16043 Lock Profit is a position-management utility, not a strategy EA. It never opens trades. Its job is narrower and more focused than the other files in the EX16 family: every tick it walks the open positions on the account, filters for the ones tagged with magic number 22216043, and progressively ratchets the stop-loss on each one to lock in realized profit. The header file claims a '12-layer stack' spanning REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, and OnTester, but in practice the only layer that does any work is MANAGE — the trailing-stop engine — and the closest thing to a NO-TRADE gate is the magic-number filter that decides which positions this EA is willing to touch. There are zero indicator handles, no OnInit-time IndicatorCreate calls, no arrays of MQL5 indicator buffers, and no OnTester. This file is a tool you attach to a chart, not a system that decides when to enter.
The trailing engine is built around four numeric inputs. InitialTriggerValue=20 is the profit threshold that has to be crossed before the EA does anything at all. InitialSLValue=9 is the first amount of profit it locks in once the trigger fires. StepTriggerValue=20 is how much additional profit is needed for the next ratchet, and StepSLIncrement=9 is how much additional profit gets locked at that ratchet. So with the defaults, on a long trade the EA waits for 20 units of profit, then moves the stop to entry+9; when profit hits 40 units, the stop moves to entry+18; at 60 units, entry+27; and so on, climbing by 9 units every 20 units of additional profit. The level number outProfitLevel = 1 + floor((profit - 20) / 20) is what the panel displays, and the EA also records the last level per position in a long array (lastTrailLevels) so it only fires a PositionModify when the level has actually increased.
The units in those four numbers depend on TrailMode, an enum with three values. TRAIL_BY_POINTS treats one unit as one SymbolInfoDouble(SYMBOL_POINT), so on a 5-digit gold broker 20 points equals 2.0 pips. TRAIL_BY_PIPS multiplies by point*10 to get the conventional 1-pip = 10-points relationship, so 20 pips means 200 points. TRAIL_BY_PROFIT_USD, which is the default, treats the numbers as dollars of floating P&L, and the EA converts dollar amounts into a price offset through the broker's tickValue, contractSize, and tickSize fields — the same math the broker uses to mark positions to market. That last mode is the only one that genuinely works across symbols with different contract specs, since the EA reads tickValue at modify-time and re-computes the price offset from scratch every call.
CalculateNewSL is the function that does the math. It pulls the position's entry price, current price, lots, and floating P&L out of PositionGetDouble, calls ConvertPriceToValue to normalize the profit into the mode's unit, compares it against InitialTriggerValue, and returns 0 if the trigger hasn't been crossed yet. If it has, it computes the level, multiplies the locked-profit value by the level ramp, and calls ConvertToPriceOffset to turn that into a price delta from the entry. The check at line 412 honors SYMBOL_TRADE_STOPS_LEVEL — the broker's minimum stop distance — but only logs a warning if the calculated SL is too close, it does not actually reject the trade; that responsibility falls through to the broker's own order-validation and either succeeds or returns an error code through TryModify_EX16043. The function also has commented-out MathMin/MathMax clamps (lines 402, 408) that would have enforced the stop-level strictly, but they're disabled in the current build.
The trailing direction is one-way. For a buy, the new stop must be higher than the entry price AND higher than the current stop (or the current stop must be zero, which is treated as 'no stop yet'). For a sell, the stop must be lower than the entry AND lower than the current stop. There is no path in the source that loosens a stop — the only PositionModify calls that fire are moves that lock in more profit. That property is what makes the EA genuinely a 'lock profit' tool and not a generic stop-chaser.
The chart panel is built by BuildPanelText but, at least in this build, it isn't actually shown. OnTick has the line string currentPanelText = "HELLO LIVE CHART"; instead of the real BuildPanelText() call, and a 1-second OnTimer prints "HELLO LIVE CHART - Timer". The full panel logic exists in the source — it lists every matching position with its ticket, direction, lots, profit, current SL, locked level, and distance to the next ratchet — but the wiring is incomplete. If you want to see the panel, uncomment those two lines. The logging is real, though: LogAction writes to a 20-entry ring buffer actionLog that the panel would display, and prints to the terminal journal if EnableDebugPrints is true (the default).
At the bottom of the file are three retry helpers — TryClose_EX16043, TryClosePartial_EX16043, and TryModify_EX16043 — that wrap trade.PositionClose, trade.PositionClosePartial, and trade.PositionModify in a 3-attempt loop that retries on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED. Only TryModify_EX16043 is actually wired in: ProcessTrailingSL calls it on line 224 to push the new SL. The two close helpers are unused dead code. ErrorDescription is a 35-entry switch that maps MQL5 trade error codes to human-readable strings, also currently unused by the live path.
The header lists the EA as 'portable' across FX Majors, Gold/Metals, with a suggested timeframe of M5 (also works on H1). That's accurate given the design — there is nothing symbol-specific or timeframe-specific in the logic — but because the EA doesn't gate by session or by weekday, you should run it on the same chart where the original entry was placed, or on a chart that has visibility into the same account's positions. The minimum recommended balance in the database is $100, which is realistic for a utility: this EA doesn't allocate margin, it only modifies SLs, so its capital footprint is whatever the opening EA decided on.
What to expect in backtest: the Strategy Tester will load this file, the OnInit will succeed, but the OnTester and no trade-execution paths will produce almost no tester activity — there are no entries, no exits by this EA, and the trailing logic only fires on positions that exist on the account. In live or demo use, the value is real: drop this EA on a chart that already has open trades with magic 22216043 (or change InpMagicNumber to match your strategy's magic), set the four knobs to your preferred scale, and the SL on each trade will march into profit according to the ladder.
Strategy Deep Dive
Each tick, OnTick calls ProcessTrailingSL which iterates PositionsTotal() and selects only positions where POSITION_MAGIC == 22216043, resizing the long lastTrailLevels array if needed. For each match it pulls entry, current price, lots, and floating P&L out of PositionGetDouble, then calls CalculateNewSL which either returns 0 (profit below the trigger) or returns entry ± a price offset derived from (9 + (level-1)9) units of profit converted via ConvertToPriceOffset — point10 for pips, point for points, or tickValuecontractSize/tickSize math for USD. The new SL is sent only if it sits further into profit than the current one; the function honors SYMBOL_TRADE_STOPS_LEVEL by logging a warning rather than rejecting. LogAction pushes every event into a 20-entry ring buffer and (if EnableDebugPrints) the journal, and OnTick is supposed to refresh a chart panel built by BuildPanelText — though the live code currently substitutes a placeholder string. Three Try retry helpers wrap PositionClose, PositionClosePartial, and PositionModify with 3 attempts on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED, of which only TryModify_EX16043 is wired in.
This EA does not generate entries. It is a position-management utility that walks PositionsTotal() each tick, filters for trades where POSITION_MAGIC equals the configurable InpMagicNumber (default 22216043), and adjusts the stop-loss on each match. To use it, attach it to a chart that already hosts positions opened by another strategy EA, a manual trader, or a copier, all tagged with this magic number.
ProcessTrailingSL runs every tick and only ever tightens the stop. It computes outProfitLevel = 1 + floor((normalizedProfit - InitialTriggerValue) / StepTriggerValue) and sends the new SL via TryModify_EX16043, leaving the position's take-profit unchanged. The function returns 0 — and no modify fires — if position profit has not yet crossed InitialTriggerValue, so the original stop-loss (or zero) remains in place until then.
There is no fixed per-trade SL input — this EA assumes another system placed the original stop or left it at zero. Its job is to replace that SL with a 'locked' level at entry ± (InitialSLValue + (level-1) * StepSLIncrement) units (default 9 + (level-1)*9) once profit crosses InitialTriggerValue=20. The new SL is only ever moved in the profitable direction; if the calculated value is not strictly better than the current stop, no modify is sent.
The EA does not touch the take-profit. When calling PositionModify, it reads PositionGetDouble(POSITION_TP) and passes the existing TP through unchanged. The profit target from the original opening trade — set by whichever EA or trader placed the order — remains the only TP this code respects.
Minimum recommended balance: $100 on any ECN or standard account, since this EA only modifies SLs and does not allocate margin. Best deployed as a companion on XAUUSD M5 (or H1), EURUSD, GBPUSD, or any Gold/Metals symbol listed as portable in the source header, attached to the same chart where the opening EA runs. The trailing engine has no session or weekday filter, so leave it running 24/5 and the magic-number gate (22216043) ensures it only touches positions you intend. This is a stop-loss tool, not a turnkey system — pair it with a separate strategy EA or manual entries tagged with the same magic.
Strategy Logic
Pipsgrowth EX16043 Trend — Strategy Logic Analysis (from .mq5 source)
Family: Trend
Magic: 22216043
Version: 2.00
BRIEF:
Lock Profit trailing EA that manages open positions by progressively moving the stop-loss to lock in profit. Supports trailing by points, pips, or USD, with configurable trigger and step increments and a chart info panel. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
OnTimer()ProcessTrailingSL()BuildPanelText()DrawPanel()DeletePanel()CalculateNewSL()ConvertToPriceOffset()ConvertPriceToValue()LogAction()GetTrailModeString()GetTrailModeUnit()ErrorDescription()- ...and 3 more
INTERNAL CONSTANTS (2 total):
MAX_LOG_ENTRIES= 20 //MOVEDTOGLOBALSCOPEMAX_LOG_ENTRIES= 20 //MOVEDTOGLOBAL
INPUT PARAMETERS (9 total across 3 groups):
- [=== Trailing Settings ===]
InitialTriggerValue= 20 // Initial profit to activate trailing (Points/Pips/USD) - [=== Trailing Settings ===]
InitialSLValue= 9 // First locked profit amount (Points/Pips/USD) - [=== Trailing Settings ===]
StepTriggerValue= 20 // Additional profit needed for next SL move - [=== Trailing Settings ===]
StepSLIncrement= 9 // How much to move SL at each step - [=== Display ===]
EnableDebugPrints=true//Printdebug messages to journal - [=== Display ===]
EnablePanelDisplay=true// Show info panel on chart - [=== Display ===]
PanelTextColor=clrWhite// Panel text color - [=== Identity ===]
InpMagicNumber=22216043// MagicNumber(positions to manage) - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_16043" // TradeComment
// Pipsgrowth EX16043 Trend — Execution Flow (from source analysis)
// Family: Trend
// Lock Profit trailing EA that manages open positions by progressively moving the stop-loss to lock in profit. Supports trailing by points, pips, or USD, with configurable trigger and step increments and a chart info panel. 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 |
|---|---|---|
| InitialTriggerValue | 20 | Initial profit to activate trailing (Points/Pips/USD) |
| InitialSLValue | 9 | First locked profit amount (Points/Pips/USD) |
| StepTriggerValue | 20 | Additional profit needed for next SL move |
| StepSLIncrement | 9 | How much to move SL at each step |
| EnableDebugPrints | true | Print debug messages to journal |
| EnablePanelDisplay | true | Show info panel on chart |
| PanelTextColor | clrWhite | Panel text color |
| InpMagicNumber | 22216043 | Magic Number (positions to manage) |
| InpTradeComment | "Psgrowth.com Expert_16043" | Trade Comment |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX16043 Lock_Profit — Lock profit trailing EA, full 12-layer stack."
#include <Trade/Trade.mqh>
#define MAX_LOG_ENTRIES 20 // MOVED TO GLOBAL SCOPE
//--- Inputs
enum ENUM_SL_TRAIL_MODE
{
TRAIL_BY_POINTS = 0,
TRAIL_BY_PIPS,
TRAIL_BY_PROFIT_USD
};
input group "=== Trailing Settings ==="
input ENUM_SL_TRAIL_MODE TrailMode = TRAIL_BY_PROFIT_USD;
input double InitialTriggerValue = 20; // Initial profit to activate trailing (Points/Pips/USD)
input double InitialSLValue = 9; // First locked profit amount (Points/Pips/USD)
input double StepTriggerValue = 20; // Additional profit needed for next SL move
input double StepSLIncrement = 9; // How much to move SL at each step
input group "=== Display ==="
input bool EnableDebugPrints = true; // Print debug messages to journal
input bool EnablePanelDisplay = true; // Show info panel on chart
input color PanelTextColor = clrWhite; // Panel text color
input group "=== Identity ==="
input ulong InpMagicNumber = 22216043; // Magic Number (positions to manage)
input string InpTradeComment = "Psgrowth.com Expert_16043"; // Trade Comment
//--- Global
CTrade trade;
#define PANEL_OBJ_NAME "LockProfitPanel_EA" // Added _EA to make it more unique
string lastPanelText = ""; // Stores the last text drawn to optimize panel updates
long lastTrailLevels[]; // Dynamically sized array for ticket-indexed profit levels
string actionLog[MAX_LOG_ENTRIES]; // MOVED DECLARATION HERE AFTER MAX_LOG_ENTRIES IS DEFINED
int logIndex = 0; // MOVED DECLARATION HERE
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize trade object (optional, defaults are usually fine)
trade.SetExpertMagicNumber((long)InpMagicNumber); // identify this EA when modifying positions
// trade.SetDeviationInPoints(10);
ArrayResize(lastTrailLevels, 0); // Start with an empty array
DeletePanel(); // Clean up any old panel objects
LogAction("[INFO] Lock Profit EA initialized - Mode: " + GetTrailModeString(TrailMode));
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
DeletePanel();
LogAction("[INFO] Lock Profit EA stopped. Reason: " + IntegerToString(reason));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.