Help Creating MTF Previous Bar Indicator MQL5

 

Hello, I am currently creating an indicator that shows the high and low of the previous bar for an user inputted time frame. It is currently working in some scenarios, however when the input timeframe or chart timeframe is changed it can start to output incorrect lines or sometimes not even output at all. I am new to MQL5 and am still getting use to the coding style so would appreciate any advice on how to fix my problem or improve my code.

I have attached two images showing correct and incorrect outputs:

Correct: Input is set to 1 day, showing indicator on 5m chart

Incorrect: Line appears to show just the current days high and low for every bar. Input is set to 1 day, showing indicator on 15m chart:

Thank you

#property indicator_chart_window
#property indicator_buffers 2 //for previous day high and previous day low
#property indicator_plots 2
#property indicator_type1 DRAW_LINE
#property indicator_type2 DRAW_LINE

input ENUM_TIMEFRAMES userInputTimeframe = PERIOD_D1;
double prevDayHigh[], prevDayLow[];

int OnInit(){
   SetIndexBuffer(0,prevDayHigh,INDICATOR_DATA); //assign the arrays to the buffers
   SetIndexBuffer(1,prevDayLow,INDICATOR_DATA);   
   return(INIT_SUCCEEDED);
}

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[]){
   
   for (int i = prev_calculated; i < rates_total; i++){
      int shift = iBarShift(_Symbol,userInputTimeframe,time[i]);
      double highD1 = iHigh(_Symbol,userInputTimeframe,shift+1);
      double lowD1 = iLow(_Symbol,userInputTimeframe,shift+1);
      
      prevDayHigh[i] = highD1;
      prevDayLow[i] = lowD1;       
   }
   return(rates_total); 
}
Documentation on MQL5: Constants, Enumerations and Structures / Chart Constants / Chart Timeframes
Documentation on MQL5: Constants, Enumerations and Structures / Chart Constants / Chart Timeframes
  • www.mql5.com
Chart Timeframes - Chart Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Files:
Correct.PNG  167 kb
Incorrect.PNG  228 kb