This is a sample code that draw a trendline from 35th bar to the last bar
//@version=5
indicator(title="Quick example: line.new()", overlay=true)
if barstate.islast
line.new(x1=bar_index[35], y1=close[35],
x2=bar_index, y2=close)
It uses barstate.islast
as a condition. I want to know if it is possible to check bar_index
as a condition to draw a line from 35 value to the value that is specified in the conditional.
For example from 35 to 4th bar. Something like this:
//@version=5
indicator(title="Quick example: line.new()", overlay=true)
if bar_index == 4
line.new(x1=bar_index[35], y1=close[35],
x2=bar_index, y2=close)
This code does not work. I am new to Pine Script BTW.
I am not entirely sure whether you want to plot from the 4th bar from the start to the 35th bar from the start, or the 35th bar from the end to the 4th bar from the end, so put both scenarios below:
// From bar number a to bar number b (FROM THE LEFT - START OF HISTORY)
a = 4
b = 35
if barstate.islast
line.new(x1=a, y1=close[bar_index-a], x2=b, y2=close[bar_index-b])
// From bar number c to bar number d (FROM THE RIGHT - END OF HISTORY)
c = 35
d = 4
if barstate.islast
line.new(x1=bar_index[c], y1=close[c], x2=bar_index[d], y2=close[d])
In both scenarios, you will need barstate.islast
because otherwise, it will plot for every bar. x1 and x2 can have the bar_index
itself as an input. x1=0
will be the first bar and x2=bar_index
is the last bar.
I hope this helps!