【问题标题】:How to match the Nth occurrence of a boolean condition?如何匹配第 N 次出现的布尔条件?
【发布时间】:2021-10-07 19:13:47
【问题描述】:

根据标题,我想知道是否可以针对最近出现的第 N 个布尔条件。这个用例一直出现在我的计划中,但我不知道如何去做。

我可能希望能够定位的一些事情的示例:

“N个小节内是否发生了两次?”

例如(伪代码使用花括号作为表示出现的手段):

x = conditionA and barssince(conditionA{1}) < 15

或者,

“一个条件是否发生between另一个条件两次出现?”

y = conditionA and barssince(conditionA{1}) > conditionB

(注意:在这种情况下,1 表示最近的第二次出现;即,0 是最近的一次)

这是一个带有视觉效果的示例问题:

“在绿色“x”后面 15 个小节内是否出现了两次(在我的情况下是较高,然后是较低)蓝色“x”形状?”

等等

由于 pine 非常面向系列和条件/发生,这似乎是一个基本概念(即,就内置函数而言?)。也许我只是没有意识到这一点。诚然,我是一名新手程序员,但这也是我喜欢使用 Pine 的原因之一 - 它对新手很友好!

【问题讨论】:

    标签: pine-script


    【解决方案1】:

    您可以使用valuewhen() 函数通过您的条件和bar_index 来完成此操作。指数从 0 开始作为第一个历史柱线。

    所以这会给我们最近出现的条件 A 的 bar_index :

    conditionA_index0 = valuewhen(conditionA, bar_index, 0)
    

    虽然这会给出下一个最新的:

    conditionA_index1 = valuewhen(conditionA, bar_index, 1)
    

    如果我们还获得另一个条件的索引:

    conditionB_index0 = valuewhen(conditionB, bar_index, 0)
    

    然后我们可以使用我们获得的索引值进行逻辑比较,看看条件是否发生在最后两次出现的条件A之间:

    lastB_betweenA = conditionB_index0 > conditionA_index1 and conditionB_index0 < conditionA_index0
    

    我们也可以推导出条件之间的条形:

    within_15_bars = conditionA_index0 - conditionA_index1 <= 15
    

    如果您正在做一些更复杂的事情,特别是如果您需要根据您的条件返回相当数量的数据点,那么最好使用 var 声明的数组来存储您的条件的 bar_index 值。

    var bool[] conditionA_array = array.new_bool()
    
    if conditionA
         array.unshift(conditionA_array, bar_index)
    

    然后您将能够检索第 n 次出现的 bar_index,如下所示:

    conditionA_index0 = array.get(conditionA_array, 0)
    

    这将检索最近出现的条件A的bar_index

    【讨论】:

    • 谢谢!这是有创意的(乍一看有点混乱)。只是在这里处理它......在我的新手中,我想我一直认为source 具有价格或指标值(例如开盘/高/低/收盘,或 RSI 水平等) .所以我想我们可以说我们在某种意义上“破解”了valuewhen() 函数来给我们 bar_index 编号,从而定位发生的历史位置?
    • 是的,类似的。布尔变量也是系列变量,就像 ohlc 值一样,只是没有数值,而是布尔值,例如 conditionA[0] 为 true,conditionA[1] 为 false,conditionA[2] false,conditionA[3] true 等. 您正在使用变量的布尔状态,来获取历史“位置”或 bar_index。所以使用 valuewhen(conditionA, bar_index, 0) 就像问最后一次 conditionA 何时为真 bar_index 是什么?
    • 好的。我必须以某种方式误用它,因为我无法绘制形状。我决定提出另一个关于使用的问题;因为 cmets 不是最好的细节和例子。也许你想回顾一下。在stackoverflow.com/questions/69508343/…
    猜你喜欢
    • 1970-01-01
    • 2019-10-16
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    相关资源
    最近更新 更多