Search code examples
pine-scriptmoving-averagetradingtrend

Assigning first candle previous color background


I have this simple code that shows the long term trend of price with the integration of a Bollinger Band to have an exclusion zone.

Price though, might be entering briefly this band to then exit it again on the next candle, so I'd like to add another option that the first candle in the band retains the same background color of the previous candle.

It's probably a very easy solution but I guess it's still out of my grasp.

TIA

as in this example

//@version=4
study(title="200SMA vs Price", shorttitle="MAvsP", overlay=false)
len = 200
src = close
out200 = sma(src, len)
plot(out200, color=color.blue, title="200SMA", linewidth=2)

mult = input(5.0, minval=0.001, maxval=50, title="StdDev", step=1)
dev = mult/10 * stdev(src, len)
upper = out200 + dev
lower = out200 - dev

plot(src, color=color.black, title="Price", linewidth=2)

bgcolor( (src > upper) ? #00FF00 :
         (src < lower) ? #FF0000 : 
         (src > lower) and (src < upper) ? #FFFF00 :
         na, transp=70)

Solution

  • bgcolor( (src > upper or (src[1] > upper[1] and (src > lower) and (src < upper))) ? #00FF00 :
             (src < lower or (src[1] < lower[1] and (src > lower) and (src < upper))) ? #FF0000 : 
             (src > lower) and (src < upper) ? #FFFF00 :
             na, transp=70)
    

    Preservation of color on the first candle when entering the channel.