Pine line.new, label.new, box.new as MQL5 objects

Short answer

Pine's line.new, label.new and box.new handles become MQL5 chart objects, created with ObjectCreate and addressed by a string name. Use a naming scheme that is unique per drawing and easy to delete as a group, such as a fixed prefix plus the bar time of the anchor.

Pine Script's line.new, label.new and box.new return handles to drawings that the script can move, restyle and delete. MQL5 has the same idea under a different name: chart objects, addressed by a string name and created with ObjectCreate. This guide is for developers converting support and resistance, pivot, zone or signal-label indicators, and covers the mapping, the coordinate conversion and the object lifetime rules that trip most hand conversions.

The mapping

Pine Script v6MQL5 objectNotes
line.new(x1, y1, x2, y2)OBJ_TRENDTwo time/price points; rays via OBJPROP_RAY_RIGHT / OBJPROP_RAY_LEFT
label.new(x, y, text)OBJ_TEXTAnchored to time/price; no bubble shape
box.new(left, top, right, bottom)OBJ_RECTANGLEOne colour for border and fill; no text
table.new(position, cols, rows)grid of OBJ_LABELPixel-positioned from a chart corner
line.set_xy1(l, x, y)ObjectMove(0, name, 0, t, p)Point index 0 or 1
line.set_color(l, c)ObjectSetInteger(0, name, OBJPROP_COLOR, c)
label.set_text(l, s)ObjectSetString(0, name, OBJPROP_TEXT, s)
line.delete(l)ObjectDelete(0, name)

A Pine handle is a value you keep in a variable or an array. In MQL5 the name is the handle, so you need a naming scheme that is unique per drawing and easy to delete as a group: a fixed prefix plus the bar time of the anchor works well.

Converting coordinates

Pine's x coordinate is a bar_index by default, or a UNIX time in milliseconds with xloc = xloc.bar_time. MQL5 objects always anchor to a datetime in seconds. Inside OnCalculate, with arrays in their default oldest-first order, bar_index - 5 is simply time[i - 5]. A millisecond time divides by 1000. A point in the future, such as bar_index + 10 for a projected level, has no entry in time[]; use time[rates_total - 1] + 10 * PeriodSeconds(), and expect it to land differently from TradingView across weekends and session breaks.

The y coordinate is a price in both languages. yloc.abovebar and yloc.belowbar ignore y in Pine and use the bar's high or low; write high[i] or low[i] and set OBJPROP_ANCHOR so the text sits on the correct side.

A worked example: pivot high levels

This Pine indicator draws a level and a price label at every confirmed pivot high and keeps only the last 20 of each.

//@version=6
indicator("Pivot levels", overlay = true, max_lines_count = 20, max_labels_count = 20)
ph = ta.pivothigh(high, 5, 5)
if not na(ph)
    line.new(bar_index - 5, ph, bar_index, ph, color = color.orange, extend = extend.right)
    label.new(bar_index - 5, ph, str.tostring(ph, format.mintick),
              style = label.style_label_down, color = color.orange, textcolor = color.white)

In MQL5 the pivot test is written out, and the line and its label share a name so they can be deleted together:

#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots   0

input int InpLeft  = 5;   // Left bars
input int InpRight = 5;   // Right bars
input int InpMax   = 20;  // Max lines (Pine max_lines_count)

const string PFX = "piv_";
string live[];            // names of drawings still on the chart, oldest first

void Remember(const string nm)
{
   int n = ArraySize(live);
   ArrayResize(live, n + 1);
   live[n] = nm;
   if(n + 1 > InpMax)                       // Pine deletes the oldest
   {
      ObjectDelete(0, live[0]);
      ObjectDelete(0, live[0] + "_lbl");
      ArrayRemove(live, 0, 1);
   }
}

int OnInit()  { return INIT_SUCCEEDED; }

void OnDeinit(const int reason) { ObjectsDeleteAll(0, PFX); }

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(prev_calculated == 0)
   {
      ObjectsDeleteAll(0, PFX);
      ArrayResize(live, 0);
   }
   int first = InpLeft + InpRight;
   int start = MathMax(prev_calculated > 0 ? prev_calculated - 1 : 0, first);
   // Only closed bars: the newest bar (rates_total - 1) is still forming.
   for(int i = start; i < rates_total - 1; i++)
   {
      int p = i - InpRight;                 // candidate pivot bar
      bool isPivot = true;
      for(int k = 1; k <= InpLeft && isPivot; k++)  if(high[p - k] >= high[p]) isPivot = false;
      for(int k = 1; k <= InpRight && isPivot; k++) if(high[p + k] >  high[p]) isPivot = false;
      if(!isPivot) continue;

      string nm = PFX + IntegerToString((long)time[p]);
      ObjectCreate(0, nm, OBJ_TREND, 0, time[p], high[p], time[i], high[p]);
      ObjectSetInteger(0, nm, OBJPROP_COLOR, clrOrange);
      ObjectSetInteger(0, nm, OBJPROP_RAY_RIGHT, true);        // extend.right
      ObjectSetInteger(0, nm, OBJPROP_SELECTABLE, false);

      string lb = nm + "_lbl";
      ObjectCreate(0, lb, OBJ_TEXT, 0, time[p], high[p]);
      ObjectSetString(0, lb, OBJPROP_TEXT, DoubleToString(high[p], _Digits));
      ObjectSetInteger(0, lb, OBJPROP_ANCHOR, ANCHOR_LOWER);   // text sits above the price
      ObjectSetInteger(0, lb, OBJPROP_COLOR, clrOrange);
      Remember(nm);
   }
   return rates_total;
}

