CreateAndShowZigzag
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LonesomeTheBlue

//@version=5

// @description Functions in this library creates/updates zigzag array and shows the zigzag
library("CreateAndShowZigzag")

Trz(float [] zigzag, int mLoc)=> 
    for x = array.size(zigzag) - 1 to array.size(zigzag) > 1 ? 0 : na by 2
        if bar_index - array.get(zigzag, x) <= mLoc
            break
        array.pop(zigzag)
        array.pop(zigzag)

addtozigzag(float [] zigzag, float value) =>
    array.unshift(zigzag, bar_index)
    array.unshift(zigzag, value)

updatezigzag(float [] zigzag, float value, int dir) =>
    if array.size(zigzag) == 0
        addtozigzag(zigzag, value)
    else
        if dir == 1 and value > array.get(zigzag, 0) or dir == -1 and value < array.get(zigzag, 0)
            array.set(zigzag, 0, value)
            array.set(zigzag, 1, bar_index)

export getZigzag(float [] zigzag, int prd, int mLoc)=>
    Trz(zigzag, mLoc)
    float ph = ta.highestbars(high, prd) == 0 ? high : na
    float pl = ta.lowestbars(low, prd) == 0 ? low : na
    var int dir = 0
    dir := ph and na(pl) ? 1 :
           pl and na(ph) ? -1 : 
           dir
    bool bothexist = ph and pl
    bool dirchanged = dir != dir[1]
    if ph or pl
        if bothexist
            updatezigzag(zigzag, dir == 1 ? ph : pl, dir)
            dir := -dir
            addtozigzag(zigzag, dir == 1 ? ph : pl)
        else
            if dirchanged  //and not nz(bothexist[1], false)
                addtozigzag(zigzag, dir == 1 ? ph : pl)
            else
                updatezigzag(zigzag, dir == 1 ? ph : pl, dir)
    [dir, bothexist]

export showZigzag(float [] zigzag, float [] zigzagold, int dir, bool specialcase, color upcol, color dncol)=>
    var line zzline = na
    if specialcase
        line.set_xy1(zzline, math.round(array.get(zigzag, 3)), array.get(zigzag, 2))
    if array.get(zigzag, 0) != array.get(zigzagold, 0) or array.get(zigzag, 1) != array.get(zigzagold, 1)
        if array.get(zigzag, 2) == array.get(zigzagold, 2) and array.get(zigzag, 3) == array.get(zigzagold, 3)
            line.delete(zzline)
        zzline := line.new(x1=math.round(array.get(zigzag, 1)), y1=array.get(zigzag, 0), x2=math.round(array.get(zigzag, 3)), y2=array.get(zigzag, 2), color=dir == 1 ? upcol : dncol)

export getTN()=>
    int TN = 8
    tick__ = syminfo.mintick
    while tick__ < 1
        TN += 1
        tick__ *= 10
    tick__ := high
    while tick__ > 1
        TN += 1
        tick__ /= 10
    TN
