Discussing the article: "How to add Trailing Stop using Parabolic SAR"

 

Check out the new article: How to add Trailing Stop using Parabolic SAR.

When creating a trading strategy, we need to test a variety of protective stop options. Here is where a dynamic pulling up of the Stop Loss level following the price comes to mind. The best candidate for this is the Parabolic SAR indicator. It is difficult to think of anything simpler and visually clearer.

Trailing stop is an automatic shift of StopLoss position behind the price, allowing to constantly keep the protective stop at some distance from the price. This approach allows the trader to protect part of the accumulated profit without exiting the position prematurely. Each time the market price moves away from the position opening price, the trailing stop automatically tightens the StopLoss, maintaining the specified distance between it and the current price. However, if the price approaches the opening price, StopLoss remains at the same level. This provides protection against losses due to possible market fluctuations.

However, if you need a more specialized version of the trailing stop, you can always develop a function in MQL5 to extend the capabilities of the standard tool.

There is a program function, to which the required price is passed to set the StopLoss level. The program checks some prohibiting factors, such as the StopLevel level - the distance, closer to which stops cannot be placed, or the FreezeLevel level - the freezing distance, within which a position or pending order cannot be modified. In other words, if the price has approached the stop level of the position at a distance closer than the FreezeLevel level, then the stop order is expected to be triggered, and modification is prohibited. Trailing stops also have some individual parameter settings that are also checked before moving the stop loss level to the specified price, for example, the symbol and magic of the position. All these criteria are checked immediately before moving the StopLoss position to the specified level.

Parabolic SAR indicator perfectly serves as a "pointer" of the levels required by StopLoss.

Author: Artyom Trishkin

 
Thanks for the interesting article. Just a quick read. Got the basics down. From my phone. At home from my computer I will familiarise myself with it in more detail and use the included files in my projects by analogy - later.
 
Roman Shiredchenko projects by analogy - later.

You are welcome. There will be an article on trailing classes soon - as a logical conclusion of this topic.

They will be used, let's say, more correctly and, as to me, more conveniently.

 

Thanks for the article,

But I wish you modify this to avoid truncation errors with fp numbers:

        pos_profit_pt= int ((tick.bid - pos_open) / Point ());              // calculate the profit of the position in points 

To:

        pos_profit_pt= (int) MathRound((tick.bid - pos_open) / Point ());              // calculate the profit of the position in points 
 
The article is thorough, but it is too voluminous for a relatively small topic. Not everyone will be able to cope with it.
 
But everything is explained from start to finish... It is possible to connect other indicators for trawl, like MA for example.
 
Artyom Trishkin #:

You're welcome. There will be an article on trailing classes coming out soon - as a logical conclusion to this topic.

They will be used, let's say, more correctly and, in my opinion, more conveniently.

thank you - I have taken the examples to my robots:

//--- если не новый бар - уходим из обработчика
   if(!IsNewBar())
      return;
и 
//--- устанавливаем в объект торгового класса магический номер
   ExtTrade.SetExpertMagicNumber(InpMagic);

 

I'm looking at such a topic myself....

//+------------------------------------------------------------------+
//| Manage Open Positions: Trailing Stop   |
//+------------------------------------------------------------------+
void ManageOpenPositions(string Sym, int mn)
  {
   if(TrailingStop > 0)
    for(int i = 0; i < PositionsTotal(); i++)
     {
      if(PositionGetSymbol(i)==Sym) // Select and check if the position is on the current symbol
      if(PositionGetString(POSITION_SYMBOL) == Sym)
      if(PositionGetInteger(POSITION_MAGIC)==mn || mn == -1)
        {
         ulong  ticket = (ulong)PositionGetInteger(POSITION_TICKET);      // Get the position ticket
...

I will also look at your proposed variant in the work:

//+------------------------------------------------------------------+
//| Функция трейлинга стопа по значению цены StopLoss                |
//+------------------------------------------------------------------+
void TrailingStopByValue(const double value_sl, const long magic=-1, const int trailing_step_pt=0, const int trailing_start_pt=0)
  {
//--- структура цен
   MqlTick tick={};
//--- в цикле по общему количеству открытых позиций
   int total=PositionsTotal();
   for(int i=total-1; i>=0; i--)
     {
      //--- получаем тикет очередной позиции
      ulong  pos_ticket=PositionGetTicket(i);
      if(pos_ticket==0)
         continue;
         
      //--- получаем символ и магик позиции
      string pos_symbol = PositionGetString(POSITION_SYMBOL);
      long   pos_magic  = PositionGetInteger(POSITION_MAGIC);
      
      //--- пропускаем позиции, не соответствующие фильтру по символу и магику
      if((magic!=-1 && pos_magic!=magic) || pos_symbol!=Symbol())
         continue;
         
      //--- если цены получить не удалось - идём далее
      if(!SymbolInfoTick(Symbol(), tick))
         continue;
...