Paresh Kumar
Paresh Kumar

Reputation: 13

pine script how to reset barssince to zero at the beginning of every session

I'm looking to track the number of bars after following condition is met for a candle:

volume > 3x sma(volume)

I'm using barssince for this purpose. However I don't want to carry forward this value to the next day's session

Is there any way to do this using barssince

Thanks

Code:

strategy(title="Test", overlay=true)
var highvolbar=0
VolLen = input(title="Vol MA Length", type=input.integer, defval=50)
sess = input(defval = "0915-1530", title="Trading Session")
t = time(timeframe.period, sess)
sessionOpen = na(t) ? false : true


if(sessionOpen)
    smavolcompare = volume > 3 * sma(volume,VolLen) 
    highvolbar := barssince(smavolcompare)

last_bar = timestamp(year, month, dayofmonth + 1, 15, 15, 0) == time_close

if (last_bar)
    highvolbar:=0
plot(highvolbar)

I want highvolbar to reset to 0 at the end of every session

Upvotes: 1

Views: 2755

Answers (1)

PineCoders-LucF
PineCoders-LucF

Reputation: 8789

Here we declare the highvolbar variable with var to make it persistent and keep track of the count manually, without using barsince():

//@version=4
strategy(title="Test")
var int highvolbar=na
VolLen = input(title="Vol MA Length", type=input.integer, defval=50)
sess = input(defval = "0915-1530", title="Trading Session")
t = time(timeframe.period, sess)
sessionOpen = not na(t)
newSession = sessionOpen and not sessionOpen[1]
smavolcompare = volume > 3 * sma(volume,VolLen)

if newSession
    // Reset.
    highvolbar := na
if smavolcompare
    // Begin count.
    highvolbar := 0
else if not na(highvolbar)
    // A count is happening; increment it.
    highvolbar := highvolbar + 1

last_bar = timestamp(year, month, dayofmonth + 1, 15, 15, 0) == time_close

if (last_bar)
    highvolbar:=0
plot(highvolbar)

enter image description here

Upvotes: 1

Related Questions