Z-Score Buy and Sell Signals
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Steversteves

//@version=5
indicator("Z-Score Buy and Sell Signals", overlay=true, max_labels_count = 500)

lengthInput = input.int(75, "Length", minval = 2)
// Calculating High Z Score

a = ta.sma(close, lengthInput)
b = ta.stdev(close, lengthInput)
c = (close - a) / b 



// Highest and Lowest

highz = ta.highest(c, lengthInput)

lowz = ta.lowest(c, lengthInput) 

// Condition Alerts

var wait = 0

wait := wait + 1

if (c <= lowz) and (wait > 30)
    wait := 10
    label.new(x=bar_index, y=high, text="Buy", size = size.tiny, color=color.green)
    alert("Buy The Dip "+syminfo.ticker, alert.freq_once_per_bar)
    

if (c >= highz) and (wait > 30)
    wait := 10
    label.new(x=bar_index, y=high, text="Sell", size = size.tiny, color=color.red)
    alert("Sell The Rally "+syminfo.ticker, alert.freq_once_per_bar)

// Colors

color bear = color.new(color.orange, 0) 
color bull = color.new(color.lime, 0) 

bool overbought = c >= 2 
bool oversold = c <= -2 

brcolor = overbought ? bear : oversold ? bull : na

barcolor(brcolor)