pine-scripttradingstochasticcrossover

Crossover and crossunder functions don't respect the parameters I'm giving pine script


I'm trying to add a simple background color when on a stochastic, k crosses over d any time but when k is above 80, and equally k crosses under d any time but when k is below 20.

Yet constantly I'm getting crossover and crossunder signals in these condition. In this case in the picture there is not ever a crossover at all.

No Crossover

Can anyone help me explaining why this happens?

Thanks

//@version=4
study(title="Stochastic RSI", shorttitle="Stoch RSI", format=format.price, precision=2, resolution="")
smoothK = input(3, "K", minval=1)
smoothD = input(3, "D", minval=1)
lengthRSI = input(14, "RSI Length", minval=1)
lengthStoch = input(14, "Stochastic Length", minval=1)
cross = input(false, "Highlight Only Crosses in Ob & Os Areas")
src = input(close, title="RSI Source")
rsi1 = rsi(src, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)
plot(k, "K", color=#0094FF)
plot(d, "D", color=#FF6A00)
h0 = hline(80, "Upper Band", color=#606060)
h1 = hline(20, "Lower Band", color=#606060)
fill(h0, h1, color=#9915FF, transp=80, title="Background")

col_ = (k > 80 and crossover(k, d)) or (k < 20 and crossunder(k, d))
         ? na
     : crossunder(k, d)
         ? #d7000080
     : crossover(k, d)
         ? #00d70080
     : na

bgcolor(col_)

Solution

  • //@version=4
    study(title="Help (Stochastic RSI)", shorttitle="Stoch RSI", format=format.price, precision=2, resolution="")
    smoothK = input(3, "K", minval=1)
    smoothD = input(3, "D", minval=1)
    lengthRSI = input(14, "RSI Length", minval=1)
    lengthStoch = input(14, "Stochastic Length", minval=1)
    cross = input(false, "Highlight Only Crosses in Ob & Os Areas")
    src = input(close, title="RSI Source")
    rsi1 = rsi(src, lengthRSI)
    k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
    d = sma(k, smoothD)
    plot(k, "K", color=#0094FF)
    plot(d, "D", color=#FF6A00)
    h0 = hline(80, "Upper Band", color=#606060)
    h1 = hline(20, "Lower Band", color=#606060)
    fill(h0, h1, color=#9915FF, transp=80, title="Background")
    
    //col_ = (k > 20 and crossover(d, k)) ? #d7000080 : ((k < 80 and crossunder(d, k)) ? #00d70080 : na)
    col_ = (k > 20 and k[1]<d[1] and k[0]>d[0]) ? #d7000080 : ((k < 80 and k[1]>d[1] and k[0]<d[0]) ? #00d70080 : na)
    
    bgcolor(col_)