FAQ

How to Display Labels / Lines for the future bars in PineScript?

How to Display Labels / Lines for the future bars in PineScript?

Sometimes you might want to display labels in TradingView for the future bars so they won’t intersect with the latest bars. Also, it might be useful to plot lines into the future as a projection. From first sight, it’s not obvious how to do that in PineScript. In this article, I will show you an example of how you can do that.

First, let’s look at the code to plot a single label for the last bar:

l = label.new(bar_index, high, tostring(close))
label.delete(l[1])

This will give us an expected result:

If we want to move the label to the right we have to put a negative index to bar_index, for example, bar_index[-5]. But that doesn’t work in TradingView and will give us “Index can’t be a negative value (-5)” error.

Fortunately, you can use time as an x-axis for the label to bypass this issue. For that, I will use xloc.bar_time as xloc and will compute bar size in milliseconds to shift my label to the right. Here is an example:

dt = time - time[1]
l = label.new(time + 5 * dt, high, tostring(close), xloc = xloc.bar_time)
label.delete(l[1])

This will plot a label 5 bars into the future:

As you can see I use a variable dt to store the distance between 2 bars open times. After that, I’m using this variable as a multiplier to calculate the time I want to plot by the label at: time + 5 * dt

Same approach works for line objects as well:

dt = time - time[1]
l = line.new(time + 5 * dt, high, time + 10 * dt, high,  xloc = xloc.bar_time)
line.delete(l[1])

This will plot us a line for the future bars:

As you can see it’s a pretty simple trick that can allow you to plot lines and labels for the future bars. However, this works really well only for the instruments like crypto trading 24/7. If you want to make reliable solutions for stocks with certain trading sessions it might require bit more calculations for you. In one of my next articles, I’ll try to cover it as well.


Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png

Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news