'How to get last nth bars in a chart ? or how to get total number of bars in a chart?
I know how to get reference of the first three bars in a chart:
firstBar = bar_index == 0
secondBar = bar_index == 1
thirdBar = bar_index == 2
However, I can't figure out how to get the last three bars in a chart.
I guess having the total number of bars would help, but I cannot get that either... For example:
totalNumOfBars = ??????? // cannot get that variable
lastBar = bar_index == totalNumOfBars
previousBar = bar_index == totalNumOfBars - 1
antePreviousBar = bar_index == totalNumOfBars - 2
EDIT
Here is what I tried so far:
// for the 1mn timeframe
var TotalNumOfBars = 0
if time == timestamp(year(timenow), month(timenow), dayofmonth(timenow), hour(timenow), minute(timenow), 0)
TotalNumOfBars := bar_index
but when I try to reuse this variable, it does not seem to work as expected, for example:
plot( bar_index == TotalNumOfBars-2 ? 1 : 0 )
never plots "1" in the chart.
Solution 1:[1]
bar_index is a series and you can access previous value using the history referencing operator
totalNumOfBars = bar_index
previousBar = bar_index[1]
antePreviousBar = bar_index[2]
//@version=4
study("Number of Bars on the chart", overlay = false)
plot(bar_index)
Solution 2:[2]
You can use built-in variables timenow and time to calculate distance from last bar and current bar and in this way estimate total bar count. But this calculation will be inaccurate because of holidays and so on.
Look at this script as an example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | svaor |