The loop stops before the newest bar, so a pivot is only drawn once the bar that confirms it has closed. Each drawing's name is recorded in creation order, and once there are more than 20 the oldest is deleted, which is what Pine's max_lines_count does. OBJ_TEXT has no bubble, so the label's background colour becomes the text colour; white text with no background would be invisible on a light chart. The pivot test here treats an equal high on the left as disqualifying and an equal high on the right as allowed; compare with TradingView on a chart that has equal highs, because tie handling is where hand-written pivots usually disagree.

Boxes and updating a drawing

An OBJ_RECTANGLE has a single colour, used for both the border and the fill. A Pine box with a different border_color and bgcolor therefore needs either a choice of one, or two objects (a filled rectangle plus an unfilled one on top). Box text needs a separate OBJ_TEXT.

// box.new(left, top, right, bottom, border_color = color.blue, bgcolor = color.new(color.blue, 80))
string nm = "zone_" + IntegerToString((long)time[left]);
ObjectCreate(0, nm, OBJ_RECTANGLE, 0, time[left], top, time[right], bottom);
ObjectSetInteger(0, nm, OBJPROP_COLOR, clrLightSteelBlue);  // one colour: border and fill
ObjectSetInteger(0, nm, OBJPROP_FILL, true);
ObjectSetInteger(0, nm, OBJPROP_BACK, true);                // behind the candles

// box.set_right(b, bar_index): move the second anchor point
ObjectMove(0, nm, 1, time[i], bottom);

The common Pine pattern var line l = line.new(...) followed by line.set_xy1 on later bars translates to creating the object once (check ObjectFind(0, name) < 0) and calling ObjectMove afterwards. Do not create a new object on every tick to emulate it.

Lifetime: limits, realtime ticks and clean-up

Three Pine behaviours are easy to miss. First, TradingView keeps at most max_lines_count, max_labels_count and max_boxes_count drawings of each kind, 50 by default and up to 500, and silently deletes the oldest. A conversion without that limit keeps every drawing the script ever made. Second, on the realtime bar Pine rolls back drawings made on earlier ticks of the same bar, so a label created on an unconfirmed signal disappears if the signal goes away. MQL5 keeps every object you create, so either draw on closed bars only, as above, or delete and recreate the live bar's objects on each tick. Third, MQL5 objects outlive the indicator; delete them by prefix in OnDeinit and when prev_calculated is 0, or every reload adds a second copy.

What Stratlate does with drawings

The converter maps line.new to OBJ_TREND, label.new to OBJ_TEXT, box.new to OBJ_RECTANGLE and tables to a grid of OBJ_LABEL objects. Bar-index and millisecond x coordinates are both converted to bar times, with future bar indexes extended by whole periods. It applies the script's max_*_count limits (50 when the script does not set one) by deleting the oldest drawing, places yloc.abovebar and yloc.belowbar labels at the bar's high or low, carries colour, width, line style and extend, and names every object with a pine_ prefix that OnDeinit removes. Setter calls with no object equivalent, such as label.set_style, label.set_size, box.set_text and box.set_border_style, are dropped and listed in the report. Compile the output and compare it with TradingView on the same symbol before relying on it.

Pitfalls

  • Reusing an object name. Names are unique per chart, so a second ObjectCreate with an existing name does not add a new object. Symptom: only the first label ever appears, or later levels never move.
  • Bar index passed where a time is expected. Symptom: every object sits at 1970 on the far left, invisible.
  • Drawing on the forming bar. Symptom: duplicate or stale labels that TradingView would have rolled back.
  • No limit on the number of drawings. Symptom: thousands of objects, a slow terminal, and a chart far busier than TradingView's.
  • Using OBJ_LABEL for a price label. OBJ_LABEL is positioned in pixels and does not move with the chart. Symptom: the label stays fixed while candles scroll under it.
  • No clean-up. Symptom: lines left on the chart after the indicator is removed, or doubled after its inputs change.

FAQ

What is the MQL5 equivalent of line.new?

An OBJ_TREND chart object created with ObjectCreate, with two time and price points. extend.right becomes OBJPROP_RAY_RIGHT, colour OBJPROP_COLOR, width OBJPROP_WIDTH and style OBJPROP_STYLE.

How do I convert bar_index to a time for ObjectCreate?

Inside OnCalculate with oldest-first arrays, bar_index - n is time[i - n]. A future bar index has no time entry, so add whole periods to the newest bar time with PeriodSeconds().

Why do my converted labels pile up on the chart?

TradingView keeps only max_labels_count labels (50 by default) and deletes the oldest. MQL5 keeps every object, so track the names you create and delete the oldest yourself.

Convert drawing-heavy indicators

Paste a Pine indicator that uses lines, labels, boxes or tables; the converter produces the chart-object code, the clean-up and the drawing limits, and reports any styling it could not carry.

Open the converter

Related guides