#// Indicator for TOS
#// © LuxAlgo
#study("Zig Zag Channels [LuxAlgo]",overlay=true
# converted by Sam4Cok@Samer800 - 08/2024
input src = close;
input length = 100; #
input extendLines = yes;
input showRepaintedChannel = yes;
input ShowExtremities = yes; #(true,'Show Extremities')
input ShowLabels = yes; #(true,'Show Labels')
def na = Double.NaN;
def last = isNaN(close);
def n = BarNumber();
def extedn = if extendLines then yes else !last;
def upper = Highest(src, length);
def lower = Lowest(src, length);
def os = if src[length] > upper then 0 else
if src[length] < lower then 1 else os[1];
def btm1 = os == 1 and os[1] != 1;
def top1 = os == 0 and os[1] != 0;
def btm = if isNaN(btm1[-length]) then btm[1] else btm1[-length];
def top = if isNaN(top1[-length]) then top[1] else top1[-length];
def dir = if !last then if btm then 0 else if top then 1 else dir[1] else dir[1];
def zigzag = if top then high else
if btm then low else na;
#-- BaseLine
def startPrice = if btm then low else if top then high else startPrice[1];
def x1 = if top then n else if btm then n else x1[1];
def x2 = if !last then n else x2[1];
def y1 = if n == HighestAll(x1) then startPrice else y1[1];
def y2 = if n == HighestAll(x2) then src else y2[1];
def x11= highestall(x1);
def x22= highestall(x2);
def y22= highestall(y2);
def slope = (y22 - y1)/(x22 - x1);
def base = y1 + ((n - x11) * slope);
def baseLine = if n >= x11 then base else na;
def max = Max(close, open);
def min = Min(close, open);
def maxx = if isNaN(baseLine) then 0 else if max>baseLine then (max - baseLine) else maxx[1];
def minn = if isNaN(baseLine) then 0 else if min<baseLine then (baseLine - min) else minn[1];
def up = if !isNaN(baseLine) then highestAll(maxx) else up[1];
def lo = if !isNaN(baseLine) then highestAll(minn) else lo[1];
#--- plot
plot zigzagLine = zigzag;
zigzagLine.AssignValueColor(if dir[1] then GetColor(2) else GetColor(6));
zigzagLine.EnableApproximation();
plot trendLine = if showRepaintedChannel and extedn then baseLine else na;
plot UpChannel = if ShowExtremities and extedn then trendLine + up else na;
plot LoChannel = if ShowExtremities and extedn then trendLine - lo else na;
trendLine.AssignValueColor(if slope>0 then GetColor(6) else GetColor(2));
UpChannel.SetDefaultColor(GetColor(1));
LoChannel.SetDefaultColor(GetColor(0));
UpChannel.SetStyle(Curve.MEDIUM_DASH);
LoChannel.SetStyle(Curve.MEDIUM_DASH);
AddChartBubble(ShowLabels and top, high, AsDollars(high), Color.GREEN);
AddChartBubble(ShowLabels and btm, low, AsDollars(low), Color.RED, no);
AddLabel(ShowLabels, if slope>0 then "Trend Up" else "Trend Down", if slope>0 then Color.GREEN else Color.RED);
#-- END of CODE