Trailing stop function

 

Hello everyone,

so I have a trailing stop function which works but once it changes my SL it keeps doing it again and again

So this is the function 

void TrailingStop()
{
   //Last bar close price
   MqlRates PriceInformation[];
   ArraySetAsSeries(PriceInformation,true);
   int Data=CopyRates(Symbol(),Period(),0,Bars(Symbol(),Period()),PriceInformation);
   double lastClosePrice=PriceInformation[1].close;
   //Last bar average true range
   double myPriceArray[];
   int AverageTrueRangeDefinition=iATR(_Symbol,PERIOD_D1,10);
   ArraySetAsSeries(myPriceArray,true);
   CopyBuffer(AverageTrueRangeDefinition,0,0,2,myPriceArray);
   double LastAverageTrueRangeValue=NormalizeDouble(myPriceArray[1],_Digits);
   //SL
   double SL=lastClosePrice+LastAverageTrueRangeValue*2.4;
   //loop
   for(int i=PositionsTotal()-1; i>=0; i--)
   {
      string symbol=PositionGetSymbol(i);
      
         if(Symbol()==symbol)
         {
         ulong PositionTicket=PositionGetInteger(POSITION_TICKET);
         double CurrentStopLoss=PositionGetDouble(POSITION_SL);
         
            if(SL<CurrentStopLoss)
            {
               trade.PositionModify(PositionTicket,SL,0);
            }
         }
   }
}

Does anyone have an idea how to fix this?

 
Before modify check if anything has changed. Like the error suggests.
 
Enrique Dangeroux:
Before modify check if anything has changed. Like the error suggests.

There is a check. It should be modified only if lastClosePrice+LastAverageTrueRangeValue*2.4 is lower than PositionGetDouble(POSITION_SL).

 
Demosfen:

There is a check. It should be modified only if lastClosePrice+LastAverageTrueRangeValue*2.4 is lower than PositionGetDouble(POSITION_SL).

maybe it's a normalizing issue, print both values, normalize with _Digits or check with
if( SL < CurrentStopLoss-_Point )
 

You should normalize SL

//SL
double SL=NormalizeDouble(lastClosePrice+LastAverageTrueRangeValue*2.4, _Digits);


if(SL<CurrentStopLoss)
 
amrali:

You should normalize SL

I will try it out. Thank you

 
amrali: You should normalize SL
You used NormalizeDouble, It's use is usually wrong, as it is in your case.
 
William Roeder:
You used NormalizeDouble, It's use is usually wrong, as it is in your case.

I will look into it. But in my function I use values from yestarday and they do not change anymore right. Thats why I dont get why my if-check doesnt work properly.

 
Demosfen:

I will look into it. But in my function I use values from yestarday and they do not change anymore right. Thats why I dont get why my if-check doesnt work properly.

You can add a Print() statement, perhaps before your if check, to see the values of SL and CurrentStopLoss - that'll take all the guess works out of the way.

Reason: