Bars() returns 0 when called on first execution of indicator after the terminal starts, but not on subsequent executions.

 

I use the number of bars on the chart as a limit to a loop iteration. If the indicator is already loaded on the chart when the terminal starts, Bars() returns 0, and my code fails. If I remove and then replace the indicator on the chart, it returns the correct number and my code succeeds. Why is this happening, and is there a way around?

 

   int bars = Bars(Symbol(),Period());
   Print("bars=",bars);
   datetime last_bar_time = time[bars-1];
   
   for(i=entry_shift+1;i<bars;i++)
   {
//code here..
   }

 2016.10.11 16:10:44.707 PAT_Indicator_v2 (GBPUSD-sb,M5) bars=0

2016.10.11 16:18:37.903 PAT_Indicator_v2 (GBPUSD-sb,M5) bars=125656

 

This happens when the terminal starts faster then the download of the quotes from you broker.

Use a loop with sleep to wait ...

 
Carl Schreiber:

This happens when the terminal starts faster then the download of the quotes from you broker.

Use a loop with sleep to wait ...

Don't use loop. Just exit from event handler until Bars returns sufficient number of bars for your indicator.

Make sure to recalculate indicator fully if Bars changed more than 1 bar at a time (this may happen if the teminal filled gaps in the quotes or downloaded more history).

 
Carl Schreiber:

This happens when the terminal starts faster then the download of the quotes from you broker.

Use a loop with sleep to wait ...

 

Sleep() does not work in the indicator.