Check for Enough bars in history and download data


In my EA, I use a moving average indicator with a large period, it needs to access up to 150 bars in history.

So I need to check if there are enough bars in history and, if not, download the missing data from within the OnInit() function. What is a good practice to do so. As for now, my code looks like this, but it is unable to download more than 100 bars of history on certain pairs/timeframe (for instance XAGEUR D1):

Code Please…

 if(Bars(_Symbol,_Period ) < min_bars_in_history) // if total bars is less than min_bars_in_history
        Print("::init:: Not enough bars in history. Will download needed bars...");
        MqlRates rates[]; 
        // Try 5 times to allow for enough time to download all needed history
        int try = 5;
        while(try >0)
            int copied=CopyRates(Symbol(),0,0,min_bars_in_history,rates);
            if(copied >= min_bars_in_history) 
                Print("::init:: Bars copied from history: ", copied);
                Print("::init:: Failed to get more than ", copied, " bars from history");
                if(try>1) Print("::init:: Will try again");
        int copied=CopyRates(Symbol(),0,0,min_bars_in_history,rates); 
        if(copied < min_bars_in_history)
            Print("::init:: Definitely failed to download enough bars from history");
            success = false; 

None of that is necessary.

  1. It shouldn’t be done in OnInit as you may not yet be connected. Useless for the current chart. Do it in OnTick for other pairs and other timeframes. See Download history in MQL4 EA - MQL4 and MetaTrader 4 - MQL4 programming forum

  2. When you open a chart, on most brokers you get at least 2K initially. If you don’t have any history, here’s how you can get all available from the broker.

  1. 100 bars usually means the tester. Unless you specify a start date, it starts at the beginning of history plus 100 bars. Either specify at start date after your start of history, get more history, or just have the EA return if you don’t have the 150 needed.

Thank you so much for this in-depth explanation…