ZwiTrader
ZwiTrader

Reputation: 345

Update variables at every change, regardless of timeframe

I would like to display a label with the current close that is colored according to the change with respect to the very last (i.e., intra-bar) value of close, thereby replicating the way a symbol's values are colored in a watchlist (at every single change of value)

However, it seems that Pine Script will only update user/script variables at the start of a new bar (with respect to the chart's timeframe resolution).

Although close will always return the most current value, there is no way (that I have found) to access the very last close— only close[1], which is the last bar's close and not the truly-previous value of close. I would need something along the lines of close[0,1], of the form source[bar_index, array_index_of_changes_within_bar_index].

I have tried several ways to get around this: arrays, combinations of var and non-var variables, security() at 1s resolutions (which would have been a subpar solution but which, regardless, Pine Script does not allow).

Any suggestions as to whether or not this is achievable in Pine Script?

Upvotes: 0

Views: 1256

Answers (1)

rumpypumpydumpy
rumpypumpydumpy

Reputation: 3803

You can use a varip declared array like so to do the close comparison intrabar

var label close_label = label.new(x = bar_index, y = close, style = label.style_label_left, size = size.normal, textcolor = color.white)
varip float[] intrabar_closes = array.new_float()

array.unshift(intrabar_closes, close)
if array.size(intrabar_closes) > 2
    array.pop(intrabar_closes)
col = array.size(intrabar_closes) > 1 ? array.get(intrabar_closes, 0) >= array.get(intrabar_closes, 1) ? color.lime : color.red : na
label.set_xy(close_label, x = bar_index, y = close)
label.set_color(close_label, color = col)
label.set_text(close_label, text = tostring(close))

Upvotes: 1

Related Questions