Bars variable returning 0

 
My indicator draws rectangles that go from the beginning of the chart to the end.
To do that, I use the Bars pre-defined variable https://docs.mql4.com/predefined/bars
Since I only need that done once, it is in the OnInit() function of the indicator.
Everything works fine, but sometimes (not always), when switching Time frames or Symbol, the Bars variable returns 0 and the indicator crashes. The bars are shown and ir I reload the indicator on this new TF or symbol, it works fine, with Bars returning the proper number.
Any hints on why this happens?
Bars - Predefined Variables - MQL4 Reference
Bars - Predefined Variables - MQL4 Reference
  • docs.mql4.com
Bars - Predefined Variables - MQL4 Reference
 
Sadi: it is in the OnInit() function of the indicator.
Don't try to use any price or server related functions in OnInit (or on load,) as there may be no connection/chart yet:
  1. Terminal starts.
  2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
  3. OnInit is called.
  4. For indicators OnCalculate is called with any existing history.
  5. Human may have to enter password, connection to server begins.
  6. New history is received, OnCalculate called again.
  7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
 
Thank you.

So, how do I make it run only once (that's all I need for now), and make sure it only runs only when the bars have been loaded?
 
Sadi:
Thank you.

So, how do I make it run only once (that's all I need for now), and make sure it only runs only when the bars have been loaded?
int OnCalculate (const int rates_total,      // size of input time series
                 const int prev_calculated,  // bars handled in previous call
                 const datetime& time[],     // Time
                 const double& open[],       // Open
                 const double& high[],       // High
                 const double& low[],        // Low
                 const double& close[],      // Close
                 const long& tick_volume[],  // Tick Volume
                 const long& volume[],       // Real Volume
                 const int& spread[]         // Spread
   )
{
    
    if ( prev_calculated == 0 )
    {
        // Do all functions you cannot do in OnInit() here.
    }

    // . . . 
}
 
Perfect. Thank you!