We can colour the chart’s background in TradingView and also fill a background section. But how do we colour the chart’s full background from top to bottom conditionally?

In this article:

Colouring a TradingView background conditionally

The colours that TradingView scripts use can be set by hand or defined programmatically. With that latter we can work with any hexadecimal colour value as well as the basic TradingView colours.

Any of those colour values can shade the chart’s background from top to bottom when used with the bgcolor() function (Pine Script Language Tutorial, n.d.). The area that this function colours is either the background of the main instrument (when the script is overlaid on that data series) or the subchart in which the script’s values display. For more on bgcolor(), see colouring the background of a TradingView chart.

The standard use of bgcolor() is to fill the chart’s background on every bar. But this function’s color argument also accepts an expression that sets the colour conditionally (TradingView, n.d.). This means that we can come up with a true/false condition (like close > open) and give the chart’s background a colour based on the result of that condition. For example, bars that closed higher can be given a green background while a red background is for those that closed lower.

Besides choosing between colours, it’s also possible to turn a coloured background conditionally on or off. For that we use the na built-in variable, which represents a “not a number” value (TradingView, n.d.). What’s special about this value is that, when the background’s colour is set to na, it gives the background the same colour as the chart (see Pine Script Language Tutorial, n.d.), which makes it look invisible. So instead of making the background red or green depending on how the bar closed, we can also colour the background of bars that closed higher and use na to ‘turn off’ the background when the bar closed lower.

Note: The fill() function, which colours a section of the chart’s background, cannot accept conditional colour values nor a na value. This means that, if we want to colour the chart’s background conditionally, we can only do so with bgcolor().

Both bgcolor() approaches – conditionally choosing one of several colours or conditionally turning the background ‘off’ – are shown in the programming example below.

Using code to conditionally colour a TradingView background

In the programming example below we recreate the standard stochastic indicator with additional features. The script colours its background blue, red, or green depending on whether the stochastic K value is neutral, overbought, or oversold. With an input option we can also turn off the blue background colouring. After discussing the code, we’ll look at charts displaying the indicator and its input options:

study(title="Stochastic conditional background colouring", 
     shorttitle="Stoch colour", overlay=false)

// Inputs
priceData   = input(title="Price Data", type=source, defval=close)
stochLength = input(title="Length", type=integer, defval=14)
dLength     = input(title="D", type=integer, defval=3)
kSmooth     = input(title="K", type=integer, defval=3)
fillDefault = input(title="Colour Neutral Stoch?", type=bool, defval=true)
obLevel     = input(title="Overbought", type=integer, defval=80)
osLevel     = input(title="Oversold", type=integer, defval=20)

// Compute values
stochK = sma(stoch(priceData, high, low, stochLength), kSmooth)
stochD = sma(stochK, dLength)

// Plot values
plot(series=stochK, title="K", color=blue)
plot(series=stochD, title="D", color=orange)

hline(price=obLevel, title="Overbought line", linestyle=dotted, color=gray)
hline(price=osLevel, title="Oversold line", linestyle=dotted, color=gray)

// Colour background
backgroundColour = (stochK > obLevel) ? red :
    (stochK < osLevel) ? green :
    (fillDefault) ? #63B8FF :
    na
    
bgcolor(color=backgroundColour, transp=85, 
     title="Conditionally coloured background")

The example begins with the study() function that needs to be included in every indicator (see Pine Script Language Tutorial, n.d.). We set three of its arguments here: title and shorttitle for specifying the indicator name, and overlay set to false makes the indicator plot in a subchart instead of on the main price chart (TradingView, n.d.).

Then we add several manual input options to the script:

priceData   = input(title="Price Data", type=source, defval=close)
stochLength = input(title="Length", type=integer, defval=14)
dLength     = input(title="D", type=integer, defval=3)
kSmooth     = input(title="K", type=integer, defval=3)
fillDefault = input(title="Colour Neutral Stoch?", type=bool, defval=true)
obLevel     = input(title="Overbought", type=integer, defval=80)
osLevel     = input(title="Oversold", type=integer, defval=20)

These inputs show up in the script’s ‘Inputs’ window (see image further down below) and allow us to manually configure several values. They are made with the input() function, and this function also returns the input’s current value (TradingView, n.d.). We store each value returned by input() in a variable with the assignment operator (=). That way we can use the variable later on in the script when we want to use the input’s current value.

