Find the High or Low for a number of bars -- code

 

This function will find the High or Low of some number of bars. I was pulling my hair out debugging this thing. The High part of the function worked great but the Low part of function always return 0. Then I realized that The variable barApex was not initially defined and so was set to 0. It was hard to find a Low price lower than 0!

-- enjoy.

//+------------------------------------------------------------------+
//| apexFromBars - get high, low, from some number of bars           |
//+------------------------------------------------------------------+

double apexFromBars(int Nbars, string highLow)
{
   double barApex;                              // declare the return value
   int ix;                                      // declared the index counter   
   
   for(ix=0;ix<=Nbars-1;ix++)                   // run the loop
   {
      if(highLow == "Low")                      // if looking for a low
      {
      barApex = Ask;                            // start with a price above the Low so Low won't be zero
         if (Low[ix] < barApex)                 // look through the index of bars to find the lowest Low
         {
            barApex = Low[ix];
         }
      }
      if(highLow == "High")                     // if looking for High do the following (like above)
      {
      barApex = Bid;                   		// don't really need this
         if (High[ix] > barApex)                 
         {
            barApex = High[ix];                    
         }
      }						// I have a few un-needed "{}" -- they help me see the structure
   }
   Print("Index:",Nbars,"  highLow:",highLow,"  barApex:",barApex," Bid:",Bid,"  Ask:",Ask); // when testing print everything -- trust nothing!
   return(barApex); // return either the High or Low of the bar history
}
 
Why not use iHighest and iLowest? https://docs.mql4.com/series/iHighest
 

Yes of course! Use the right tool for the right job.

double apexBars(int Nbars, string highLow)
{
   double barApex;
   if(highLow == "Low")
      barApex = Low[iLowest(NULL,0,MODE_LOW,Nbars,0)];

   if(highLow == "High")
      barApex = High[iHighest(NULL,0,MODE_HIGH,Nbars,0)];

   Print("Index:",Nbars,"  highLow:",highLow,"  barApex:",barApex);
   return(barApex);
}
Reason: