Sindar
Sindar

Reputation: 10879

If/else-like behaviour

I'm actually having a huge problem debugging one of a script i'm programming on tradingview.

To make it simple, on the image below you'll find that at line 54, i'm calculating the value of "a" which firstly return 22.19.

After that i'm trying an if / else on which i'm basically doing the same calculation whether if my if/else is true or false and i'm not understanding why this return me a different result then the first time i'm calculating the "a" value.

Is there something obvious i'm missing there because this is actually driving me crazy ^^"

enter image description here

Edit 1 (with the value of Price and Price 1 ) :

enter image description here

Complete code :

Pastebin link : Nw2dWMi7

Upvotes: 0

Views: 538

Answers (1)

Starr Lucky
Starr Lucky

Reputation: 1961

Let's simplify your example:

//@version=5
indicator("Dominant Cycle Tuned Rsi - V5")


var globalScope = 0.0
var localScope1 = 0.0
var localScope2 = 0.0


globalScope := ta.change(close)


if close > close[1]
    // this ta.change has it's own set of values for cases when close > close[1]
    localScope1 := ta.change(close)
    localScope2 := na
else
    localScope1 := na
    // this ta.change has it's own set of values for other cases 
    localScope2 := ta.change(close)
    
plot (globalScope, color=color.red)
plot (localScope1, color=color.black)
plot (localScope2, color=color.black)

Firs of all, you're getting warning

The function 'ta.change' should be called on each calculation for consistency. It is recommended to extract the call from this scope.

From the manual: (https://www.tradingview.com/pine-script-docs/en/v4/language/Functions_and_annotations.html#execution-of-pine-functions-and-historical-context-inside-function-blocks)

The history of series variables used inside Pine functions is created through each successive call to the function. If the function is not called on each bar the script runs on, this will result in disparities between the historic values of series inside vs outside the function’s local block. Hence, series referenced inside and outside the function using the same index value will not refer to the same point in history if the function is not called on each bar.

The reason why you're getting different results because that when you're calling ta.change in a local scope.

if close > close[1]
    // this ta.change has it's own set of values for cases when close > close[1]
    localScope1 := ta.change(close)

here we comparing close and close[1] ONLY FOR cases when close > close[1].

And here

else
    localScope1 := na
    // this ta.change has it's own set of values for other cases 
    localScope2 := ta.change(close)

for the cases ONLY when close < close[1].

So results of two conditional statements and global scope will be different.

Upvotes: 2

Related Questions