Little loop isn't working as it is supposed to :)

 

Hello,

I am writing a script to loop over each day and collect certain data points like ATR(1) dependent on the day of the week and write it into a multidimensional array. So that I can do calculations on this array like the average ATR of all mondays and output the data into a csv file.

So far so good. Now I am having this routine and it doesn't work as I intended. The WeekCounter is supposed to be updated each time at the end of the loop if the weekday = 1 (mondays). But as you can see in the results - and I really don't understand this - the WeekCounter is updated before the Print-Command even though the Print Command comes first. Why is this?


#property version   "1.00"
#property strict
#property show_inputs

input int WeeksToCheck = 20;           
int DaysToCheck = WeeksToCheck * 5;    
int shift = 1;                         
int WeekCounter = 0;   

void start()
{
   //Jump to first friday to start
   while(weekday(shift) != 5) shift++;
   
   //Update the condition
   DaysToCheck = DaysToCheck + shift;
 
   while(shift<DaysToCheck)
   {
      Print("weekday = ", weekday(shift), ", Shift:", shift, " Week: ", WeekCounter);
      shift++;
      if(weekday(shift)==1) WeekCounter++;
   }
}                

//Sub routine
int weekday(int i)
{
   return(TimeDayOfWeek(iTime(NULL, PERIOD_D1, i)));
}




 
   while(shift<DaysToCheck)
   {
      Print("weekday = ", weekday(shift), ", Shift:", shift, " Week: ", WeekCounter);
      shift++;
      if(weekday(shift)==1) WeekCounter++;
   }

Try changing to

   while(shift<DaysToCheck)
   {
      Print("weekday = ", weekday(shift), ", Shift:", shift, " Week: ", WeekCounter);
      if(weekday(shift)==1) WeekCounter++;
      shift++;
   }

 It may help you

 
Ah, now I see why. Thanks!
 
if(weekday(shift)==1)
This assumes that there is no Sunday bar, not true for brokers using GMT timezone (or later.)
int iWeekStart(int shift=0){
   datetime now = Time[shift];                        // Current Chart time.
   int iW1 = iBarShift(NULL, PERIOD_W1, now);         // Weekly Chart shift
   datetime startWeek = iTime(NULL, Period_W1, iW1);  // Weekly Chart time.
   return iBarShift(NULL,0, startWeek);               // Current Chart shift.
}
Reason: