如何为条件的所有出现计算条件关闭和当前关闭的差异

How to calculate difference of condition close and current close for all occurences of the condition

con = ta.barssince(ta.rsi(close, 14) > 20) == 1

var flag = false

if ta.barssince(ta.ema(close, 50) > ta.ema(close, 200)) == 1
    flag := true

if ta.barssince(ta.ema(close, 50) < ta.ema(close, 200)) == 1
    flag := false

var labels = array.new_label()
var conCloses = array.new_float()

if con
    array.unshift(labels, label.new(bar_index, close, ""))
    array.unshift(conClose, close)

if flag[1]
    var txt = 0.
    for conClose in conCloses
        txt := close - conClose

    for label in labels
        label.set_text(label, str.tostring(txt))

afterFlag = flag[1] and not flag

if afterFlag
    array.clear(labels)
    array.clear(conCloses)

我想计算所有条件出现时条件满足时的收盘价与当前收盘价的差异,并用标签显示。我尝试使用与我问过的上一个问题相同的逻辑,但只发现自己在挣扎。帮助将不胜感激。

插入了一张我正在努力实现的图片。

如果您希望在每个刻度上更新值,您应该在全局范围内设置标签的文本,否则,文本将仅在出现 flag[1] 和 real-time 时更新价格将被忽略。

脚本中带有标签的第二个 for..in 结构仅使用 txt 的最后一个值,因为它是在前一个循环的所有迭代之后执行的。您可以在 for [index, element]..in 结构中使用索引来设置标签的文本:

//@version=5
indicator("myScript", overlay = true)

con = ta.barssince(ta.rsi(close, 14) > 20) == 1

var flag = false

if ta.barssince(ta.ema(close, 50) > ta.ema(close, 200)) == 1
    flag := true

if ta.barssince(ta.ema(close, 50) < ta.ema(close, 200)) == 1
    flag := false

var labels = array.new_label()
var conCloses = array.new_float()

if con
    array.unshift(labels, label.new(bar_index, close, "", color = color.new(color.blue, 80), style = label.style_label_up))
    array.unshift(conCloses, close)

var txt = 0.
for [i, conClose] in conCloses
    txt := conClose - close
    label.set_text(array.get(labels, i), str.tostring(txt))