I am working on an indicator, where, based on certain conditions, I change the color of a bar's background (using bgcolor). This is easy to do. But what I now want to do is to edit the bar's bgcolor transparency based on the certain conditions in relation to the previous bar.
As an example, if the RSI is above a certain value, I change the bgcolor to green (this is easy to do). Going further, if the latest bar's RSI > previous bar's RSI and both RSIs are above the threshold value, I would like the latest bar's bgcolor transparency to be 5% less than that of the previous bar. This doesn't apply to just a pair of bars, but to an entire series of bars.
I can't figure out how to do this. Any help?
You can calculate the transparency
value into a variable according to your conditions. For example:
//@version=5
indicator("RSI background")
myRSI = ta.rsi(close, 20)
RSIcondition = myRSI >= 60
barAlpha = 100.0
if RSIcondition and not RSIcondition[1] // first candle to break the RSI value
barAlpha := 80
else if RSIcondition and myRSI > myRSI[1] // second candle that break RSI value, and is higher than previous RSI
barAlpha := barAlpha[1] * 0.95
else if RSIcondition // second candle that break RSI value, but is not higher than previous RSI
barAlpha := barAlpha[1] / 0.95
myColor = RSIcondition ? color.new(color.green, barAlpha) : na
bgcolor(myColor)
This example shows the long way to achieve what you want, but I think it's clearer to understand it that way.
You can also check gradient
. It won't give you the full control over the exact transparency of the the color, but it can be more efficient:
gradienColor = RSIcondition ? color.from_gradient(myRSI, 60, 100, color.new(color.green, 80), color.new(color.green, 10)) : na
bgcolor(gradienColor)