ScriptingTutorialsColour a plot by condition

Colour a plot by condition

In this tutorial we will plot the closing price and colour it by bar: green where the close is above the previous close, red where it is not.

Each step below is a whole script. Replace what is in the editor, and check it.

Step 1: plot the close

indicator("Rising close", "rising", true)
plot(close)

One line, drawn in the default colour: plot’s colour argument carries a default and we have not passed one. We are about to take that argument over.

Step 2: colour it

plot takes a colour, and the colour may differ on every bar. So the test goes inside the argument. The conditional expression takes a condition and two values and produces one of them.

indicator("Rising close", "rising", true)
plot(close, color = close > close[1] ? color.green : color.red)

Check it. The line is now green on every bar that closed above the one before it and red on the rest, so the colour changes along the line rather than once for the whole plot.

close[1] is the close of the previous bar. The square brackets read a value from an earlier bar.

Step 3: name the condition

The plot call is doing two jobs at once. We move the test to its own line and give it a name.

indicator("Rising close", "rising", true)
bool up = close > close[1]
plot(close, color = up ? color.green : color.red)

The chart is identical. What changed is the script: the condition now has a name, and the plot call reads as one thought.

Step 4: soften the two colours

color.new takes a colour and an opacity and returns the same colour at that opacity. Opacity runs from 0 to 1, and 1 is solid — read the argument as how much of the colour you want.

indicator("Rising close", "rising", true)
bool up = close > close[1]
plot(close, color = up ? color.new(color.green, 0.5) : color.new(color.red, 0.5), linewidth = 2)

Check it. The line is thicker and both colours are half strength, so the price bars underneath stay visible through it.

The mistake to avoid

It is tempting to write the condition around the call instead:

if close > close[1] {
    plot(close, color = color.green)
}

That is rejected. plot must be called at the top level of the script, and a branch opens a scope of its own, so the interpreter reports that the call must be made in the global scope. The same holds for every chart-output function.

The condition belongs in an argument. That is why steps 2 to 4 put it there.

What we built

A four-line indicator that answers a question per bar in the colour of the line. The shape — compute a bool, then use it inside plot’s colour argument — is the one to reuse whenever output has to change with a condition.

Next

Ready to put this into practice?
Try GoCharting Premium
Unlock advanced orderflow, market profile, options desk, and real-time data — everything you just read about, live in your charts.
Upgrade