Reputation: 258
I am wondering if there is a way to get the number of bar
of the timeframe that my chart is in it from the beginning.
My goal is to use the final bar_index as a variable in my code, but the issue is that the bar index will increase by time. so I was wonderingwhat would be the solution here.
To explain more I am providing the example here.
Lets say I am in 2H
charts and there are in total 20K bar_index
there, if I know the 20K for the beginning, I can then provide the condition that whatever total bars that my chart will have should be divided with n
and then just apply my functions on a range of the results. but I dont know how I can know the total number of bars in the chart from the beginning...
I guess my question can also be ask as follow: can we somehow at the beginning of the code (not at the end via barstate.islast
) know what is the total number of bars in the chart based on the timeframe we are in?
Upvotes: 1
Views: 1630
Reputation: 59586
The bar_index
variable has been introduced in Pine Script 5. It gives you the current bar number starting with 0.
Don't forget the code is executed at each bar. So, if you test first against barstate.islast
and then retrieve the bar_index
value, the total number of bars will be available at the beginning of your code (i.e., when it is executed for the last time).
Then, you can reference any past bars (or x
positions) once in the last bar to draw or compute your function.
Upvotes: 0
Reputation: 316
Workaround is: Assuming the data has no hole in them (that's why i use the>=15 min in my case since 1 min usually has little data in most of charts)
we can do this:
var timeframeinmin = 15
if barstate.isfirst
maxBarIndex := int((timenow - time[0]) / (60000 * timeframeinmin))
plot(maxBarIndex, title="Max Bar Index Since Beginning", color=color.blue, linewidth=2)
Upvotes: 0
Reputation: 21159
No, this is not possible to know. Your script will be executed on each bar starting from the first very bar. All the built-in variables such as bar_index
will also be calculated on each bar. So, you cannot get that information until you wait till the last bar.
You have two options:
Upvotes: -1