0

I want to calculate average price of a specific bar which I get by using confirm=true parameter from input.time. To calculate average I need high and low of that bar and to get that bar index of the selected bar is required. To get that bar index I wrote a custom function which calculates bar index but it calculates from left to right (from very 1st bar till the selected bar) and not like how inbuilt bar index function calculates i.e. from right to left ( from lastest bar till selected bar).

This is the custom function i wrote to calculate bar index...

bar_1   = input.time (title = "Bar 1", defval = 0900, inline = "1", confirm = true)

index(t_) =>
    var int i = na
    if t_ < time
        i := bar_index
    i

// Calculating bar index
a_ = index(bar_1)

// Get high price
h_ = high[a_]

As I explained earlier it does not calculate bar index like the inbuilt function in pine script and also it does not work if i try to call high or low price of that bar index. If anyone can help me to solve these issues it'll be much appriciated, Thank you!

1 Answers1

0

You should get the timeframe of the chart, then get the unix time of the last bar so that you can calculate how much bar are in between :

//@version=5
indicator("My script")

selected_time   = input.time (title = "Bar 1", defval = 0900, inline = "1", confirm = true)

range_in_second = (last_bar_time - selected_time)/1000

// Change the timeframe in seconds :
nb_seconds = timeframe.in_seconds(timeframe.period)

nb_bar = math.floor(range_in_second / nb_seconds)

// Get high price
h_ = high[nb_bar]
G.Lebret
  • 2,826
  • 2
  • 16
  • 27