joost
joost

Reputation: 71

How to get the number of bars in a day in pine script in tradingview?

I'm trying to plot the 9/50/180 day SMA regardless of the timeframe period.

If you're looking at the candles in 1D, 4h, 3h, 15m, .. I just want to see the 9/50/.. day SMA.

If I could calculate the number of bars in a day, I could take the SMA over a 9 * #numberOfCandlesInDay length.

I could define a numberOfMinutes per syminfo.prefix (lots of work) and then calculate the number of bars based on timeframe.multiplier, but that is a hassle and prone to error.

Any tips?

Upvotes: 1

Views: 1892

Answers (2)

alewis729
alewis729

Reputation: 416

As already answered by PineCoders request.security() is best for your personal problem, however I'd like to answer the actual question.

I don't think there is a built-in function to get the number of bars in a single day for any timeframe (ofc lower than the Daily) but this is one method I came up with:

  • Get the number of seconds in a day via timeframe.in_seconds()
  • Get the number of seconds in the current timeframe period
  • Divide them to get how many times the timeframe period can be within a day
dayInSeconds = timeframe.in_seconds("1D")
tfInSeconds = timeframe.in_seconds(timeframe.period)
barsInDay = tfInSeconds < dayInSeconds ? dayInSeconds / tfInSeconds : 0

The good thing is that the result type is of simple int so it can be used as offset in drawings (plot, bgcolor, etc) to draw into future bars.

However I noticed that the calculation isn't precise if the asset has missing bars either because of the data source not providing all price data for the day for some reason, or because the asset doesn't trade 24h (like SPX500 EIGHTCAP for instance, that's missing price data between 5 & 6pm NY time). But for all other more usual cases it works fine.

Upvotes: 0

PineCoders-LucF
PineCoders-LucF

Reputation: 8789

Why not use security()? This uses our f_secureSecurity() wrapper function so that you avoid repainting:

//@version=4
study("", "MAs", true)
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
smaD9   = f_secureSecurity(syminfo.tickerid, "D", sma(close, 9))
smaD50  = f_secureSecurity(syminfo.tickerid, "D", sma(close, 50))
smaD180 = f_secureSecurity(syminfo.tickerid, "D", sma(close, 180))
plot(smaD9  )
plot(smaD50 )
plot(smaD180)

Another option is to use a ready-made indie like this one:

https://www.tradingview.com/script/8AUuFonD-5-MAs-w-alerts-LucF/

Upvotes: 1

Related Questions