// Ping me for donations, Collaborations or Support
study("ZigZag++", "ZigZag++ Lucem Anb", true, format.price)
Depth = input(12, "Depth", input.integer, minval=1, step=1)
Deviation = input(5, "Deviation", input.integer, minval=1, step=1)
mtf_val = input("", "Resolution", input.resolution)
line_thick = input(4, "Line Thickness", input.integer, minval=1, maxval=4)
p = input("Lime", "Up Color", options=["Red", "Lime", "Orange", "Teal", "Yellow", "White", "Black"])
q = input("Red", "Down Color", options=["Red", "Lime", "Orange", "Teal", "Yellow", "White", "Black"])
display_a = input(true, "Display Background Direction Changes?")
repaint = input(true, "Repaint Levels")
var lastlow = 0.0
var lasthigh = 0.0
data(x) => security(syminfo.tickerid, mtf_val!="" ? mtf_val : timeframe.period, x)
cc(x) => x=="Red"?color.red:x=="Lime"?color.lime:x=="Orange"?color.orange:x=="Teal"?
color.teal:x=="Yellow"?color.yellow:x=="Black"?color.black:color.white
col(c) => c>0 ? (cc(p)) : c<0 ? (cc(q)) : na
getLow(x, y, z, a) =>
ll = y
v = data(x)
m = v==ll or data(z) - v > a*syminfo.mintick
if v!=ll
ll := v
if m
v := 0.0
[v,ll]
getHigh(x, y, z, a) =>
lh = y
v = data(x)
m = v==lh or v - data(z) > a*syminfo.mintick
if v!=lh
lh := v
if m
v := 0.0
[v,lh]
[v,e] = getLow(lowest(Depth), lastlow, low, Deviation)
lastlow := e
zBB = v != 0.0
[v1,e1] = getHigh(highest(Depth), lasthigh, high, Deviation)
lasthigh := e1
zSS = v1 != 0.0
d = 0, zigzagHigh = 0, zigzagLow = 0
d := zBB ? 1 : zSS ? -1 : nz(d[1], 0)
virtualLow = zigzagLow[1] + 1
if not zBB or (zBB and d == d[1] and low > low[virtualLow])
zigzagLow := nz(zigzagLow[1]) + 1
virtualHigh = zigzagHigh[1] + 1
if not zSS or (zSS and d == d[1] and high < high[virtualHigh])
zigzagHigh := nz(zigzagHigh[1]) + 1
direction_changed = d!=d[1]
x1 = bar_index-zigzagLow
x2 = bar_index-zigzagHigh
y1 = low[zigzagLow]
y2 = high[zigzagHigh]
if not repaint and d!=d[1]
line zigzag = line.new(x1[1], y1[1], x2[1], y2[1], color=col(d[1]*-1), style=line.style_solid, width=line_thick)
if repaint
line zigzag = line.new(x1, y1, x2, y2, color=col(d*-1), style=line.style_solid, width=line_thick)
if (d == d[1])
line.delete(zigzag[1])
bgcolor(display_a ? col(-d) : na, editable=false, title="Direction Changes")
alertcondition(direction_changed, "Direction Changed", 'Zigzag on {{ticker}} direction changed at {{time}}')
alertcondition(direction_changed and d<0, "Bullish Direction", 'Zigzag on {{ticker}} bullish direction at {{time}}')
alertcondition(direction_changed and d>0, "Bearish Direction", 'Zigzag on {{ticker}} bearish direction at {{time}}')