We first make a ‘source’ input type by setting the input() function’s type argument to source. This kind of input creates a pull-down menu that allows us to select several kinds of price bar data from the instrument that the script is added to (Pine Script Language Tutorial, n.d.). Its default value (defval) is set to close here, but high, low, open, and other prices are possible too. “Price Data” is the value that we set to the title argument, and this text is placed before the input option in the script’s ‘Inputs’ window. We store the input’s current value in the priceData variable.

The next three inputs (which we name “Length”, “D”, and “K”) are all numerical integer inputs, and we make these by setting their type argument to integer (TradingView, n.d.). These inputs, used for calculating the stochastic values, are given default values of 14, 3, and 3. Their current settings are kept in the stochLength, dLength, and kSmooth variables for use later on.

The next input has its type argument set to bool to create a Boolean true/false input option (Pine Script Language Tutorial, n.d.). We name this one “Colour Neutral Stoch?” and give it a true default value, which makes this true/false checkbox enabled (checked) by default. We use its value stored in the fillDefault variable later on to determine if we should colour the background of neutral stochastic values or not.

The last two inputs (“Overbought” and “Oversold”) are numerical integer inputs again, and we give these standard values of 80 and 20. We’ll use their obLevel and osLevel variables to determine whether the stochastic K value is overbought or oversold, which has implications for the colour we give the background.

Next we compute the stochastic values:

stochK = sma(stoch(priceData, high, low, stochLength), kSmooth)
stochD = sma(stochK, dLength)

The stochastic K value is computed with the stoch() function, which needs four arguments: a variable series with the source data and its high and low prices, plus an integer that defines the length in number of bars (TradingView, n.d.). We set the first argument to our priceData input variable that holds the instrument’s closing prices by default. With the high and low built-in variables we define the high and low prices, and the stochastic length is set with the stochLength input variable that’s set to a standard value of 14 earlier.

We then smooth the values returned by stoch(). We do that with sma(), a function that computes the Simple Moving Average (SMA) with two arguments: a series of values to calculate on and the SMA length in number of bars (TradingView, n.d.). Its first argument here is the value that’s returned by the stoch() function while the kSmooth input variable (that has a default value of 3) sets the smoothing length. We store this stochastic K in the stochK variable.

Then we compute the stochastic D value. For that we use the sma() function again, this time with the stochK values and the dLength input variable passed in. The smoothed K value is stored in the stochD variable with the assignment operator (=).

After that it’s time to display the values on the chart:

plot(series=stochK, title="K", color=blue)
plot(series=stochD, title="D", color=orange)

hline(price=obLevel, title="Overbought line", linestyle=dotted, color=gray)
hline(price=osLevel, title="Oversold line", linestyle=dotted, color=gray)

Both stochastic values are shown on the chart here with plot(), a function that plots the series of data on the chart that’s specified by its series argument (TradingView, n.d.). In the first plot() function call we set that argument to the stochK variable. We name this plot “K” with the title argument, and this affects how the plot is named in the chart’s ‘Data Window’ and in the ‘Style’ window when setting a script’s colours manually. The colour of the K line is set to the blue standard TradingView colour. Since we don’t specify the plot() function’s style argument, plot() displays the data as a line by default (TradingView, n.d.). With the second plot() statement we display the stochD values on the chart with an orange line that’s named “D”.

Then we plot the overbought and oversold lines. We do that with hline(), a function that renders a horizontal line at a given price level (TradingView, n.d.). Both hline() statement are alike; their price argument is set to the obLevel or osLevel input variable and are named “Overbought line” or “Oversold line” with the title argument. Both lines show on the chart as a dotted line (linestyle=dotted) in grey (color=gray).

We then determine the colour for our background conditionally:

backgroundColour = (stochK > obLevel) ? red :
    (stochK < osLevel) ? green :
    (fillDefault) ? #63B8FF :
    na

Here we assign the backgroundColour variable one of 4 colours based on 3 conditions. The colour that’s going to be stored in this variable depends on which conditions are true or false, and we evaluate those conditions with several conditional (ternary) operators (?:). That operator evaluates a condition and, when the condition is true, returns its second value. Should the condition be false, then the conditional operator returns its third value (Pine Script Language Tutorial, n.d.).

Since we’ve combined several conditional operators here, they’re evaluated consecutively. The first checks if the current K value (stochK) is greater than (>) the overbought level, which we’ve set with the obLevel input variable. When that’s the case, the red standard TradingView colour is returned by the conditional operator and then stored in the backgroundColour variable with the assignment operator (=).

