"For" Loop to detect most recent peak

 

I haven't really searched but, I was trying to think of a way to detect the most recent peak on a chart. A solution that I believe would work involves using a For Loop to check "x" number of periods previously. The loop would just check previous values and compare which of the values was greater. If the value that's further in the past is greater the peak hasn't been located yet. But, as soon as the previous value is lower than the current value that would be the most recent peak.

For instance take the Period Array with the following values "TestArray[1,1,2,3,4,5,4]" (assuming TestArray[0] is the current bar)

For this array it would check starting with TestArray[1]: is TestArray[1] > TestArray[2]? The answer would be no because "1" < "2".

Is TestArray[2] > TestArray[3}? NO and so on until you get to TestArray[5].

Is TestArray[5] > TestArray[6]? YES it is so this would be the most recent peak.


That is the logic of the loop. Does that make sense and what are the flaws with measuring the most recent peak that way?

//PriceArray[] is stored as a series, meaning current price = PriceArray[0]
//PeakPrice stores the peak to be used later

for(idx = 1; idx < 61; idx ++) //'for' loop to check previous 60 periods for most recent peak
        {
                if(idx < 59)
                {       if(PriceArray[idx] < PriceArray[idx + 1])
                        {
                                PeakPrice = PriceArray[idx + 1];
                        }
                        else if(PriceArray[idx] > PriceArray[idx + 1])
                        {
                                PeakPrice = PriceArray[idx];
                        }
                }
                else if(idx >= 60)
                {
                        PeakPrice = PriceArray[idx];
                }
        }
 
Hank Clark: I haven't really searched but, I was trying to think of a way to detect the most recent peak on a chart. A solution that I believe would work involves using a For Loop to check "x" number of periods previously.
  1. A for loop means doing it yourself.
    Not compiled, not tested.
    template<typename T>
    int ArrayMax(const T& array[], int start=0, int count=WHOLE_ARRAY){
       if(count==WHOLE_ARRAY) count = ArraySize(array)-start;
       int iLargest = start;
       for(int i=start+count-1; i > start; --i) if(array[iLargest] < array[i]) iLargest=i;
       return iLargest;
    }
    Not compiled, not tested.
    The only advantage it that you control which element is selected if there is an exact tie, by the search direction.

  2. Use the functions provided. Perhaps you should read the manual. Array Functions / ArrayMaximum - Reference on algorithmic/automated trading language for MetaTrader 5
  3. For prices:
    int    iHH = iHighest(_Symbol, _Period, MODE_HIGH, x, iStart);
    double  HH = iHigh(_Symbol, _Period, iHH);
    Replace iHighest with MQL5 equivalent.