i will appreciate your help!

 

i converted a code from tradingview to mql5, but the drawing is not exactly the same, can you find the bug?

tradingview code:

//@version=5
strategy("TYX.EShinX-连续K线原始供给需求块策略 V3.7 ",overlay = true,
     max_lines_count = 500,max_labels_count = 500,max_boxes_count = 500,

     initial_capital = 1000000 , 
     currency = currency.AUD , 
     default_qty_value = 100000 , 
     default_qty_type = strategy.cash,
     pyramiding = 1 ,
     commission_value = 3.5 ,
     commission_type = strategy.commission.cash_per_order,
     slippage = 0 , 
     margin_long = 0,
     margin_short = 0 ,
     calc_on_order_fills = false,
     calc_on_every_tick =true )



var bool gbroken=false
var bool rbroken=false



//-----------------------------------[MARKET STRUCTURE INDICATOR]-----------------------------------{ 
//---------------------------
//market breaking indicator 
//
//-----------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(5, 'Swings Period', minval = 2,group = 'Market Structure Settings')
breaks = input.int(1, 'Maximum Breaks', minval = 1,group = 'Market Structure Settings')
maxDuration = input(1000, 'Breaker Maximum Duration',group = 'Market Structure Settings')

//Style
bullCss = input(#089981, 'Bullish MS', inline = 'bull', group = 'Market Structure Settings')
bullBreakCss = input(#f23645, 'Breaker', inline = 'bull', group = 'Market Structure Settings')

bearCss = input(#f23645, 'Bearish MS', inline = 'bear', group = 'Market Structure Settings')
bearBreakCss = input(#089981, 'Breaker', inline = 'bear', group = 'Market Structure Settings')

//-----------------------------------------------------------------------------}
//UDT { /// MSS MSB 
//-----------------------------------------------------------------------------{
type breaker
    line level
    int  breaks = 0

//-----------------------------------------------------------------------------}
//Bullish Breaker
//-----------------------------------------------------------------------------{
var phx = 0  
var phcross = false
var bullms = array.new<breaker>(0)
var os = 0

n = bar_index
ph = fixnan(ta.pivothigh(length, length))

if ph != ph[1]
    phx := n-length
    phcross := false

//Test for bullish market structure
if close > ph and not phcross
    line.new(phx, ph, n, ph, color = bullCss)
    gbroken:=true
    //MS label
    label.new(int(math.avg(phx, n)), ph, os == -1 ? 'MSS' : 'MSB'
      , textcolor = bullCss
      , color = color(na)
      , size = size.small
      , style = label.style_label_down)

    bullms.unshift(breaker.new(line.new(n, ph, n, ph, color = bullBreakCss, style = line.style_dotted)))
    phcross := true

    if bullms.size() > 100
        bullms.pop()
    
    os := 1

//Iterate trough existing bullish structures and test for breaks
break_down = false

//-----------------------------------------------------------------------------}
//Bearish Breaker
//-----------------------------------------------------------------------------{
var plx = 0  
var plcross = false
var bearms = array.new<breaker>(0)

pl = fixnan(ta.pivotlow(length, length))

if pl != pl[1]
    plx := n-length
    plcross := false

//Test for bearish market structure
if close < pl and not plcross
    line.new(plx, pl, n, pl, color = bearCss)
    rbroken:=true

    //MS label
    label.new(int(math.avg(plx, n)), pl, os == 1 ? 'MSS' : 'MSB'
      , textcolor = bearCss
      , color = color(na)
      , size = size.small
      , style = label.style_label_up)

    bearms.unshift(breaker.new(line.new(n, pl, n, pl, color = bearBreakCss, style = line.style_dotted)))
    plcross := true

    if bearms.size() > 100
        bearms.pop()
    
    os := -1

//Iterate trough existing bearish structures and test for breaks
break_up = false

if bearms.size() > 0
    for i = bearms.size()-1 to 0
        get = bearms.get(i)
        get.level.set_x2(n)
        
        if close > get.level.get_y2() and open < get.level.get_y2()
            get.breaks += 1

            if get.breaks == breaks
                bearms.remove(i)
                break_up := true
        else if (n - get.level.get_x1()) >= maxDuration
            bearms.remove(i).level.delete()

//Resistance events


var bool bear=false
var bool bull=false

bull:=close>open?true:false
bear:=open>close?true:false

var bullcnt=0
var bearcnt=0



if not (bull or bear)
    bullcnt:=0
    bearcnt:=0


var float bullh=0
var float bulll=0
var float bearh=0
var float bearl=0


var bool gstopper=false
var bool rstopper=false



if bull //and not gstopper
    rstopper:=false
    rbroken:=false
    if bullcnt==0
        bullh:=high[1]
        bulll:=low[1] 

    bullcnt:=bullcnt+1
    bearcnt:=0

if bear
    gbroken:=false 
    gstopper:=false
    if bearcnt==0
        bearh:=high[1]
        bearl:=low[1]

    bearcnt:=bearcnt+1
    bullcnt:=0

var bullbox=array.new_box()
var bearbox=array.new_box()

var box gbox=na
var box rbox=na
clrg=input.color(color.rgb(76, 175, 79, 50),"demand box color",group = "Demand/Supply style settings",tooltip = "background color of the demand zones")
clrr=input.color(color.rgb(255, 82, 82, 50),"supply box color",group = "Demand/Supply style settings",tooltip = "background color for the supply zones")
clrt=input.color(color.black,"text color",tooltip = "select the color of the text of label and box , set opacity to 0% to make the text disappear",group="Demand/Supply style settings")
clrl=input.color(color.rgb(151, 105, 162),"label color",tooltip = "select the background color of the label , set opacity to 0% to make the text disappear",group="Demand/Supply style settings")


mincnt=input(4,"minimum number of consecutive bars",tooltip = "this is the minimum number of consecutive bars[of same color] that must be present to qualify for a demand/supply zone",group="Demand/Supply style settings")


bool ea=input(true,"enable alerts",group="Demand/Supply style settings")
bool sa=input(true,"Strategy alerts",group="Demand/Supply style settings")

bool el=input(false,"enable labels to indicate the zones that were broken",group ="Demand/Supply style settings",tooltip = "enabling this checkbox will show labels which indicates the zones/bands that were broken")
// plot(bullcnt,color = color.green)
// plot(bearcnt,color=color.red)


//--------------------------------------------------------------------------------------------------------
type levels 
    float top 
    float bottom 
    int   index = bar_index



var demand = array.new<levels>()
var supply = array.new<levels>()


//--------------------------------------------------------------------------------------------------------

//drawing boxes



if bullcnt>=mincnt and not gstopper and gbroken
    gbox:=box.new(bar_index[bullcnt],bullh,bar_index,bulll,bgcolor = clrg,extend=extend.none,border_color = clrg,text = "DEMAND",text_color = clrt,text_halign = text.align_left)
    array.push(bullbox,gbox)
    gstopper:=true
    // if ea
    //     alert("Demand box created")
    gbroken:=false

    demand.unshift(levels.new(bullh,bulll))



if bearcnt>=mincnt and not rstopper and rbroken
    rbox:=box.new(bar_index[bearcnt],bearh,bar_index,bearl,bgcolor = clrr,extend=extend.none,border_color = clrr,text="SUPPLY",text_color=clrt,text_halign = text.align_left)
    array.push(bearbox,rbox)
    rstopper:=true
    // if ea
    //     alert("supply box created")
    rbroken:=false

    supply.unshift(levels.new(bearh,bearl))


mql5 code in first comment.

tradingview chart:

mt5 chart:


 
//+------------------------------------------------------------------+
//|                                                    indicator.mq5 |
//|                                      Copyright 2024, Issam Kadhi |
//|                      https://www.upwork.com/freelancers/issamk31 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, Issam Kadhi"
#property link      "https://www.upwork.com/freelancers/issamk31"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots 0

struct array{int x1; double y1; int x2; double y2; int breaks;};

input int length_ = 5;//Swings Period
int length=MathMax(2,length_);
input int breaks_ = 1;//Maximum Breaks
int breaks=MathMax(1,breaks_);
input int maxDuration = 1000;//Breaker Maximum Duration
input color bullCss = clrGreen;//Bullish MS
input color bullBreakCss = clrGreen;//Breaker
input color bearCss = clrRed;//Bearish MS
input color bearBreakCss = clrRed;//Breaker
input color clrg=clrGreen;//demand box color
input color clrr=clrRed;//supply box color
input color clrt=clrBlack;//text color
input color clrl=clrFireBrick;//label color
input int mincnt=4;//minimum number of consecutive bars
input bool ea=true;//enable alerts
input bool sa=true;//Strategy alerts
input bool el=false;//enable labels to indicate the zones that were broken
input bool extend = false;//Extend Boxes And Delete Broken Ones

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   
//---
   return(INIT_SUCCEEDED);
  }
void OnDeinit(const int reason)
{

   ObjectsDeleteAll(0,prefix);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
double pivotlow(int period1, int period2, int i)
{
   if(i<=period2)return 0;
   int pos=iLowest(_Symbol,PERIOD_CURRENT,MODE_LOW,period1+period2+1,i-period2);
   return pos==i?INT_MAX:iLow(_Symbol,PERIOD_CURRENT,pos);
}
double pivothigh(int period1, int period2, int i)
{
   if(i<=period2)return INT_MAX;//Print(i);
   int pos=iHighest(_Symbol,PERIOD_CURRENT,MODE_HIGH,period1+period2+1,i-period2);//Print(pos);
   return pos==i?0:iHigh(_Symbol,PERIOD_CURRENT,pos);
}
string prefix="MSI-";
int count=0;
datetime lastTimeGreen=TimeCurrent();
void lineGreen(int x2, double y2, color couleur, int os)
{
   int i,pos=iBarShift(_Symbol,PERIOD_CURRENT,lastTimeGreen);
   for(i=x2-1;i>=pos;i--)
      if(y2<=MathMax(iOpen(_Symbol,PERIOD_CURRENT,i),iClose(_Symbol,PERIOD_CURRENT,i))
      &&y2>=MathMin(iOpen(_Symbol,PERIOD_CURRENT,i),iClose(_Symbol,PERIOD_CURRENT,i)))
         break;
   
   if(i<pos)return;
   lastTimeGreen=iTime(_Symbol,PERIOD_CURRENT,x2);
      
   string name=prefix+IntegerToString(x2);
   if(ObjectFind(0,name)<0)
      ObjectCreate(0,name,OBJ_TREND,0,0,0);
      
   ObjectSetDouble(0,name,OBJPROP_PRICE,0,y2);
   ObjectSetDouble(0,name,OBJPROP_PRICE,1,y2);
   ObjectSetInteger(0,name,OBJPROP_TIME,0,iTime(_Symbol,PERIOD_CURRENT,i));
   ObjectSetInteger(0,name,OBJPROP_TIME,1,iTime(_Symbol,PERIOD_CURRENT,x2));
   ObjectSetInteger(0,name,OBJPROP_RAY,false);
   ObjectSetInteger(0,name,OBJPROP_COLOR,couleur);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,5);

   labelGreen((x2+i)/2, y2, os == -1 ? "MSS" : "MSB",  couleur);
   
   ChartRedraw();
}
datetime lastTimeRed=TimeCurrent();
void lineRed(int x2, double y2, color couleur, int os)
{
   int i,pos=iBarShift(_Symbol,PERIOD_CURRENT,lastTimeRed);
   for(i=x2-1;i>=pos;i--)
      if(y2<=MathMax(iOpen(_Symbol,PERIOD_CURRENT,i),iClose(_Symbol,PERIOD_CURRENT,i))
      &&y2>=MathMin(iOpen(_Symbol,PERIOD_CURRENT,i),iClose(_Symbol,PERIOD_CURRENT,i)))
         break;
   
   if(i<pos)return;
   lastTimeRed=iTime(_Symbol,PERIOD_CURRENT,x2);
      
   string name=prefix+IntegerToString(x2);
   if(ObjectFind(0,name)<0)
      ObjectCreate(0,name,OBJ_TREND,0,0,0);
      
   ObjectSetDouble(0,name,OBJPROP_PRICE,0,y2);
   ObjectSetDouble(0,name,OBJPROP_PRICE,1,y2);
   ObjectSetInteger(0,name,OBJPROP_TIME,0,iTime(_Symbol,PERIOD_CURRENT,i));
   ObjectSetInteger(0,name,OBJPROP_TIME,1,iTime(_Symbol,PERIOD_CURRENT,x2));
   ObjectSetInteger(0,name,OBJPROP_RAY,false);
   ObjectSetInteger(0,name,OBJPROP_COLOR,couleur);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,5);

   labelRed((x2+i)/2, y2, os == -1 ? "MSS" : "MSB",  couleur);
   
   ChartRedraw();
}
void labelRed(int x1, double y1, string text, color couleur)
{
   string name=prefix+IntegerToString(x1)+"RED";
   if(ObjectFind(0,name)<0)
      ObjectCreate(0,name,OBJ_LABEL,0,0,0);
   
   int x,y;
   ChartTimePriceToXY(0,0,iTime(_Symbol,PERIOD_CURRENT,x1),y1,x,y);
   
      
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,name,OBJPROP_COLOR,couleur);
   ObjectSetInteger(0,name,OBJPROP_FONTSIZE,10);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,5);
   
   ChartRedraw();
}
void box(int x,double y, int x2, double y2, color couleur,string text, color textColor)
{
   string name=prefix+IntegerToString(x)+"BOX";
   if(ObjectFind(0,name)<0)
      ObjectCreate(0,name,OBJ_RECTANGLE,0,0,0);

   ObjectSetDouble(0,name,OBJPROP_PRICE,0,y);
   ObjectSetDouble(0,name,OBJPROP_PRICE,1,y2);
   ObjectSetInteger(0,name,OBJPROP_TIME,0,iTime(_Symbol,PERIOD_CURRENT,x));
   ObjectSetInteger(0,name,OBJPROP_TIME,1,iTime(_Symbol,PERIOD_CURRENT,x2));
   ObjectSetInteger(0,name,OBJPROP_COLOR,couleur);
   ObjectSetInteger(0,name,OBJPROP_FILL,true);

   name=prefix+IntegerToString(x)+"BOXLABEL";
   if(ObjectFind(0,name)<0)
      ObjectCreate(0,name,OBJ_LABEL,0,0,0);
   
   int x1,y1;
   ChartTimePriceToXY(0,0,iTime(_Symbol,PERIOD_CURRENT,x),y,x1,y1);

   
      
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x1);
   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y1);
   ObjectSetInteger(0,name,OBJPROP_COLOR,textColor);
   ObjectSetInteger(0,name,OBJPROP_FONTSIZE,5);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,5);
   ObjectSetString(0,name,OBJPROP_TEXT,text);
   
   ChartRedraw();

}
void labelGreen(int x1, double y1, string text, color couleur)
{
   string name=prefix+IntegerToString(x1)+"GREEN";
   if(ObjectFind(0,name)<0)
      ObjectCreate(0,name,OBJ_LABEL,0,0,0);
   
   int x,y;
   ChartTimePriceToXY(0,0,iTime(_Symbol,PERIOD_CURRENT,x1),y1,x,y);
   
      
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,name,OBJPROP_COLOR,couleur);
   ObjectSetInteger(0,name,OBJPROP_FONTSIZE,10);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,5);
   
   ChartRedraw();
}
datetime bars;
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[])
  {
//-----------------------------------------------------------------------------{
   if(bars!=time[rates_total-2])ObjectsDeleteAll(0,prefix);
   bars=time[rates_total-2];
   //ObjectsDeleteAll(0,prefix);
   ArraySetAsSeries(time,true);
   
   lastTimeRed=TimeCurrent();
   lastTimeGreen=TimeCurrent();
   
   ArraySetAsSeries(close,true);
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);

   
   int os = 0;
   double ph[];
   ArrayResize(ph,rates_total);
   double pl[];
   ArrayResize(pl,rates_total);
   int phx = 0;
   int plx = 0;  
   bool phcross = false;
   bool plcross = false;
   bool rbroken=false;
   bool gbroken=false;




   for(int i=0;i<rates_total-1;i++)
   {
      int n = i;
      ph[i] = pivothigh(length, length, i);
      
      if(ph[i] != ph[i+1])
      {
          phx = n+length;
          phcross = false;
      }

      //Test for bullish market structure
      if(close[i] > ph[i] && !phcross)
      {//Print(1);
          lineGreen(n, !ph[i]?high[i]:ph[i], bullCss, os);
          gbroken=true;
          phcross = true;
          os = 1;
      }
      //-----------------------------------------------------------------------------{
      
      pl[i] = pivotlow(length, length,i);
      
      if(pl[i] != pl[i+1])
      {
          plx = n+length;
          plcross = false;
      }
      //Test for bearish market structure
      if(close[i] < pl[i] && !plcross)
      {
          lineRed(n, pl[i]==INT_MAX?low[i]:pl[i], bearCss, os);
          rbroken=true;
          plcross = true;
          os = -1;
      }
      //Iterate trough existing bearish structures and test for breaks
   }
   
   int last=-1;
   for(int i=rates_total-1;i>=0;i--)
   {
      string name2=prefix+IntegerToString(i)+"GREEN";
      if(ObjectFind(0,name2)>=0)
      {
         if(last==1)
            ObjectSetString(0,name2,OBJPROP_TEXT,"MSS");
         else
            ObjectSetString(0,name2,OBJPROP_TEXT,"MSB");
         last=0;
      }
      name2=prefix+IntegerToString(i)+"RED";
      if(ObjectFind(0,name2)>=0)
      {
         if(last==0)
            ObjectSetString(0,name2,OBJPROP_TEXT,"MSS");
         else
            ObjectSetString(0,name2,OBJPROP_TEXT,"MSB");
         last=1;
      }   
   }
   
   ChartRedraw();

   bool bear=false;
   bool bull=false;
   int bullcnt=0;
   int bearcnt=0;

   double bullh=0;
   double bulll=0;
   double bearh=0;
   double bearl=0;


   bool gstopper=false;
   bool rstopper=false;

   os = 0;
   ArrayResize(ph,rates_total);
   ArrayResize(pl,rates_total);
   phx = 0;
   plx = 0;  
   phcross = false;
   plcross = false;
   rbroken=false;
   gbroken=false;


   for(int i=rates_total-2;i>=0;i--)
   {         
      if(ph[i] != ph[i+1])
          phcross = false;

      //Test for bullish market structure
      if(close[i] > ph[i] && !phcross)
      {//Print(1);
          gbroken=true;
          phcross = true;
      }
      
      
      if(pl[i] != pl[i+1])
          plcross = false;

      //Test for bearish market structure
      if(close[i] < pl[i] && !plcross)
      {
          rbroken=true;
          plcross = true;
      }

      bull=close[i]>open[i]?true:false;
      bear=open[i]>close[i]?true:false;


      if(!(bull || bear))
      {
         bullcnt=0;
         bearcnt=0;
      }

      if(bull )//and not gstopper
      {
         rstopper=false;
         rbroken=false;
         if(bullcnt==0)
         {
             bullh=high[i+1];
             bulll=low[i+1];
         }
         bullcnt=bullcnt+1;
         bearcnt=0;
      }

      if(bear)
      {
         gbroken=false; 
         gstopper=false;
         if(bearcnt==0)
         {
            bearh=high[i+1];
            bearl=low[i+1];
         }
         bearcnt=bearcnt+1;
         bullcnt=0;
      }

      if(bullcnt>=mincnt && !gstopper && gbroken)
      {
         box(i+bullcnt,bullh,i,bulll,clrg,"DEMAND", clrt);
         gstopper=true;
         gbroken=false;
      }

      if(bearcnt>=mincnt && !rstopper && rbroken)
      {
         box(i+bearcnt,bearh,i,bearl,clrr,"SUPPLY", clrt);
         rstopper=true;
         rbroken=false;
      }
   }




   return(rates_total);
  }
//+------------------------------------------------------------------+
 

You shouldn't use the iOpen/iTime functions in OnCalculate because they will not sequence to the correct bar unless you use iBarShift.

Instead of using iOpen and iTime, use the "time" and "open" buffer which is in the signature of OnCalculate

You can set the buffers to series if you want to make [0] the latest index.