label.new() in MQL5: OBJ_TEXT, anchors, limits and deletion

Short answer

label.new() becomes a chart object: OBJ_TEXT anchored at a time and price, or OBJ_LABEL pinned to a screen position. Objects are addressed by a unique name instead of a handle and nothing deletes them for you, so naming, anchoring and cleanup with ObjectDelete are the real work.

label.new() places a piece of text at a bar and a price and returns a handle the script can move, restyle or delete later. In MQL5 the same thing is a chart object: OBJ_TEXT for text anchored at a time and price, OBJ_LABEL for text pinned to a screen position in pixels. Objects are addressed by a unique name instead of a handle, nothing deletes them for you, and they are not part of the indicator's data, so the conversion is mostly about naming, anchoring and cleanup rather than about the drawing itself.

What label.new() computes

label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip) creates a label whose x is a bar index (xloc.bar_index, the default) or a UNIX time in milliseconds (xloc.bar_time), and whose y is a price (yloc.price) or is ignored in favour of the bar's high or low (yloc.abovebar, yloc.belowbar). style picks a bubble shape such as label.style_label_up or plain text with label.style_none; color is the bubble, textcolor the text. The call returns a label id; label.set_text, label.set_xy, label.set_color and label.delete take it. A script keeps at most max_labels_count labels (default 50, maximum 500) and TradingView deletes the oldest automatically. Labels created on the realtime bar are rolled back on each tick and recreated, which is why the var label l = na / label.delete(l) idiom exists for a single label that follows the last bar.

The MQL5 equivalent

The Pine version writes "Buy" under every EMA crossover and keeps one price label on the last bar.

//@version=6
indicator("Label demo", overlay=true, max_labels_count=50)
up = ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
if up
    label.new(bar_index, low, "Buy", style=label.style_label_up, color=color.green, textcolor=color.white)
var label last = na
if barstate.islast
    label.delete(last)
    last := label.new(bar_index, high, str.tostring(close), xloc=xloc.bar_index, yloc=yloc.price)

In MQL5 each label is an OBJ_TEXT named after the bar time, so a re-run of the same bar updates the existing object rather than adding a second one. The max_labels_count limit is a ring of names: when it overflows, the oldest object is deleted. The last-bar label is a single object moved with ObjectMove, the MQL5 form of the var / delete / new idiom.

#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots   0

input int InpFast      = 9;    // Fast EMA
input int InpSlow      = 21;   // Slow EMA
input int InpMaxLabels = 50;   // max_labels_count

int    hFast, hSlow;
string gNames[];      // ring of label names, oldest first (Pine deletes the oldest itself)

// label.new(bar_index, low, "Buy", yloc=yloc.price): an OBJ_TEXT anchored at (time, price)
void LabelNew(const datetime t, const double price, const string text, const color clr, const bool above)
{
   string nm = "lbl_" + IntegerToString((long)t);
   if(ObjectFind(0, nm) >= 0)              // same bar re-run: move it, do not duplicate it
     {
      ObjectMove(0, nm, 0, t, price);
      return;
     }
   if(!ObjectCreate(0, nm, OBJ_TEXT, 0, t, price))
      return;
   ObjectSetString (0, nm, OBJPROP_TEXT, text);
   ObjectSetInteger(0, nm, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, nm, OBJPROP_FONTSIZE, 9);
   ObjectSetInteger(0, nm, OBJPROP_ANCHOR, above ? ANCHOR_LOWER : ANCHOR_UPPER);
   ObjectSetInteger(0, nm, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, nm, OBJPROP_HIDDEN, true);   // keep it out of the object list
   int n = ArraySize(gNames);
   ArrayResize(gNames, n + 1);
   gNames[n] = nm;
   if(n + 1 > InpMaxLabels)                 // Pine's limit: the oldest label disappears
     {
      ObjectDelete(0, gNames[0]);
      ArrayRemove(gNames, 0, 1);
     }
}

int OnInit()
{
   hFast = iMA(_Symbol, _Period, InpFast, 0, MODE_EMA, PRICE_CLOSE);
   hSlow = iMA(_Symbol, _Period, InpSlow, 0, MODE_EMA, PRICE_CLOSE);
   return (hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE) ? INIT_FAILED : 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[])
{
   if(BarsCalculated(hFast) < rates_total || BarsCalculated(hSlow) < rates_total)
      return 0;
   static double f[], s[];
   if(CopyBuffer(hFast, 0, 0, rates_total, f) < 0 || CopyBuffer(hSlow, 0, 0, rates_total, s) < 0)
      return 0;
   int start = MathMax(prev_calculated - 1, 1);
   for(int i = start; i < rates_total; i++)
     {
      bool up = f[i] > s[i] && f[i - 1] <= s[i - 1];
      if(up)
         LabelNew(time[i], low[i], "Buy", clrLimeGreen, false);
      else if(i == rates_total - 1)
         ObjectDelete(0, "lbl_" + IntegerToString((long)time[i]));   // signal vanished on the live bar
     }
   // var label last = na ... label.delete(last); last := label.new(...): one object, moved each tick
   int last = rates_total - 1;
   string nm = "lbl_last";
   if(ObjectFind(0, nm) < 0)
      ObjectCreate(0, nm, OBJ_TEXT, 0, time[last], high[last]);
   else
      ObjectMove(0, nm, 0, time[last], high[last]);
   ObjectSetString (0, nm, OBJPROP_TEXT, DoubleToString(close[last], _Digits));
   ObjectSetInteger(0, nm, OBJPROP_ANCHOR, ANCHOR_LOWER);
   return rates_total;
}

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

Argument by argument: x with xloc.bar_index becomes time[i] inside OnCalculate (or iTime(_Symbol, _Period, shift) elsewhere); xloc.bar_time values are milliseconds and divide by 1000 to become a datetime. y is the price argument of ObjectCreate; yloc.abovebar and yloc.belowbar mean passing high[i] or low[i] with OBJPROP_ANCHOR set to ANCHOR_LOWER or ANCHOR_UPPER. textcolor is OBJPROP_COLOR, size is OBJPROP_FONTSIZE, tooltip is OBJPROP_TOOLTIP. The coloured bubble of label.style_label_up has no text-object equivalent; the usual compromise is coloured text, or an OBJ_ARROW glyph plus an OBJ_TEXT.

Where the two differ

TopicPine ScriptMQL5
IdentityOpaque handle returned by label.newA unique string name, at most 63 characters; creating an existing name fails
Limitmax_labels_count, oldest removed automaticallyNo limit; you delete old objects yourself
LifetimeRemoved with the scriptStays on the chart after the indicator is removed unless OnDeinit deletes it
Realtime barRolled back each tick, so label.new in global scope makes one labelNothing is rolled back; name the object after the bar time and update it in place
Screen-anchored textNot a label; use tableOBJ_LABEL with OBJPROP_CORNER and pixel distances
Bubble styleslabel.style_label_up and similarNone; coloured text, or a glyph object plus text
Strategy TesterLabels appear in backtestsObjects are drawn only in visual mode
Reading backlabel.get_x, label.get_textObjectGetInteger(OBJPROP_TIME), ObjectGetString(OBJPROP_TEXT)

What the Stratlate converter emits

label.new(x, y, text) is emitted as pine_label_new(x, y, text), a runtime helper that creates an OBJ_TEXT named pine_label_N at the time of bar x (a millisecond value from xloc.bar_time is recognised by its size) and returns an integer id, so label.delete, label.set_text and label.set_xy map onto pine_label_delete, pine_label_set_text and pine_label_set_xy with that id; yloc.abovebar and yloc.belowbar go through pine_label_new_at_bar, which reads the bar's high or low. Colour, text colour, the up/down style as an anchor, size and tooltip are applied by pine_label_style; the bubble shape itself is not drawn. The runtime keeps a live list capped at 50 labels (the max_labels_count default) and deletes the oldest, and it rolls back objects created on the forming bar before each re-run so the var / delete / new idiom behaves as in Pine. A plain label script converts CLEAN; compile it and check the chart, because object placement is where platform differences show.

Pitfalls

  • Naming objects with a counter. Every recalculation (a new tick, a chart timeframe switch, prev_calculated == 0) creates fresh objects on the same bars until the chart is covered.
  • Forgetting ObjectsDeleteAll(0, prefix) in OnDeinit. The labels survive the removal of the indicator and reappear on every chart template that includes them.
  • Using ANCHOR_UPPER for text above a bar. The anchor names the point of the text that sits at the price, so text above a high needs ANCHOR_LOWER.
  • Passing a Pine millisecond time straight into ObjectCreate. The object lands in the year 50000; divide by 1000 first.
  • Deleting and recreating the last-bar label on every tick. It flickers and costs time; ObjectMove plus ObjectSetString on one object is enough.
  • Expecting the objects to show up in a non-visual Strategy Tester run. They do not exist there, so an EA must not read them back for its logic.

FAQ

Should I use OBJ_TEXT or OBJ_LABEL?

OBJ_TEXT for anything tied to a bar and a price, which is every label.new with yloc.price, abovebar or belowbar. OBJ_LABEL sits at a pixel offset from a chart corner and does not scroll with price, which makes it the building block for Pine tables, not for labels.

How do I reproduce max_labels_count?

Keep the object names in an array in creation order; after each ObjectCreate, if the array is longer than the limit, ObjectDelete the first name and remove it from the array. That is exactly what TradingView does with the oldest label.

Why do my converted labels pile up on the last bar?

The x value was taken as a bar index but passed where a time is expected, or the other way round. A bar index must be mapped through time[i]; a bar index larger than the last bar (a label in the future) needs time[last] + n * PeriodSeconds().

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related