Z-Score with Buy & 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
// For informational video, visit the link below:
// https://www.tradingview.com/chart/SPY/Wm4sYvcX-How-to-use-Z-Score-Indicator/ 
indicator("Z Score with Signals", max_labels_count = 500)

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

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

// Calculating Low Z Score

d = ta.sma(low, lengthInput)
e = ta.stdev(low, lengthInput)
f = (low - d) / e 

// Calculating High and Low Average

z = (c + f) / 2 

// Determine Colour 
color BullColor = input.color(color.green, "Bull")
color BearColor = input.color(color.red, "Bear")
color BearishColor = input.color(color.orange, "BearishColour")
color BullishColor = input.color(color.orange, "BullishColour")
color VeryBearishColor = input.color(color.red, "Very Bearish")
color VeryBullishColor = input.color(color.green, "Very Bullish")

// Build color

bool bear = z < 0 
bool bearish = z > 1.5 and z < 2.0 
bool verybearish = z > 2.0 
bool bullish = z < -1.5 and z > -2.0 
bool verybullish = z < -2.0
color palette = bear ? BearColor : BullColor 
color border = bearish ? BearishColor : bullish ? BullishColor : verybearish ? VeryBearishColor : verybullish ? VeryBullishColor : na 


plot (z, "Z-Score", style=plot.style_histogram, color=palette)

// SMA line

plot(z, "Border", color = border, linewidth=3)

// Highest vs lowest nuy and sell

highz = ta.highest(z, lengthInput)

lowz = ta.lowest(z, lengthInput) 


// Condition Alerts

var wait = 0

wait := wait + 1

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

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


