//+------------------------------------------------------------------+
//|                                            ExtendRectangleV2.mq5 |
//|                                     Copyright 2021, John de Boed |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, John de Boed"
#property link      "https://www.mql5.com"
#property version   "2.00"
#property indicator_chart_window

// Check if extend needed
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[])
  {
      int BarNumber=Bars(_Symbol,_Period);  // Current BarNumber
      if (isNewBar(BarNumber))              // Check for new bar
         ExtendRec();                       // Extend rectangle to the right
      return(rates_total);
  }
  

// Also extend on chart event
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
   {
      int BarNumber=Bars(_Symbol,_Period);  
      if (isNewBar(BarNumber))
         ExtendRec();
      return;
   } 

// Extends all rectangles to the right
void ExtendRec()
   {
      string Obj_Name;
      long Obj_Type;
      int Tel,NrRect;

      NrRect=ObjectsTotal(0,0,-1);
      for (Tel=0;Tel<NrRect;Tel++)
         {
            Obj_Name=ObjectName(0,Tel,0,-1);
            Obj_Type=ObjectGetInteger(0,Obj_Name,OBJPROP_TYPE);
            if (Obj_Type==OBJ_RECTANGLE)
                ObjectSetInteger(0,Obj_Name,OBJPROP_TIME,1,TimeCurrent());
         }
      return;
   } 

// Check for newbar, returns true if found 
bool isNewBar(int BarNumber)
   {
      static int LastBarNumber;
      if (BarNumber>LastBarNumber)
         return true;
      else
         return false;
   }
                                 