indicator that looks at its own turning points to decide its length?

 

 Hi, say you want to change the window length of your indicator to the number of bars since its last turning point, you would do that like this:

 

   for(int i=0; i<limit; i++)
   {    
   ExtMapBuffer0[i]=iMA(0,0,10,0,0,0,i);
   }

   for(i=limit-1; i>=0; i--)
   { 
  
   double curr = ExtMapBuffer0[i]; //current value
   double prev = ExtMapBuffer0[i+1]; //previous value
   double pprev =ExtMapBuffer0[i+2]; //before previous value
   
   if (i > Bars-3 || pprev == EMPTY_VALUE) { TurningPointBuffer[i] = 0; continue; }
    
   int shift = i + 2;
   while (pprev == prev)
      {
      shift++;
      if (shift > Bars-1 || ExtMapBuffer0[shift] == EMPTY_VALUE) break;
      pprev = ExtMapBuffer0[shift];
      }
   
   if ((curr < prev && prev > pprev) || (curr > prev && prev < pprev))
      TurningPointBuffer[i] = 1;
   else
      TurningPointBuffer[i] = TurningPointBuffer[i+1]+1; 
   }

and then code another buffer for the SMA taking TurningPointBuffer[i] as the length parameter. But this only returns you a SMA with window length equal to the number of bars since a turn of a SMA(10) because I set it at iMA(0,0,10,0,0,0,i);. How would you approach it to make it turn since its own turning point? What I mean is count the number of bars of this new "hybrid" SMA that turns based on a window length since its own last turn? So it looks at its own turning points to decide its length?

 
Find the last two turning points, that becomes your length. Compute iMA(length,iBar) iBar from the last turning point-1 to current bar.
Reason: