TradingView – Cannot use ‘barcolor’ in local scope

Ran into this issue a few times when trying to set the bar or background colour in a pine script. Its a relatively simple fix, but it can trip you up the first time you see it.

For example, this is a super simple RSI script. I’m attempting to set the bar colour if the RSI value is above 80:

//@version=5
indicator(shorttitle="RSI Script", title="Simple RSI Script", overlay = false)
length = input(14, title="RSI Period")
overBought = input(70, title="Overbought Level")
overSold = input(30, title="Oversold Level")

rsiValue = ta.rsi(close, length)

plot(rsiValue, title="RSI", color=color.blue)
hline(overBought, title="Overbought Level", color=color.red)
hline(overSold, title="Oversold Level", color=color.green)

if (rsiValue > 80)
    barcolor(color=color.red)

However, if I try to add this script to the chart I get the error “Cannot use ‘barcolor’ in local scope”.

To get around this, remove the if statement and use something like the following:

myColour = (rsiValue > 80) ? color.purple : na
barcolor(color=myColour)

Effectively this either sets the bar colour to purple if RSI value is above 80, or na if it’s not. Full script below for clarity:

//@version=5
indicator(shorttitle="RSI Script", title="Simple RSI Script", overlay = false)
length = input(14, title="RSI Period")
overBought = input(70, title="Overbought Level")
overSold = input(30, title="Oversold Level")

rsiValue = ta.rsi(close, length)

plot(rsiValue, title="RSI", color=color.blue)
hline(overBought, title="Overbought Level", color=color.red)
hline(overSold, title="Oversold Level", color=color.green)

myColour = (rsiValue > 80) ? color.purple : na
barcolor(color=myColour)