I draw a line and a label to mark at the position where the candlestick meets the conditions. Every time a new candlestick that meets this condition appears, the indicator deletes the old line and label to draw a new line and label. However,I would like to move the label to the future position 3 candlesticks away from the last candlestick but still belong to this line to avoid overlapping on the nearby candlesticks. Please take the time to help me! Thank you so much.
The label is overlapping nearby bars:
//@version=5
indicator("My script", overlay=true, max_labels_count = 500)
var lastbar = 0
var linesl = line.new(na,na,na,na)
var label labelsl = na
barsincecond = 0
cross = ta.crossover(close,ta.hma(close,30))
distance = ta.barssince(cross)
if cross
lastbar := bar_index
barsincecond := distance
line.delete(linesl)
linesl := line.new(x1=lastbar, y1=close , x2=lastbar + barsincecond +5, y2=close, extend=extend.right, color = color.rgb(230, 75, 18), style=line.style_solid, width=2)
label.delete(labelsl)
labelsl := label.new(bar_index + barsincecond + 5, close, text='Close ' + str.tostring(math.round((close - close*3*0.01)/syminfo.mintick)*syminfo.mintick), color=color.rgb(230, 75, 18), style=label.style_label_left, textcolor=color.white)
You can use last_bar_index
as the x variable to plot the label at the last bar. If you still want it three bars beyond that, just use last_bar_index+3
The code with the change:
//@version=5
indicator("My script", overlay=true, max_labels_count = 500)
var lastbar = 0
var linesl = line.new(na,na,na,na)
var label labelsl = na
barsincecond = 0
cross = ta.crossover(close,ta.hma(close,30))
distance = ta.barssince(cross)
if cross
lastbar := bar_index
barsincecond := distance
line.delete(linesl)
linesl := line.new(x1=lastbar, y1=close , x2=lastbar + barsincecond +5, y2=close, extend=extend.right, color = color.rgb(230, 75, 18), style=line.style_solid, width=2)
label.delete(labelsl)
labelsl := label.new(last_bar_index, close, text='Close ' + str.tostring(math.round((close - close*3*0.01)/syminfo.mintick)*syminfo.mintick), color=color.rgb(230, 75, 18), style=label.style_label_left, textcolor=color.white)
Edit 1:
Changed the code to make it more consistent and update on every new bar:
//@version=5
indicator("My script", overlay=true, max_labels_count = 500)
var linesl = line.new(na,na,na,na)
var label labelsl = na
barsincecond = 0
cross = ta.crossover(close,ta.hma(close,100))
lastbar = ta.valuewhen(cross, bar_index, 0)
lastclose = ta.valuewhen(cross, close, 0)
if barstate.islast
line.delete(linesl)
linesl := line.new(x1=lastbar, y1=lastclose, x2=last_bar_index, y2=lastclose, extend=extend.none, color = color.rgb(230, 75, 18), style=line.style_solid, width=2)
label.delete(labelsl)
labelsl := label.new(last_bar_index, lastclose, text='Close ' + str.tostring(math.round((lastclose - lastclose*3*0.01)/syminfo.mintick)*syminfo.mintick), color=color.rgb(230, 75, 18), style=label.style_label_left, textcolor=color.white)