'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)
I want to calculate the difference of the close of when the condition is met with the current close for all the occurence of the condition, and display it with a label. I tried using the same logic with the previous question I asked but only find myself struggling. Help would be appreciated.
Solution 1:[1]
If you would like the values to be updated on every tick you should set the label's text in the global scope, otherwise, the text will be updated only on the flag[1] occurrence and real-time price would be ignored.
The second for..in structure with labels in your script is using only the last value of the txt as it is executed after all iterations of the previous loop. You can use indexing in the for [index, element]..in structure to set the label's text:
//@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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | e2e4 |

