Search code examples
pine-scriptpine-script-v5

How to get bar_index value on specific date


I am trying to find the bar_index for each time, when I select the time interactively on a specific timeframe.

lets say in 1D timeframe I select the today date via

i_date = input.time(timestamp("23 Aug 2023 00:00 +0300"), "Date", confirm=true)

Then I expect that the corresponding bar_index be 0 for it. In the same way, for the time of yesterday, I expect that bar_index be 1. How can I do this?

I also looked into this question but it is not computing the bar index as I am looking for.


Solution

  • You can check if (time == i_date) is true and store the bar_index in a var.

    //@version=5
    indicator("My script", overlay=true)
    
    i_date = input.time(timestamp("23 Aug 2023 00:00 +0300"), "Date", confirm=true)
    
    var int idx_date = na
    
    idx_date := (time == i_date) ? bar_index : idx_date
    
    plotchar(idx_date, "Idx", "")
    plotchar(bar_index, "bar_index", "")
    

    Here, I selected yesterday as the input. The bar_index in the image points to today. So, idx_date is today - 1. enter image description here