简体   繁体   中英

Pine Script: Counting with variable lookback period (barssince)

It should be an easy task but somehow I can't figure it out. I've tried the sum-function, for loops and other tips that I have found on the internet but nothing works.

I want to do the following: When the RSI is overbought, I want to count for how many bars the 50 SMA is rising. So the lookback period is variable and starts when the RSI crosses 80 from below.

I can get this period with barssince but it looks like I cannot use this value as period in the sum-function math.sum(condition, barssince(...)) or as limit in a "for loop" (for i = 1 to barssince(...)).

I also used int(max(1, nz(barssince(...)) + 1)) to avoid na or zero as period and I defined max_bars_back as argument in the indicator(). But it didn't help.

A variable period doesn't work with the sum-function. I could make it work with other functions like lowest() for example. So it's a problem with the sum-function.

I need a workaround for this. Any ideas? Please please can anybody help me?

//@version=5
indicator("Counter")

rsi = ta.rsi(close, 14)
sma = ta.sma(close, 50)

cross = ta.crossover(rsi, 80)

lookback = int(math.max(1, nz(ta.barssince(cross)) + 1))

// First idea with sum function

cond = rsi > 80 and sma > sma[1] ? 1 : 0

count = math.sum(cond, lookback)



// Second idea with for loop

count = 0

if barstate.islast
    for i = 1 to lookback
        if rsi > 80 and sma50 > sma50[1]
            count += 1       

You are somehow close. You can combine multiple conditions and count at the same time.

Below code will start counting when the RSI is above 50 and if the SMA is rising. If the RSI goes below 50 or SMA stops rising, it resets the counter.

Note: I lowered RSI limit to 50 so you can see more action in the screenshot below.

//@version=5
indicator("Counter")

rsi = ta.rsi(close, 14)
sma = ta.sma(close, 50)

var sma_up_count = 0
sma_up_count := rsi > 50 ? sma > sma[1] ? sma_up_count + 1 : 0 : 0

plot(sma_up_count)

在此处输入图像描述

As your description, I think you may meet the same problem as me.

A variable period doesn't work with the sum-function.

you can try this:

sum = 0
for i = 0 to s
    sum := sum + k[i]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM