Determine second highest bar within a set range

 

I wonder if someone can assist? I'm looking to determine the second highest bar within a set number of bars. This is my code, but it does not produce the correct answer, as can be seen in the attached chart. The highest bar is H 1=16 (correct), reduce search range 1: from 1 to 15 H A=8(correct), reduce search range 2: from 17 to 30 H B=46(Incorrect). Chart attached, My Code:

void OnTick()
{
if (GetNewChartCandle()==true)
{
int HighestBar1=0;
int HighestBar2=0;
int HighestBarA=0;
int HighestBarB=0;
int start=0;
int end=0;

HighestBar1=iHighest(_Symbol,_Period,MODE_HIGH,30,1);

if(HighestBar1==1)
{
start=HighestBar1+1;
HighestBar2=iHighest(_Symbol,_Period,MODE_HIGH,30,start);
}

if(HighestBar1==30)
{
end=HighestBar1-1;
HighestBar2=iHighest(_Symbol,_Period,MODE_HIGH,end,1);
}

if(HighestBar1<=29 && HighestBar1>=2)
{
start=HighestBar1+1;
end=HighestBar1-1;
HighestBarA=iHighest(_Symbol,_Period,MODE_HIGH,end,1);
HighestBarB=iHighest(_Symbol,_Period,MODE_HIGH,30,start);
HighestBar2=MathMax(HighestBarA,HighestBarB);
}

Comment("H 1: ",HighestBar1,"\n","H 2: ",HighestBar2,"\n","H A: ",HighestBarA,"\n","H B: ",HighestBarB,"\n","Start: ",start,"\n","End: ",end);
}
}

bool GetNewChartCandle()
{
MqlRates priceData[];
CopyRates(_Symbol,_Period,0,3,priceData);

static datetime timeStampLastCheck;
datetime timeStampCurrentCandle;

bool newCandle=false;

timeStampCurrentCandle=priceData[0].time;

if (timeStampCurrentCandle==timeStampLastCheck)newCandle=false;
if (timeStampCurrentCandle!=timeStampLastCheck)newCandle=true;

timeStampLastCheck=timeStampCurrentCandle;

return newCandle;
}

Files:
Chart.jpg  83 kb
 
ShaunBo: determine the second highest bar within a set number of bars. T
  1. Copy the highs, sort them, get which ever you want. Or
  2. Go through them and find the highest and second.
    Not compiled, not tested, just typed.
    int iFirst, iSecond; double first=0, second=0;
    for(int i=iBeg; i<iEnd; ++i){
       double h=iHigh(_Symbol,_Period, i);
       if(h > first){ iSecond=iFirst; second=first; iFirst=i; first=h; }
       else if(h > second){ iSecond=i; second=h; }
    }
    Not compiled, not tested, just typed.

  3. if (timeStampCurrentCandle==timeStampLastCheck)newCandle=false;
    if (timeStampCurrentCandle!=timeStampLastCheck)newCandle=true;
    Simplify your code.
              Increase Order after stoploss - MQL4 programming forum #1.3 2017.05.29
Reason: