How to get rates of a different timeframe than the chart's timeframe?

Guys,

I am trying to code an indicator for D1 charts, which uses M1 price/volume/spread/etc. data to calculate the indicator daily values. I use this code to copy rates:

MqlRates       RatesM1[],RatesD1[];
datetime       first_bar_date=SeriesInfoInteger(_Symbol,PERIOD_M1,SERIES_FIRSTDATE);
datetime       last_bar_date=SeriesInfoInteger(_Symbol,PERIOD_M1,SERIES_LASTBAR_DATE);

ArraySetAsSeries(RatesM1,true);
ArraySetAsSeries(RatesD1,true);

int            CopyRatesM1Check=CopyRates(_Symbol,PERIOD_M1,first_bar_date,last_bar_date,RatesM1);
int            CopyRatesD1Check=CopyRates(_Symbol,PERIOD_D1,first_bar_date,last_bar_date,RatesD1);

but it doesn’t work. For some reason I have to change chart timeframe inside the code to be able to read the rates:

MqlRates       RatesM1[],RatesD1[];
datetime       first_bar_date=SeriesInfoInteger(_Symbol,PERIOD_M1,SERIES_FIRSTDATE);
datetime       last_bar_date=SeriesInfoInteger(_Symbol,PERIOD_M1,SERIES_LASTBAR_DATE);

ArraySetAsSeries(RatesM1,true);
ArraySetAsSeries(RatesD1,true);

int            CopyRatesM1Check=CopyRates(_Symbol,PERIOD_M1,first_bar_date,last_bar_date,RatesM1);
ChartSetSymbolPeriod(0,_Symbol,PERIOD_D1);
int            CopyRatesD1Check=CopyRates(_Symbol,PERIOD_D1,first_bar_date,last_bar_date,RatesD1);

However, this creates all sorts of further issues. For example, (this piece of code is placed in OnInit() section) it runs twice! and if I have opened a file it causes the second run to fail, and etc. Does any of you guys have any idea how to deal with this?

Thanks a lot,

Don’t place such code in OnInit(), it will never work correctly.

Let’s say I want to copy M1 and D1 data, and I attach the indicator to chart on M1 timeframe. when I run the code it will only copy M1 rates, and won’t copy D1 rates. Basically, CopyRates function works properly only if used to copy rates at current timeframe.

Can you elaborate on why not in OnInit?

Thanks a a lot,

CopyRates() works properly on any timeframe. But the timeseries may be updating or needing download, check the return code and error code in code of error.

There is a greater chance timeseries are not yet available in OnInit(). Use OnTimer() or OnCalculate() instead.

Just a little comment …

Price Rates are the same on all time frames !!!.

Price Rates are “the same” just for the last [the most recent] bar. Technically index[0] if ordered as AsSeries.

If you need rates from older bars (like Bar.index[1] or older) , they will be different for each timeframe you query them.