But if that condition isn’t true, the second conditional operator is executed. This one evaluates if the K value (stochK) is less than (<) the oscillator’s oversold level (osLevel). If that’s true, the conditional operator returns green and that colour is then stored in the backgroundColour variable.

When that condition isn’t true either, the third conditional operator is processed. This time it simply evaluates the fillDefault input variable, which holds the current value of our “Colour Neutral Stoch?” input option. Since that input is a Boolean true/false input, its fillDefault input variable either holds a value of true or false. When this checkbox is enabled (and so fillDefault is true), the third conditional operator returns #63B8FF here; the hexadecimal colour value of steel blue. That colour value is then stored in the backgroundColour variable. When the “Colour Neutral Stoch?” input option isn’t checked (meaning fillDefault is false), then this last conditional operator returns na. That value, in effect, ‘turns off’ the coloured background by making it transparent (see Pine Script Language Tutorial, n.d.).

So what are we doing here in normal English? We first check if the stochastic K line is in the overbought area and store the red colour in our variable when that’s the case. If the K line isn’t overbought, we evaluate if it perhaps is oversold. When it is, the green colour is put into our variable. When K isn’t overbought nor oversold, we process the “Colour Neutral Stoch?” input option. If that checkbox is enabled, then for stochastic K values that aren’t overbought or oversold the backgroundColour variable is set to steel blue. When that checkbox is disabled (unchecked), then we put the na transparent colour in that variable for any neutral stochastic K value.

Once the background colour is determined, it’s time to perform the actual background colouring:

bgcolor(color=backgroundColour, transp=85, 
     title="Conditionally coloured background")

With the bgcolor() function we colour the chart’s full background from top to bottom (TradingView, n.d.). Its color argument is set to the backgroundColour variable that we’ve just assigned a colour conditionally. The transp argument, which sets the transparency of the background ranging from 0 (not transparent) to 100 for fully transparent (TradingView, n.d.), is set to 85 for a reasonably transparent background.

We also set the bgcolor() function’s title argument to “Conditionally coloured background”. That name is shown in the script’s ‘Style’ window when manually adjusting a script’s colours, and a descriptive name helps to identify that filled background.

Conditionally colouring a chart’s background in TradingView or not

The above example added to a EUR/USD chart looks like:

Example of colouring a background conditionally in TradingView

And added to a GBP/USD chart, our stochastic indicator look as follows:

Colouring a background programmatically in TradingView

The input options that the indicator makes look like this and have these default values:

Input options of our TradingView example script

When we disable the “Colour Neutral Stoch?” input option, the background of the neutral stochastic K values isn’t made blue anymore. And so the previous GBP/USD chart changes to:

Colouring the background of a TradingView chart

Changing other inputs, like the “Overbought” and “Oversold” options to values of 90 and 10, changes that chart as follows:

Changing the colour of TradingView chart programmatically

By the way, since we’ve used the title argument to set descriptive names for plot(), hline(), and bgcolor(), the ‘Style’ window of our script looks like:

Manually changing the TradingView script's style and colour settings

See offsetting a coloured background in TradingView for other ways to colour the chart’s background, while the basics of bgcolor() are discussed in colouring the background of a TradingView chart. While that function colours the chart’s full background from top to bottom, the fill() function colours a background section and can fill the background between a plot and horizontal line. The available colours in TradingView are the basic TradingView colours as well as the hexadecimal colour values that literally allow millions of different colours.

Summary

The bgcolor() function colours the chart’s background, and this can either be the main chart area (when the script is overlaid on the chart’s instrument) or the script’s subchart. The background colour is set with the function’s color argument, and this argument accepts colour values that are set conditionally. We can set colours conditionally with the conditional ternary operator (?:). That operator evaluates a condition and, when the condition is true, returns its second value while its third value is returned when the condition is false. Besides conditionally selecting a colour, we can also ‘turn off’ the background when a certain condition occurs. We do that with the na (“not a number”) built-in variable, and that makes the background set with bgcolor() invisible.


References

Pine Script Language Tutorial (n.d.). Retrieved on October 23, 2015, from https://docs.google.com/document/d/1sCfC873xJEMV7MGzt1L70JTStTE9kcG2q-LDuWWkBeY/

TradingView (n.d.). Script Language Reference Manual. Retrieved on December 11, 2015, from https://www.tradingview.com/study-script-reference/