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());
datetime last_bar_time = time[bars-1];
2016.10.11 16:10:44.707 PAT_Indicator_v2 (GBPUSD-sb,M5) bars=0
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).
Sleep() does not work in the indicator.