Search code examples
pine-scriptpine-script-v5tradingview-apitradingtechnical-indicator

How do I highlight the most recent signal in PineScript for TradingView?


I am encountering an issue in Pine Script v5 that I hope you can help with. My script runs perfectly fine, but I want to make the most recent "BUY" and "SELL" condition labels and background shading more prominent while reducing the opacity of older signals. The goal is to minimize chart clutter by highlighting only the latest signals and dimming the older ones.

Currently, the code colors and shades all the signals instead of just the most recent one. Below is the relevant section of my code. Could you advise what I might be doing wrong or if there's a specific function to achieve this in Pine Script?

I would appreciate any guidance on how to achieve this, or if it's even possible within Pine Script.

Screenshot results:

Screenshot results

Pinescript Code:

// Initialize variables to track the bar index of the most recent buy or sell signal
var int lastBuyIndex = na
var int lastSellIndex = na

// Track the most recent buy or sell condition
if (buyCondition)
    lastBuyIndex := bar_index
if (sellCondition)
    lastSellIndex := bar_index

// Plot Buy and Sell signals for EMA, MACD, RSI, and Volume
plotshape(series=buyCondition, location=location.belowbar, color=lastBuyIndex == bar_index ? color.green : color.new(color.green, 70), style=shape.labelup, text="BUY", textcolor=color.white, size=size.small, offset=0)
plotshape(series=sellCondition, location=location.abovebar, color=lastSellIndex == bar_index ? color.red : color.new(color.red, 70), style=shape.labeldown, text="SELL", textcolor=color.white, size=size.small, offset=0)

// Background shading for buy and sell signals
bgcolor(color = (buyCondition and lastBuyIndex == bar_index) ? color.new(color.green, 15) : color.new(color.green, 90), title="Buy Shading")
bgcolor(color = (sellCondition and lastSellIndex == bar_index) ? color.new(color.red, 15) : color.new(color.red, 90), title="Sell Shading")

Solution

  • You cannot do this with plotshape() and bgcolor(). You cannot change their properties once they are printed.

    You are going to need to use drawing objects such as label and box.

    Here is how you would do it with a label:

    var label last_long_label = na
    
    if (buyCondition)
        label.set_color(last_long_label, color.new(color.green, 90))                                // Reduce opacity of the old label
        last_long_label := label.new(bar_index, high, "BUY", color=color.new(color.green, 40))      // Create a new label with more bright color