Search code examples
pine-scriptalgorithmic-trading

Highlight candle which is near to moving average on pine script


I am trying to identify whether a candle is near the moving average(not touching the MA). The candle that touching the moving average is working perfectly. How can I highlight the candle which is near to the MA?

Here is my current code

sma20 = sma(close, 20)
bullishEC = close > open[1] and close[1] < open[1]
maLongCondition = close > sma20 and (cross(sma20,low) or cross(sma20,close))
buy = bullishEC and maLongCondition
barcolor( buy ? color.yellow : na, title="bullish")

Thank you.


Solution

  • You can calculate the desired area with sma20 value + your desired percentage:

    colorAreaPercentage = input(1 , "Colored area precentage" , input.integer , minval = 0)
    sma20 = sma(close, 20)
    barColor =  close > sma20 and close < sma20 + (sma20 * colorAreaPercentage /100) ? color.fuchsia : close < sma20 and close > sma20 - (sma20 * colorAreaPercentage / 100) ? color.orange : na
    if ((high >= sma20 and low <= sma20) or high == sma20 or low == sma20)
        barColor := na
    barcolor(barColor)
    

    This will color 1% above the moving average and 1% below the moving average

    Edit:

    if ((high >= sma20 and low <= sma20) or high == sma20 or low == sma20)
        barColor := na
    

    This part of code will leave the touching candles uncolored.