Function library for maintaining positions with a simple trailing stop – library MetaTrader 4

With the help of this library it is possible to implement the ability to maintain positions with a simple trailing stop in any Expert Advisor. This library is universal and is designed to be able to connect to virtually any EA using the #include compiler directive and granting the EA the ability to maintain positions with a simple trailing stop.


In order to connect the library to an EA it is necessary to make the following changes:

1. Insert the compiler directive before the declaration of functions:

#include <a-SimpleTrailing.mqh>

2. Declare the global variables:

color clModifyBuy = Aqua;    // Color of Buy modification icon
color clModifySell = Tomato; // Color of Sell modification icon

3. Declare the external parameters:

// Use sound signals during the execution of trades
extern bool   UseSound        = True; 
extern string NameFileSound   = "expert.wav"; // Name of the sound file
extern int    NumberOfTry     = 3;  // Number of trade attempts on errors 
extern int    PauseAfterError = 75; // Pause between trade attempts in seconds

4. Insert the line at the end of the start() function:

if(UseTrailing) 
    TrailingPositions();

5. Place the library file a-SimpleTrailing.mqh into the terminal folder …\experts\include\

Once the library is connected, the EA will have the following external parameters:

Alternative:  iStochKomposterAlert - indicator MetaTrader 5
// Use trailing stop. If 'False', the trailing stop is disabled.
UseTrailing = True;
// Trail only profit. If 'False', then the trailing stop will start 
// working in the unprofitable zone.
ProfitTrailing = True; 
TrailingStopBuy = 50;  // Trailing stop size for Buy orders.
TrailingStopSell = 50; // Trailing stop size for Sell orders.
TrailingStep = 5;      // Trailing step.
The TrailingPositions() function can take on the following parameters:

– symbol name (“” – current symbol);
– operation (-1 – any position, 0 – Buy, 1 – Sell);
– MagicNumber (-1 – any magic number).

This allows to narrow the scope of the trailing stop operation. For example, trail only Euro:

if(UseTrailing) 
    TrailingPositions("EURUSD");

Or trail only Pound Sells:

if(UseTrailing) 
    TrailingPositions("GBPUSD", OP_SELL);

And if the EA uses a magic number, then it must be passed to the maintenance function:

if(UseTrailing) 
    TrailingPositions("", -1, MAGIC);


📈 ROBOTFX MetaTrader Expert Advisors and Indicators to maximize profits and minimize the risks