Trailing stop issue

 
Below is my trailing stop code, the backtest and demo results are different when it comes to the profit...most if not all trades are extremely off like one trade is $0.9 but in backtest $6.90 what might be the issue? I am using MQL5 Every tick based on real ticks
void trail()
   {

      MqlTradeRequest request = {};
      MqlTradeResult  result = {};
      

      for(int i = 0; i < PositionsTotal(); i++)
         {
            ulong  position_ticket = PositionGetTicket(i);
            if(!PositionSelectByTicket(position_ticket))break;
            string symbol = PositionGetString(POSITION_SYMBOL);
            ulong Position_Magic  = PositionGetInteger(POSITION_MAGIC);
            
            ZeroMemory(request);
            ZeroMemory(result);
                           
            request.action   = TRADE_ACTION_SLTP;
            request.symbol   = symbol;
            request.position = position_ticket;
            request.magic    = Position_Magic;
            
            double points = SymbolInfoDouble(symbol,SYMBOL_POINT);
            int    digits = (int) SymbolInfoInteger(symbol,SYMBOL_DIGITS);
            
            if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
               {
                  double bid = SymbolInfoDouble(symbol,SYMBOL_BID);
                  request.tp = PositionGetDouble(POSITION_TP);
                  double OpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
                  
                  if(bid > OpenPrice + TslTriggerPoints * points)
                     {
                        double NewSL = bid - TslPoints * points;
                        NewSL = NormalizeDouble(NewSL,digits);
                        double SL = PositionGetDouble(POSITION_SL);
                        if(NewSL > SL)
                           {
                              request.sl = NewSL;
                              if(SL == NewSL)continue;
                              if(!OrderSend(request,result))
                                 {
                                    ErrCode = GetLastError();
                                    Print("Unable to trail stopLoss, ",ErrCode);
                                 }
                           }
                     }
               }
            else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
               {
                  double ask = SymbolInfoDouble(symbol,SYMBOL_ASK);
                  request.tp = PositionGetDouble(POSITION_TP);
                  
                  double OpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
                  
                  if(ask < OpenPrice - TslTriggerPoints * points)
                     {
                        double NewSL = ask + TslPoints * points;
                        NewSL = NormalizeDouble(NewSL,digits);
                        double SL = PositionGetDouble(POSITION_SL);
                        if(NewSL < SL)
                           {
                              request.sl = NewSL;
                                                      
                              if(SL == NewSL)continue;
                              if(!OrderSend(request,result))
                                 {
                                    ErrCode = GetLastError();
                                    Print("Unable to trail stopLoss, ",ErrCode);
                                 }
                           }
                     
                     }   
               }
         }
   }
The Fundamentals of Testing in MetaTrader 5
The Fundamentals of Testing in MetaTrader 5
  • www.mql5.com
What are the differences between the three modes of testing in MetaTrader 5, and what should be particularly looked for? How does the testing of an EA, trading simultaneously on multiple instruments, take place? When and how are the indicator values calculated during testing, and how are the events handled? How to synchronize the bars from different instruments during testing in an "open prices only" mode? This article aims to provide answers to these and many other questions.
 
Derrick Mutange: Below is my trailing stop code, the backtest and demo results are different when it comes to the profit...most if not all trades are extremely off like one trade is $0.9 but in backtest $6.90 what might be the issue? I am using MQL5 Every tick based on real ticks

Please read the follow in regards to how the Strategy Tester handles stops and how it greatly differs from a real live trading conditions, due to slippage/deviation.

Forum on trading, automated trading systems and testing trading strategies

Optimization has a Drawdown of 23% but "run single test" returns 87% DD

Fernando Carreiro, 2022.07.25 20:50

Unfortunately it is incorrect to say that S/L and T/P are properly handled. Not even when using "Real Ticks" does the Strategy Tester properly handle T/P and S/L.

The tester will always have the T/P and S/L triggered at the EXACT prices, irrespective of the actual quote prices, thus NEVER suffers slippage. The same problem applies to pending orders.

That is why back-test results of so many EA's that use pending orders or broker-side T/P and S/L, always giver better results in the Strategy Tester then on a live account.


Forum on trading, automated trading systems and testing trading strategies

Question about slippage affecting TP or SL

Fernando Carreiro, 2022.06.01 02:10

The only way (that I have found based on experience) to reduce slippage on the Stop-loss or Take-profit, is not to use broker-side stops, but instead, have the EA manage the exit conditions (virtual stops).

It cannot eliminate slippage entirely, but it can mitigate negative slippage to a good degree, by having the EA monitor the price movement and the spread and only exit when the conditions are more favourable, instead of immediately exiting a position as soon as the target prices are hit (as is the case of broker side stops).

To accomplish this, however, requires good coding skills and well planned exit rules, considering all possible conditions and actions to take.

Forum on trading, automated trading systems and testing trading strategies

Is the backtest information correct?

Fernando Carreiro, 2022.03.27 13:14

Unfortunately, any EA relying on pending orders or broker stops (S/L & T/P) will seriously be misrepresented in the Strategy Tester and on the most part it will be more favourable than on live trading, especially when running the test with tick values.

The reason is as follows — the tester will take pending orders and the stops at the exact prices they are set to be triggered instead of the real quote value of the test market at the time. Even if in the tester the quote price would cause slippage, it still marks them as been taken at the trigger price.

For my own EAs, I never use pending orders and implement virtual stops to get a more realist back test, and the difference is always very noticeable. Here is a reference to another thread in which a user notice the same problem in his back-testing and my answer to the problem:


Forum on trading, automated trading systems and testing trading strategies

Calculate the stop loss at the close of the candle

Fernando Carreiro, 2022.03.26 01:00

Ok, now I understand the issue, but unfortunately all we have discussed so far has nothing to do with it nor will it solve the problem.

The issue is that the Strategy Tester will take the S/L and T/P at the exact price you set it instead of the real price slippage. The same also happens for the opening price of pending orders.

This is a real problem which MetaQuotes has never corrected and it has been like that even in MT4 (and it also makes back tests of Market products look very nice in the Strategy Tester, but bad in live trading).

The only solution I have come up with, is to implement virtual stops that are handled within the code (instead of the broker/tester side), that simulates the stops being hit and closes the positions when the target stops are reached.

In my own EAs I do the following:

  • I add an offset (a fixed amount of points, a very large size) to all my stops when the order is placed. For example, I add an extra 10000 points to the real stop price.
  • Then in the code, I monitor the trades and read the current stops (from open positions) and subtract the offset from their distances (the 10000 points) to get the real stop prices.
  • I then check if the Bid (for buys) or Ask (for sells) has reached those real stops.
  • If they are indeed hit, I then close the positions in the code and in this way, the positions are closed at the real prices with slippage.

When the EA is trading live, all I do is set the virtual stop offset to 0, instead of 10000 for the Strategy Tester.

The reason I use this offset is so that I still have the stops information stored with the order and position and I don't need to keep an internal cache of the data of the real stops. It is all stored within the normal trading records but just offset in value.

The value I choose, for example 10000, is so that the stops don't get accidentality triggered (in the tester system) by a very big spike in spread or slippage and also because it is a "nice" number and easy to calculate visually when reading the test reports.

I hope you will be able to understand all this process. However, for a beginner it may be difficult to implement, as it requires a higher level of coding skills.

 
Fernando Carreiro #:

Please read the follow in regards to how the Strategy Tester handles stops and how it greatly differs from a real live trading conditions, due to slippage/deviation.

Thanks I will use the virtual stops

 
Derrick Mutange #: Thanks I will use the virtual stops
You are welcome!