'How to find the first value when bar open of ema, sma

I have the plots:

E = ema(close, 34)

S = sma(close, 14)

I would like to get the value of the 2 above lines when the first close == open (means when the bar appears, at the first second of the timeframe).

How can I do that. Please help me to write 2 functions.



Solution 1:[1]

On historical bars, scripts execute on the close, so no values from the beginning of the bar are available, other than open. You could always use the values calculated on the last bar's close with E[1] for example, but that would not necessarily be equivalent to a value obtained at the open of the bar, when a new bar opens at a different price than the previous bar's close, and also because of the fact that you would not be using the same 34 or 14 values to calculate your MAs.

On realtime bars, you could achieve what you want using the varip variables introduced in Pine Scriptâ„¢ v5:

//@version=5
indicator("", "", true)
E = ta.ema(close, 34)
S = ta.sma(close, 14)

varip float eAtOpen = na
varip float sAtOpen = na
if barstate.isrealtime and barstate.isnew
    eAtOpen := E
    sAtOpen := S
plot(eAtOpen, "eAtOpen")
plot(sAtOpen, "sAtOpen", color.orange)

enter image description here

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 PineCoders-LucF