pine-scriptrsi

Pine-Script - can't use IF on PLOTSHAPE, solutions?


I am trying to make my indicator display a circle when it crosses over a high line on the RSI (e.g. at 80), but not make any more circles on the following bars/points at 80 or above unless it crosses below a lower line (e.g. at 30) first. Then I want it to put a circle as it crosses the 30 but not place any more on subsequent bars (basically same in reverse as with the 80).

I’m trying to use “plotshape”, but I can’t make it work without being able to put “plotshape” within a more complex IF statement/function. But “plotshape” cannot be used within an IF statement, so I am completely stuck. In C++ or alike simple, but not in Pine Script.

This code basically works for marking the crossover points, but I can’t work-out how to stop it marking the bars that follow.

//@version=5
indicator(title='title', shorttitle='RSI', overlay=false)

green  = color.new(color.green,  0)
red    = color.new(color.red,    0)
yellow = color.new(color.yellow, 0)

top_line = input(title='Default bull-line', defval=80.0)
bot_line = input(title='Default bear-line', defval=30.0)

src = input(title='RSI Source', defval=close)
len = input(title='RSI Length', defval=13)
rsi = ta.rsi(src, len)
plot(rsi, color=yellow)

var int A = na
var int B = na

if rsi >= top_line and rsi[1] < top_line
    A := 0

plotshape(rsi >= top_line and rsi[1] < top_line and A == 0, location=location.top,    color=green, style=shape.circle, text='')

if rsi >= top_line and rsi[1] >= top_line
    A := 1

if rsi <= bot_line and rsi[1] > bot_line
    B := 0

plotshape(rsi <= bot_line and rsi[1] > bot_line and B == 0, location=location.bottom, color=red,   style=shape.circle, text='')

if rsi >= bot_line and rsi[1] >= bot_line
    B := 1


plot(top_line, title='bullish', color=green)
plot(bot_line, title='bearish', color=red)


Solution

  • All I needed to do was add a counter rather than a flag to the code to make this work.

    if rsi >= top_line
        A := A + 2
        B := 0
    
    if rsi <= bot_line
        B := count2 + 2
        A := 0
    

    then obviously add a slight modification to the associated expressions