RicardoSantos

[RS]Simple ZigZag V2

EXPERIMENTAL: Method to improve the zigzag, best method so far...
Open-source script

In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in a publication is governed by House Rules. You can favorite it to use it on a chart.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.

Want to use this script on a chart?
study("[RS]Simple ZigZag V2", overlay=true)
TF = input('240')

f_zigzag(_TF)=>
    _hh = security(tickerid, _TF, high)
    _ll = security(tickerid, _TF, low)
    _output = high >= _hh ? high : low <= _ll ? low : na
f_tops(_TF)=>
    _hh = security(tickerid, _TF, high)
    _ll = security(tickerid, _TF, low)
    _output = high >= _hh ? high : na
f_bots(_TF)=>
    _hh = security(tickerid, _TF, high)
    _ll = security(tickerid, _TF, low)
    _output = low <= _ll ? low : na

tops = f_tops(TF)
bots = f_bots(TF)
zigzag = f_zigzag(TF)

plot(tops, color=gray, linewidth=2)
plot(bots, color=gray, linewidth=2)
plot(zigzag, color=black, linewidth=3)

f_fix_zigzag(_zigzag)=>
    _hh = _zigzag ? close : high >= nz(_hh[1]) ? highest(2) : nz(_hh[1])
    _ll = _zigzag ? close : low <= nz(_ll[1]) ? lowest(2) : nz(_ll[1])
    _isBhigh = valuewhen(_zigzag, _zigzag >= high, 1)
    _isChigh = valuewhen(_zigzag, _zigzag >= high, 0)
    _isBlow = valuewhen(_zigzag, _zigzag <= low, 1)
    _isClow = valuewhen(_zigzag, _zigzag <= low, 0)
    _output = _zigzag and _isBhigh and _isChigh ? _ll[1] :_zigzag[1] and _isBhigh[1] and _isChigh[1] ? _hh :
        _zigzag and _isBlow and _isClow ? _hh[1] : _zigzag[1] and _isBlow[1] and _isClow[1] ? _ll : _zigzag

fix_zz = f_fix_zigzag(zigzag)
plot(fix_zz, color=aqua, linewidth=2)

last_zz_a = valuewhen(zigzag, zigzag, 2)
last_zz_b = valuewhen(zigzag, zigzag, 1)
last_zz_c = valuewhen(zigzag, zigzag, 0)

ab_dif = abs(last_zz_a-last_zz_b)
bc_dif = abs(last_zz_b-last_zz_c)

fib1 = last_zz_c >= high ? last_zz_c - ab_dif : last_zz_c <= low ? last_zz_c + ab_dif : nz(fib1[1])
fib2 = last_zz_c >= high ? last_zz_c - bc_dif : last_zz_c <= low ? last_zz_c + bc_dif : nz(fib2[1])
plot(fib1, color=gray, style=cross, linewidth=1)
plot(fib2, color=silver, style=cross, linewidth=1)