I want to plot a shape with a text next to my Moving Average every 40 bars, just like that:PLOTTING TEXT EVERY 40 BARS
for i = 0 to 4000 by i + 40
_text1 = label.new(bar_index[i],_m1, style = label.style_label_left, color = color.rgb(255, 82, 82, 100), text = "MA " + str.tostring(_m1value), textcolor = color.white)
but it didnt plot anything
With the way you are doing it, you are starting from the last bar and going to the first bar to place the labels. However, Tradingview has a limitation on the number of labels you can have on your chart.
What's happening is, as you come closer to the first bar, you reach this limit and it starts to delete the old labels which are on the last bar(s).
What you need to do is, start your loop from the first bar and run your for loop till the current bar.
Also, add max_labels_count=500
to your indicator()
call.
All that being said, no need for a for
loop as it will be quite inefficient for your task. Additionally, you cannot delete the old labels so you will have labels in the incorrect position.
You can simply do the following:
//@version=5
indicator("My script", overlay=true, max_labels_count=500)
_ma = ta.sma(close, 20)
if ((bar_index % 40) == 0)
_text1 = label.new(bar_index, _ma, style = label.style_label_left, color = color.rgb(255, 82, 82, 100), text = "MA " + str.tostring(_ma), textcolor = color.white)
plot(_ma)