calculate ZigZag indicator

 

Hello . I calculate ZigZag indicator value with this method , but it's very slow in Backtest . How can I optimize this code? Or if you know a better way, please help.
I wrote the code based on my knowledge .

this code work fine but it's very slow  , i need only 5 pivot data , for this after find 5 value use "break" and I get out of the loop .

double zigzag[5];
ZeroMemory(zigzag);
int zigzag_counter=0;

for(int i=0; i<1000; i++)
  {
   double zigzag_value=read_ZigZag(_Symbol,PERIOD_M5,i);
   if(zigzag_value!=0)
     {
      zigzag[zigzag_counter]=zigzag_value;
      zigzag_counter++;
      if(zigzag_counter==5)
        {
         break;
        }
     }
  }
   

double read_ZigZag(string symbol, ENUM_TIMEFRAMES timeframe,int Candle_Number, int depth=12, int deviation=5, int back_step=3)
  {


   double result = 0;
   double ZZ[];
   ArraySetAsSeries(ZZ,true);
   int ZZ_handle = iCustom(symbol,timeframe,"ZigZag",depth,deviation,back_step);
   CopyBuffer(ZZ_handle,0,Candle_Number,1,ZZ);
   result=ZZ[0];
   return (result);
  }
//+------------------------------------------------------------------+
 
tinivini :

Hello . I calculate ZigZag indicator value with this method , but it's very slow in Backtest . How can I optimize this code? Or if you know a better way, please help.
I wrote the code based on my knowledge .

this code work fine but it's very slow  , i need only 5 pivot data , for this after find 5 value use "break" and I get out of the loop .

A very gross mistake: the MQL5 style implies that the handle (in this example 'ZZ_handle') should be created ONLY ONCE and should be done in OnInit. Please fix your 'read_ZigZag' function.