DEVIATION OF THE STOCHASTIC INDICATOR
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ceshead
//@version=5
//The Stochastic Oscillator is a technical indicator created by George Lane in the 
//1950s. It is used to identify potential overbought or oversold conditions in an 
//asset's price by comparing its closing price to its price range over a set number of 
//periods. The resulting value is displayed as a percentage between 0 and 100.
//This new technical indicator uses the stochastic oscillator as its base and calculates 
//the deviation of its moving average, generating an alternative view of market volatility.

//31/01/23
indicator(title="DEVIATION OF THE STOCHASTIC INDICATOR", shorttitle="DSI", timeframe = "")

// Getting inputs
periodK = input.int(14, title="%K Length", minval=1, group="Stochastic")
smoothK = input.int(4, title="%K Smoothing", minval=1, group="Stochastic")
periodD = input.int(3, title="%D Smoothing", minval=1, group="Stochastic")
len = input(20, title="Length", group="Deviation")
smooth = input(6,  title="Smooth ema", group="Deviation")
dev = input(2,  title="Deviation", group="Deviation")

// Logic
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
src = d
emaR = ta.ema(src, len)
out=(src-emaR)
fastOut=ta.ema(out,smooth)
slowOut=ta.ema(out,smooth*4)
sumaDevs=math.pow(out-slowOut,2)
smaSums=ta.sma(sumaDevs,5)
devs=dev*math.sqrt(smaSums/5)
bandUp2=slowOut+devs
bandDn2=slowOut-devs
sumaDevf=math.pow(out-fastOut,2)
smaSumf=ta.sma(sumaDevf,5)
devf=dev*math.sqrt(smaSumf/5)
bandUp=fastOut+devf
bandDn=fastOut-devf
bandDn2:=fastOut>0? 0:bandDn2
bandUp2:=fastOut<0? 0:bandUp2
bandUp:= bandUp<0? 0:bandUp
bandDn:= bandDn>0? 0:bandDn

// Colors
col_grow_above = input.color(#26A69A,  group="Histogram", inline="grow_above")
col_fall_above = input.color(#B2DFDB,  group="Histogram", inline="fall_above")
col_grow_below = input.color(#FFCDD2,  group="Histogram", inline="grow_below")
col_fall_below = input.color(#FF5252,  group="Histogram", inline="fall_below")

// Plots
plot(out, title="Histogram", style=plot.style_columns, color=(out>=0 ? (out[1] < out ? col_grow_above : col_fall_above) : (out[1] < out ? col_grow_below : col_fall_below)))
plot(bandUp, color=color.white , style=plot.style_line)
plot(bandUp2, color=color.blue)
plot(bandDn2, color=color.yellow)
plot(bandDn, color=color.white)




