// ZScore Indicator
//Assembled by [USER=117]@chewie76[/USER] on UseThinkScript.com
//Link: https://usethinkscript.com/threads/z-score-upper-indicator-for-thinkorswim.3896/
//Modified for TradingView by egshih
//@version=4
study("Z-Score Indicator Lower",overlay=false)
//Inputs
price = close
length = input(20)
ZavgLength = input(20)
//Initialize values
oneSD = stdev(price,length)
avgClose = sma(price,length)
ofoneSD = oneSD*price[1]
Zscorevalue = ((price-avgClose)/oneSD)
avgZv = sma(Zscorevalue,20)
//Compute and plot Z-Score
avgZscore = sma(Zscorevalue,ZavgLength)
Zscore = ((price-avgClose)/oneSD)
//Plot ZScore
plot(avgZscore,title="AverageZScore",linewidth=1)
plot (Zscore, style=plot.style_histogram, color=Zscore>0?color.green:color.red)
//Plot zero line and extreme bands
zero = 0
two = 2
one = 1
negone = -1
negtwo = -2
three = 3
negthree = -3
plot(zero,title="0Line",color=color.yellow)
plot(two,title="2Line",color=color.red)
plot(one,title="1Line",color=color.orange)
plot(negone,title="-1Line",color=color.lime)
plot(negtwo,title="-2Line",color=color.green)
//Buy Conditions, currently set at 0.75
conditionbuy = crossover(Zscore,avgZscore) and avgZscore < -0.75
conditionsell = crossunder(Zscore,avgZscore)and avgZscore > 0.75
//Plot Buy and Sell Arrows
plotshape(conditionbuy, style=shape.arrowup, color=color.green,location=location.bottom, text="Buy")
plotshape(conditionsell, style=shape.arrowdown, color=color.red,location=location.top, text="Sell")
fillthree=hline(3)
filltwo=hline(2)
fillnegtwo=hline(-2)
fillnegthree=hline(-3)
//fill Cloud
fill(fillthree,filltwo,color=color.red)
fill(fillnegtwo,fillnegthree,color=color.green)