silentPlanet
silentPlanet

Reputation: 431

bar_index of specific timestamp

I want to find the numbers of bars between a specific date and today's date(not current bar date).

This value should be constant at any bar. So far I can only think of a solution where I compute this information only at the end, after going through all intermediate bars.

What I tried:

var savedIndex = 0
if time == inputDateTime
   savedIndex = bar_index

if barstate.islast
  num_bars = bar_index - savedIndex // need this as a constant
  label.new(bar_index, 0, "# bars: " + tostring(num_bars))

Ideally I want to compute this as

var num_bars = barIndex(timenow) - barIndex(inputDate)
// looking for a function like barIndex

Upvotes: 1

Views: 3286

Answers (2)

Sỹ Lộc Nguyễn
Sỹ Lộc Nguyễn

Reputation: 11

getBarIndexAtTime(int _time_point) =>
    int m_bar_ind = an
    for count = 0 to 5000
        if time[count] >= _time_point and time[count + 1] < _time_point
            m_bar_ind := count
            break
    // @returns
    m_bar_ind

// How to use
m_date = timestamp("05 Jan 2023")
int bars = getBarIndexAtTime(_time_point = m_date)

This function convert time stamp to bar index. But it will work in your case

Upvotes: 1

rumpypumpydumpy
rumpypumpydumpy

Reputation: 3803

ts = timestamp(2021, 5, 21, 12, 00)

bartime = int(change(time))

bars = floor((timenow - ts) / bartime)

This is might be as close as you will get, however it will only work on crypto, 24/7 markets. I'm not sure it would be possible to do this for other markets due to the temporal gaps from weekends, holidays etc.

Upvotes: 2

Related Questions