简体   繁体   English

Pine Script:使用可变回溯期计数(barssince)

[英]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.我已经尝试了 sum-function、for 循环和我在互联网上找到的其他提示,但没有任何效果。

I want to do the following: When the RSI is overbought, I want to count for how many bars the 50 SMA is rising.我想做以下事情:当 RSI 超买时,我想计算 50 SMA 上升了多少根柱线。 So the lookback period is variable and starts when the RSI crosses 80 from below.因此,回溯期是可变的,从 RSI 从下方穿过 80 时开始。

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(...)).我可以用 barsince 得到这个周期,但看起来我不能将此值用作 sum 函数 math.sum(condition, barssince(...)) 中的周期或作为“for 循环”中的限制(对于 i = 1到 barsince(...))。

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().我还使用 int(max(1, nz(barssince(...)) + 1)) 来避免将 na 或零作为句点,并且我将 max_bars_back 定义为指标 () 中的参数。 But it didn't help.但这没有帮助。

A variable period doesn't work with the sum-function.可变期间不适用于 sum 函数。 I could make it work with other functions like lowest() for example.例如,我可以使它与其他函数一起使用,例如最低()。 So it's a problem with the sum-function.所以这是 sum 函数的问题。

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.当 RSI 高于 50 且 SMA 上升时,下面的代码将开始计数。 If the RSI goes below 50 or SMA stops rising, it resets the counter.如果 RSI 低于 50 或 SMA 停止上升,它会重置计数器。

Note: I lowered RSI limit to 50 so you can see more action in the screenshot below.注意:我将 RSI 限制降低到 50,因此您可以在下面的屏幕截图中看到更多操作。

//@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.可变期间不适用于 sum 函数。

you can try this:你可以试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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