Reputation: 31
I'm trying to align the text I have above a line so that the first letter in the label aligns perfectly with the left edge of the line regardless of the timeframe we are viewing. Here is a link to the image showing how it currently appears.
Here's the code:
draw_adr_hilo(hi_level, lo_level, res, adr, level_color) =>
var line hi_line = na
var line lo_line = na
if new_bar(res)
line.set_x2(hi_line, bar_index)
line.set_x2(lo_line, bar_index)
line.set_extend(hi_line, extend.none)
line.set_extend(lo_line, extend.none)
hi_line := line.new(bar_index, hi_level, bar_index, hi_level, extend=extend.right, color=level_color)
lo_line := line.new(bar_index, lo_level, bar_index, lo_level, extend=extend.right, color=level_color)
label.new(bar_index, hi_level, "Average Range: " + tostring(to_pips(adr),'#.##') + " pips", xloc.bar_index, yloc.price, style=label.style_none, textcolor=color.white)
if not na(hi_line) and line.get_x2(hi_line) != bar_index
line.set_x2(hi_line, bar_index)
line.set_x2(lo_line, bar_index)
I tried manually changing the "bar_index" from 0 to another number however the text in the label kept moving further to the left, away from the line.
I also have an additional question. I will like to have two lines of text above the line. For example, I currently have one label called the "Average Range", can you provide guidance needed to add another label either above or below the current one? So it will be "Average Range" and the price of the hi_line above or below.
Thanks so much, I appreciate you help!
Upvotes: 1
Views: 3454
Reputation: 8789
Precise horizontal alignment will be problematic because text is centered in the label. Looks good here but will not be perfect at all chart TFs. See lbl3
in this code.
For extra lines above, answer above will work. For lines both above and below the line, see lbl1
and lbl2
in code:
//@version=4
study("Labels on Lines", "", true)
yp = highest(20)
newYp = change(yp)
if newYp
// Labels up and down are used to print above and below line, with invisible color so we don't see them.
lbl1 = label.new(bar_index, yp, "Above1\nAbove2", color=#00000000, style=label.style_labeldown, textcolor=color.green)
lbl2 = label.new(bar_index, yp, "Below1\nBelow2", color=#00000000, style=label.style_labelup, textcolor=color.red)
// Label none is used here because aligns vertically above line.
// Left padding of text with spaces must vary with length of string since text is centered.
// Horizontal alignment won't always be perfect.
lbl3 = label.new(bar_index, yp, " On Line", style=label.style_none, size=size.large, textcolor=color.orange, xloc=xloc.bar_index)
if newYp[1]
// Delete previous label when there is a consecutive new high, as there's no line plot in that case.
label.delete(lbl1[1])
label.delete(lbl2[1])
label.delete(lbl3[1])
plot(newYp ? na : yp, "", color.gray, 2, plot.style_linebr, offset = -1)
Upvotes: 2