trailing to previous swing highs or swing lows

 

dear friends,

               i am not a experienced coder, but learning by going through experienced coders from forums.

i have coded a trailing stop using zigzag by calling from a EA though icustom function. my ea trails for only one time and not trailing to the next swing highs or next swing lows. i cant figure out where i am wrong.

can anybody figure out where i am wrong. thanks in advance.

 void AdjustTrail()
  { 
   for(int iBar = 1; iBar < Bars; iBar++) if(
   iCustom(NULL,0, "ZigZag", 0, iBar) != 0) break;
     int iZig1 = iBar;
   for( iBar++; iBar < Bars; iBar++) if(
      iCustom(NULL,0, "ZigZag", 0, iBar) != 0) break;
   int iZig2 = iBar;
   double h1 = High[iZig1],
         h2 = High[iZig2];
   double ZigLatestHigh = (h1 > h2) ? h1 : h2,
         ZigLatestLow  = (h1 > h2) ? Low[iZig2] : Low[iZig1];
        
   double buystoploss= ZigLatestLow-PadAmount*pips;
      
   double sellstoploss= ZigLatestHigh+PadAmount*pips;
       
   //buy order section
   
      for(int b=OrdersTotal()-1;b>=0;b--)
       {
        if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
          if(OrderMagicNumber()==Magic1)
            if(OrderSymbol()==Symbol())
              if(OrderType()==OP_BUY)
                if(ZigZagTrail)
                  {
                   if(IsNewCandle())
                     if(OrderStopLoss()<buystoploss)
                      OrderModify(OrderTicket(),OrderOpenPrice(),buystoploss,OrderTakeProfit(),0,clrNONE);
                  }
                   
                else if(Bid-OrderOpenPrice()>WhenToTrail*Point)
                       if(OrderStopLoss()<Bid-Point*TrailAmount)
                        OrderModify(OrderTicket(),OrderOpenPrice(),Bid-(Point*TrailAmount),OrderTakeProfit(),0,clrNONE);
                    
        }
        
     //sell ordeer section
      for(int s=OrdersTotal()-1;s>=0;s--)
       {
        if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
          if(OrderMagicNumber()==Magic1)
            if(OrderSymbol()==Symbol())
              if(OrderType()==OP_SELL)
                if(ZigZagTrail)
                 {
                  if(IsNewCandle())
                    if(OrderStopLoss()>sellstoploss)
                     OrderModify(OrderTicket(),OrderOpenPrice(),sellstoploss,OrderTakeProfit(),0,clrNONE);
                 }
               else if(OrderOpenPrice()-Ask>WhenToTrail*Point)
                      if(OrderStopLoss()>Ask+(TrailAmount*Point)||OrderStopLoss()==0)
                       OrderModify(OrderTicket(),OrderOpenPrice(),Ask+(TrailAmount*Point),OrderTakeProfit(),0,clrNONE);  
                   
        }
        
        
  }    

//+------------------------------------------------------------------+//+------------------------------------------------------------------+
 
Topics concerning MT4 and MQL4 have their own section.
In future please post in the correct section.
I have moved your topic to the MQL4 and Metatrader 4 section.
Reason: