How to convert classic Trailing Stop Loss to Virtual Trailing Stop Loss

 

Hello,


Normally, Stop Loss execute in broker server and it send a data of Stop Loss value to broker. This has a disadvantage of too many operation and also Stop Hunting from most of the Forex brokers. To avoid this, i heard there is a concept called Virtual Stop loss which act same as normal but it does not send value to Broker server instead it keep in the values in Local meta trader.


Classic Trailing Stop Loss code :

void TrailingStopLoss(int TrailingStopLoss_magic)
  {
// Loop through all open orders
   for(int i = OrdersTotal() - 1; i >= 0; i--)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
         double TrailingStopLoss_entryPrice = OrderOpenPrice();
         // Check if the order is a buy order with magic number 1
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == TrailingStopLoss_magic && OrderType() == OP_BUY)
           {
            if(Bid - (TrailingStopLoss_entryPrice + Trailing_TP * gPips) > gPips * Trailing_Gap)
              {
               if(OrderStopLoss() < Bid - gPips * Trailing_Gap || OrderStopLoss() == 0)
                 {
                  ResetLastError();
                  RefreshRates();
                  gOrderModifyCheck = OrderModify(OrderTicket(), OrderOpenPrice(), Bid - gPips * Trailing_Gap, OrderTakeProfit(), 0, clrBlue);
                  if((_LastError != ERR_NO_ERROR && _LastError != ERR_NO_MQLERROR) || !gOrderModifyCheck)
                     Print(__FUNCTION__ + " => Buy Order Error Code : " + GetLastError());
                 }
              }
           }

         // Check if the order is a sell order with magic number 2
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == TrailingStopLoss_magic && OrderType() == OP_SELL)
           {
            if((TrailingStopLoss_entryPrice - Trailing_TP * gPips) - Ask > gPips * Trailing_Gap)
              {
               if(OrderStopLoss() > Ask + gPips * Trailing_Gap || OrderStopLoss() == 0)
                 {
                  ResetLastError();
                  RefreshRates();
                  gOrderModifyCheck = OrderModify(OrderTicket(), OrderOpenPrice(), Ask + gPips * Trailing_Gap, OrderTakeProfit(), 0, clrPink);
                  if((_LastError != ERR_NO_ERROR && _LastError != ERR_NO_MQLERROR) || !gOrderModifyCheck)
                     Print(__FUNCTION__ + " => Sell Order Error Code : " + GetLastError());
                 }
              }
           }
        }
     }
  }


I have no idea how should i code or convert this to Virtual Trailing Stop Loss. i am not asking you to work for me or write a code for me for free. I am just saying some suggestion, idea and small sample code how i can create virtual trailing Stop loss which act same like my above code except modifying real Stop Loss value.

 

In the case of a virtual stop loss, everything is quite simple, since its value is always known. You can do something like this (pseudocode, example for a buy order):

#property strict
#define _slSize (500 * Point())

void OnTick()
  {
   //...
   if(OrderOpenPrice() - Bid >= _slSize)
     {
      //Close the order
     }
  }

There is no simple solution for a virtual trailing stop, since you need to store the virtual stop loss value for each order somewhere (modify this value instead of OrderModify and close the order when the current price breaks this value). In this case, the task of restoring work after restarting the advisor is also not simple.

[EDIT]

Despite the fact that creating an array of structures/classes for storing stop losses is not a super difficult task, keeping such an array up to date (by deleting already closed orders from it) is quite difficult.
 
Vladislav Boyko #:
Despite the fact that creating an array of structures/classes for storing stop losses is not a super difficult task, keeping such an array up to date (by deleting already closed orders from it) is quite difficult.

Although, you can cheat by using some simple but slow algorithm for this, but performing this algorithm only once a day, for example. That is, throughout the day, you do not delete anything from this array, but when the day changes, you perform a “cleanup” by copying only current orders to an auxiliary array.

However, even with the use of tricks/simplifications, this cannot be written on your knees in 10 minutes.

 
I did the same method as Vladislav. But if u only need 1 virtual sl for 1 buy order, or multiple grid-type buy orders, u may use 1 variable instead of an array
 
Vladislav Boyko #:

In the case of a virtual stop loss, everything is quite simple, since its value is always known. You can do something like this (pseudocode, example for a buy order):

There is no simple solution for a virtual trailing stop, since you need to store the virtual stop loss value for each order somewhere (modify this value instead of OrderModify and close the order when the current price breaks this value). In this case, the task of restoring work after restarting the advisor is also not simple.

[EDIT]

Despite the fact that creating an array of structures/classes for storing stop losses is not a super difficult task, keeping such an array up to date (by deleting already closed orders from it) is quite difficult.

Your code works like Virtual Stop Loss. But i need more than that here. I am looking for idea of Virtual Trailing.

Abdul Arief Bogie Ardianto #:
I did the same method as Vladislav. But if u only need 1 virtual sl for 1 buy order, or multiple grid-type buy orders, u may use 1 variable instead of an array
whether it one value or array it for Virtual Stop Loss. i am looking for Virtual Trailing.
 

Hi

You need to remember the virtual sl value for each trade and manage this as a normal SL. Of course you need to add here a management for trailing but also for closing the trade on this virtual SL.

You can remember those SLvalues when you open a trade: as global variables – for example:

GlobalVariableSet(“ord”+InetegerToString(OrderTicket()), level_sl); or even display the level as a line on the chart (or just some object on the chart which don’t need to be visible) – ObjectCreate(ChartID(),“ord”+InetegerToString(OrderTicket()), OBJ_HLINE, 0, 0, level-sl)

And later when you want to trail – just get the value of this rememberd level and modify this level instead of OrderStopLoss(). Of course, you need to also remove those remembered values after trade is closed.

Best Regards

 
void OnTick()
  {
   //...
   if(OrderOpenPrice()

MT4: You can not use any Trade Functions until you first select an order.
MT5: first select a position via CPositionInfo, directly, or by 'MT4Orders' library (2016)

 
In you Anfrage about stop hunting by your Broker change your Broker or your trading Style. Stops lese the. 10 pips is useless. You will be Stoped out, and as Long you Trade below 1000lots, Noone cares about you
 
William Roeder #:

MT4: You can not use any Trade Functions until you first select an order.
MT5: first select a position via CPositionInfo, directly, or by 'MT4Orders' library (2016)

Please pay attention to what I highlighted:

Forum on trading, automated trading systems and testing trading strategies

How to convert classic Trailing Stop Loss to Virtual Trailing Stop Loss

Vladislav Boyko, 2024.04.16 18:57

You can do something like this (pseudocode, example for a buy order):

#property strict
#define _slSize (500 * Point())

void OnTick()
  {
   //...
   if(OrderOpenPrice() - Bid >= _slSize)
     {
      //Close the order
     }
  }
Reason: