'Change bar color when condtion is true and change if it false

I am a beginner in programming, I have a question i want to make an indicator in pinescript i want to change bar color when condition is true and change when condition is false, but in crossover condition the point is when a buy signal, the color bar is green until a sell signal and the color turns red

linecci0 = 0
linecci1 = -200
linecci2 = 200
cci = cci(hl2,50)
cci1= cci < 200 and cci>-200

opl1 = crossover(cci,linecci2) and vfima > 0
ops1 = crossunder(cci,linecci1) and vfima < 0

// Deternine if we are currently LONG
isLong = false
isLong := nz(isLong[1], false)

// Determine if we are currently SHORT
isShort = false
isShort := nz(isShort[1], false)

// Buy only if the buy signal is triggered and we are not already long
buySignal = not isLong and opl1

// Sell only if the sell signal is triggered and we are not already short
sellSignal= not isShort and ops1

if (buySignal)
    isLong := true
    isShort := false

if (sellSignal)
    isLong := false
    isShort := true


plotshape(buySignal, text="BUY", style=shape.labelup, location=location.belowbar, color=color.green,textcolor=color.white, size=size.small)
plotshape(sellSignal, text="SELL", style=shape.labeldown, location=location.abovebar, color=color.red,textcolor=color.white, size=size.small)

I want to plot the green bar when I buy and it doesn't change until it sells and thank you if anyone wants to answer



Solution 1:[1]

You can use the barcolor() function to change the bar color.

Here is an example:

//@version=5
indicator("My script", overlay=true)

ema10 = ta.ema(close, 10)
ema50 = ta.ema(close, 50)

bull = ta.crossover(ema10, ema50)
bear = ta.crossunder(ema10, ema50)

barcolor(bull ? color.yellow : na)
barcolor(bear ? color.purple : na)
plot(ema10, color=color.yellow, linewidth=2)
plot(ema50, color=color.blue, linewidth=2)
plotshape(bull, color=color.yellow, size=size.small)
plotshape(bear, color=color.purple, size=size.small)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vitruvius