ATR wrong value why?

 

So I have an MT5 VPS running and an expert placed on the chart.

I use trailing stop (price + ATR) and I get ATR value with this code:

double ATR()
{
   double myPriceArray[];
   int AverageTrueRangeDefinition=iATR(_Symbol,PERIOD_D1,10);
   ArraySetAsSeries(myPriceArray,true);
   CopyBuffer(AverageTrueRangeDefinition,0,0,2,myPriceArray);
   double LastAverageTrueRangeValue=NormalizeDouble(myPriceArray[1],_Digits);
   
   return LastAverageTrueRangeValue;
}

It is based on PERIOD_D1. However yesterday I looked over the chart and switched to M1 timeframe while I had an open position.

Then suddenly my expert started to modify SL as if my ATR was calculated on PERIOD_M1 basis.

Although PERIOD_M1 is nowhere mentioned in my expert, why could this happen??

NormalizeDouble is this function:

double NormalizePrice(double p)
{
    double ts=SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
    return(MathRound(p/ts)*ts);
}

Trailing stop is this:

void TrailingStop(double p)
{   
   //SL
   double SL=NormalizePrice(barclose(1)+ATR()*p);
   
   //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);
            }
         }
   }
}
 

Are you sure you are talking about MQL5 code?

If so, then your code is incorrect:

double ATR()
{
   double myPriceArray[];
   int AverageTrueRangeDefinition=iATR(_Symbol,PERIOD_D1,10);

rule for working with indicators in MQL5 - ONE time in OnInit an indicator handle is created, and then CopyBuffer is used anywhere in the program

Documentation on MQL5: Timeseries and Indicators Access / CopyBuffer
Documentation on MQL5: Timeseries and Indicators Access / CopyBuffer
  • www.mql5.com
Counting of elements of copied data (indicator buffer with the index buffer_num) from the starting position is performed from the present to the past, i.e., starting position of 0 means the current bar (indicator value for the current bar). When copying the yet unknown amount of data, it is recommended to use a dynamic array as a buffer[]...
 
Vladimir Karputov:

Are you sure you are talking about MQL5 code?

If so, then your code is incorrect:

rule for working with indicators in MQL5 - ONE time in OnInit an indicator handle is created, and then CopyBuffer is used anywhere in the program

Thank you for your comment, I didnt know this.