trailing stop

 
Hi everyone. I am trying to implement a trailing stop. The code compiles, but the trailing stop function is not working in tester. I am trying to call the function in the very first line after OnTick, so i would assume that the function will be called every time there is a new tick. But no orders are being modified when i test the code. Can anyone spot why this is not working? 
//+------------------------------------------------------------------+
//|                                       BreakOut in the making.mq4 |
//|                                                           Jes    |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Jes"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

int magicNB = 55555;

input int speed =50;// higher number = slower visual backtesting

#include  <CustomFunctions01.mqh>
//extern int stopLossMA = 20;

//Risk per Trade
extern double riskPerTrade = 0.02;//0.01 = 1% 

//ATR STOP LOSS and TP

input double atrSLMultiplier = 1;
input double atrTPMultiplier = 2;

//range period:

extern string rangePeriodStart = "00:01";
extern string rangePeriodEnd = "08:59";

//Trailing Stop:
extern bool UseTrailingStop = false;
extern int TrailBegin = 2;
extern int TrailStep = 2;




//Definition of the Hour, this is necessary to have a drop down menu to input the hour
enum Enum_Hour{
   h00=00,     //00:00
   h01=01,     //01:00
   h02=02,     //02:00
   h03=03,     //03:00
   h04=04,     //04:00
   h05=05,     //05:00
   h06=06,     //06:00
   h07=07,     //07:00
   h08=08,     //08:00
   h09=09,     //09:00
   h10=10,     //10:00
   h11=11,     //11:00
   h12=12,     //12:00
   h13=13,     //13:00
   h14=14,     //14:00
   h15=15,     //15:00
   h16=16,     //16:00
   h17=17,     //17:00
   h18=18,     //18:00
   h19=19,     //19:00
   h20=20,     //20:00
   h21=21,     //21:00
   h22=22,     //22:00
   h23=23,     //23:00
};
 
input Enum_Hour StartHour=h08;      //Start opearation hour
input Enum_Hour LastHour=h17;       //Last operation hour
 
bool CheckActiveHours(){
   //Set by default the operations disabled
   bool OperationsAllowed=false;
   //Check if the current hour is between the allowed hours of operations, if so I return true
   if(StartHour==LastHour && Hour()==StartHour) OperationsAllowed=true;
   if(StartHour<LastHour && Hour()>=StartHour && Hour()<=LastHour) OperationsAllowed=true;
   if(StartHour>LastHour && ((Hour()>=LastHour && Hour()<=23) || (Hour()<=StartHour && Hour()>0))) OperationsAllowed=true;
   return OperationsAllowed;
}
 

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//backtester speed (higher number is slower)
for(int i = speed;i>0;i--){
   Comment(i);
   }
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()

    {
    if (UseTrailingStop) AdjustTrail();
    CheckForSignal();
    }
    
      // calculate high and low of range:
      
    void CheckForSignal(){
      datetime dtfrom=StringToTime(rangePeriodStart);
      datetime dttill=StringToTime(rangePeriodEnd);
      int ifrom=iBarShift(NULL,0,dtfrom);
      int itill=iBarShift(NULL,0,dttill);
      int ihighest=iHighest(NULL,0,MODE_HIGH,ifrom-itill,itill+1);
      int ilowest = iLowest(NULL,0,MODE_LOW, ifrom-itill,itill+1);
      
      // high and low values:
      
      double highestPrice=iHigh(NULL,0,ihighest);
      double lowestPrice = iLow(NULL,0,ilowest);
      
      //double stopLossMovingAvarage = iMA(NULL,0,stopLossMA,0,MODE_SMA,PRICE_CLOSE,1);
      
      
      //ATR STOPLOSS and TP
      double atr = iATR(NULL,0,14,0);
      
      int ATRstopLoss = (atr*atrSLMultiplier/Point);
      
      //ATR TAKEPROFIT
      double atrTP = iATR(NULL,0,14,0);
      
      int ATRtakeProfit = (atrTP*atrTPMultiplier/Point);
      
      
      if(!CheckIfOpenOrdersByMagicNB(magicNB))
      
      {
      
         if(CheckActiveHours()&& Ask == highestPrice && Open[0] < highestPrice )
         
         {
           
            double lotSize = OptimalLotSize(riskPerTrade,20);
            
            OrderSend(NULL,OP_BUY,lotSize,highestPrice+10*Point,20,highestPrice-ATRstopLoss*Point, highestPrice+ATRtakeProfit*Point,NULL,magicNB); 
            
           
         }
         
         else if(CheckActiveHours()&& Bid == lowestPrice && Open[0] > lowestPrice )
         
         {
            
            double lotSize = OptimalLotSize(riskPerTrade,20);
            
            OrderSend(NULL,OP_SELL,lotSize,lowestPrice-10*Point,20,lowestPrice+ATRstopLoss*Point,lowestPrice-ATRtakeProfit*Point,NULL,magicNB);
            
            
         }
         
       
      
      }

      
  }
  
      
   
//+------------------------------------------------------------------+
//|   Trailing Stop Function                                         |
//+------------------------------------------------------------------+
void AdjustTrail(){
   for(int i=OrdersTotal()-1;i=0;i--){
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
         if(OrderMagicNumber()==magicNB)
            if(OrderType()==OP_BUY){
               if(Bid-OrderOpenPrice()>TrailBegin*Point)
                  if(OrderStopLoss()<Bid-TrailStep*Point)
                     if(!OrderModify(OrderTicket(),Bid-(TrailStep*Point),OrderTakeProfit(),0,CLR_NONE)){
                        int err = GetLastError();
                        Print("SL modify error");
                     
                     }// OrderModify
               }//buy order
               else if (OrderType()==OP_SELL){
               if(OrderOpenPrice()- Ask >TrailBegin*Point)
                  if(OrderStopLoss()<Ask+TrailStep*Point)
                     if(!OrderModify(OrderTicket(),Ask+(TrailStep*Point),OrderTakeProfit(),0,CLR_NONE)){
                        int err = GetLastError();
                        Print("SL modify error");
                        }
               }// sell order
               
            }//orderSelect
            else{//in case it fails to select an order
            int err = GetLastError();
            Print("Error selecting an Order");
            
         }
              
      }// forloop
      
}

 
traderjes:
Hi everyone. I am trying to implement a trailing stop. The code compiles, but the trailing stop function is not working in tester. I am trying to call the function in the very first line after OnTick, so i would assume that the function will be called every time there is a new tick. But no orders are being modified when i test the code. Can anyone spot why this is not working? 
for(int i=OrdersTotal()-1;i=0;i--){
You have to write i>=0
 
for(int i=OrdersTotal()-1;i=0;i--){

I think that you want

for(int i=OrdersTotal()-1;i>=0;i--){
 
Keith Watford:

I think that you want

Thank you so much for looking at the code. However, I implemented your suggestions but the trail function is still not working:( If anyone have any other ideas im happy to hear. Been going over it so many times myself, and i really cant figure out where the issue is.. 

 
traderjes:
Hi everyone. I am trying to implement a trailing stop. The code compiles, but the trailing stop function is not working in tester. I am trying to call the function in the very first line after OnTick, so i would assume that the function will be called every time there is a new tick. But no orders are being modified when i test the code. Can anyone spot why this is not working? 

//+------------------------------------------------------------------+
//|   Trailing Stop Function                                         |
//+------------------------------------------------------------------+
void AdjustTrail(){
   for(int i=OrdersTotal()-1;i=0;i--){
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
         if(OrderMagicNumber()==magicNB)
            if(OrderType()==OP_BUY){
               if(Bid-OrderOpenPrice()>TrailBegin*Point)
                  if(OrderStopLoss()<Bid-TrailStep*Point)
                     if(!OrderModify(OrderTicket(),Bid-(TrailStep*Point),OrderTakeProfit(),0,CLR_NONE)){
                        int err = GetLastError();
                        Print("SL modify error");

                     
                     }// OrderModify
               }//buy order
               else if (OrderType()==OP_SELL){
               if(OrderOpenPrice()- Ask >TrailBegin*Point)
                  if(OrderStopLoss()<Ask+TrailStep*Point)
                     if(!OrderModify(OrderTicket(),Ask+(TrailStep*Point),OrderTakeProfit(),0,CLR_NONE)){
                        int err = GetLastError();
                        Print("SL modify error");
                        }
               }// sell order
               
            }//orderSelect
            else{//in case it fails to select an order
            int err = GetLastError();
            Print("Error selecting an Order"); // Why not just use Print("Error selecting an order",GetLasterror());
            
         }
              
      }// forloop

i wonder...were do you actually print out the error code itself in journal log using that kind of coding of yours...?

 
  • Better use input in favour of extern because it's deprecated and even will not show up in MT5 inputs.
  • TrailStep usually means the step size (increment) to move the trailing stop. I guess you mixed Trailing Step and Trailing Stop somewhere.
  • So TrailStop is somewhere missing in the inputs.
  • Point is mostly different from a Pip and may vary across brokers for the same security.
  • Check out some EAs in the codebase and compare their trailing stop logic to yours.
 
traderjes:

Thank you so much for looking at the code. However, I implemented your suggestions but the trail function is still not working:( If anyone have any other ideas im happy to hear. Been going over it so many times myself, and i really cant figure out where the issue is.. 

This line:

                  if(OrderStopLoss()<Ask+TrailStep*Point)

Should be:

                  if(OrderStopLoss()>Ask+TrailStep*Point)
Reason: