T K
T K

Reputation: 13

pine script - undeclared identifier (cannot plot due to variable is declared in (if-else loop)

Here's my code brief code


indicator(title='Ultimate Bifröst', shorttitle='Ultimate Bifröst')

// Choose base and quote currency
base = input.string("USD",title="Base CURRENCY", options=["USD","EUR","GBP","AUD","NZD","CHF","CAD"])
quote = input.string("JPY",title="Quote CURRENCY", options=["USD","JPY","GBP","AUD","NZD","CHF","CAD"])

// Add the inputs
l = input.int(title='Length', defval=20, minval=5)
// dollar group
UJ = input.symbol(title='USDJPY', defval='FX:usdjpy') 
UCA = input.symbol(title='USDCAD', defval='FX:usdcad') 
s_UJ = request.security(UJ, timeframe.period, close)
s_UCA = request.security(UCA, timeframe.period, close)

if base == "USD" and quote == "JPY"
   B1 = ta.correlation(close, s_UJ, l)*0.25
   Q1 = ta.correlation(close, s_UCA, l)*0.25

else if base == "USD" and quote == "GBP"
   B1 = ta.correlation(close, s_UJ, l)*0.5
   Q1 = ta.correlation(close, s_UCA, l)*0.5
.
.
.

plot(B1, color=color.new(#9C27B0, 0), title='B1')
plot(Q1, color=color.new(#673AB7, 0), title='Q1')

I could not plot B1 and Q1 (based on user string input) as they are declared inside if-else condition.

I also tried an option to declared both of them before if-else and put the plot command inside if-else. Still, there is also an error called "cannot use plot in local scope" which I understand that plot can be used under if-else condition.

Upvotes: 0

Views: 355

Answers (1)

vitruvius
vitruvius

Reputation: 21179

You should define those variables in global scope and then use the := operator to assign them new values in your if blocks.

B1 = 0.0
Q1 = 0.0

if base == "USD" and quote == "JPY"
    B1 := ta.correlation(close, s_UJ, l)*0.25
    Q1 := ta.correlation(close, s_UCA, l)*0.25

else if base == "USD" and quote == "GBP"
    B1 := ta.correlation(close, s_UJ, l)*0.5
    Q1 := ta.correlation(close, s_UCA, l)*0.5

Upvotes: 1

Related Questions