Pine Script Cool-down for a certain number of bars

Viewed 361

I use the following code with "barssince" in Pine Script to get buy signals after a cooldown of 4 bars.

cooldown = ta.barssince(buySignal[1]) > 3 ? buySignal : na 
plotshape(cooldown, location=location.belowbar, color=color.lime, style=shape.triangleup, text="YEY")

In the following table I try to explain "what I want", which is another way of counting the candles. Candle # 1 and candle # 6 are marked correct. Candle # 11 should be yes, but considering the logic of "barssince" it is the 4. candle since the last signal, but it is the 5. candle since the last "yes" from the cooldown function. I hope you understand what I mean. How should the function look like?

Candle # 1 2 3 4 5 6 7 8 9 10 11
buySignal yes no no no no yes yes no no no yes
buySignal with cooldown yes no no no no yes no no no no no
candles since buySignal with cooldown 0 1 2 3 4 5 1 1 2 3 4
what I want yes no no no no yes no no no no yes

Thank you!

1 Answers

You can use a variable to mark if your signal along with your cooldown counter become true. Then just increment the counter and check with your condition again and then reset your variable.

Here, I have a simple buy condition (close > 40000). It will then mark every fifth candle where close > 40000.

//@version=5
indicator("My Script", overlay=true)
var bool isBought = false
var cnt = 0
buySignal = close > 40000

if not isBought and buySignal
    isBought := true
    cnt := 0
    
cnt := cnt + 1
bool coolDown = cnt > 4 and buySignal

if coolDown
    isBought := false
    
plotshape(series=coolDown, style=shape.triangleup, size=size.small, location=location.belowbar)
hline(price=40000, linestyle=hline.style_solid, linewidth=2)

enter image description here

Related