Indicator · Pine Script v5 · On the chart

Multi Level Zigzag

by WISEPLAT· code credited to HeWhoMustNotBeNamed

This indicator calculates and plots up to four hierarchical ZigZag levels directly on the price chart to map swings and market structure across different sensitivities.

View on GitHub

Repaints

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code230
Settings18inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago20 Jun 2023

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

230 lines of Pine Script v5 from ZigZag - ishod/Multi Level Zigzag - 7.pine.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Multi Level Zigzag - 7.pine.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed

//   __    __            __       __  __                  __       __                        __      __    __              __      _______             __    __                                          __ 
//  /  |  /  |          /  |  _  /  |/  |                /  \     /  |                      /  |    /  \  /  |            /  |    /       \           /  \  /  |                                        /  |
//  $$ |  $$ |  ______  $$ | / \ $$ |$$ |____    ______  $$  \   /$$ | __    __   _______  _$$ |_   $$  \ $$ |  ______   _$$ |_   $$$$$$$  |  ______  $$  \ $$ |  ______   _____  ____    ______    ____$$ |
//  $$ |__$$ | /      \ $$ |/$  \$$ |$$      \  /      \ $$$  \ /$$$ |/  |  /  | /       |/ $$   |  $$$  \$$ | /      \ / $$   |  $$ |__$$ | /      \ $$$  \$$ | /      \ /     \/    \  /      \  /    $$ |
//  $$    $$ |/$$$$$$  |$$ /$$$  $$ |$$$$$$$  |/$$$$$$  |$$$$  /$$$$ |$$ |  $$ |/$$$$$$$/ $$$$$$/   $$$$  $$ |/$$$$$$  |$$$$$$/   $$    $$< /$$$$$$  |$$$$  $$ | $$$$$$  |$$$$$$ $$$$  |/$$$$$$  |/$$$$$$$ |
//  $$$$$$$$ |$$    $$ |$$ $$/$$ $$ |$$ |  $$ |$$ |  $$ |$$ $$ $$/$$ |$$ |  $$ |$$      \   $$ | __ $$ $$ $$ |$$ |  $$ |  $$ | __ $$$$$$$  |$$    $$ |$$ $$ $$ | /    $$ |$$ | $$ | $$ |$$    $$ |$$ |  $$ |
//  $$ |  $$ |$$$$$$$$/ $$$$/  $$$$ |$$ |  $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$  |  $$ |/  |$$ |$$$$ |$$ \__$$ |  $$ |/  |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
//  $$ |  $$ |$$       |$$$/    $$$ |$$ |  $$ |$$    $$/ $$ | $/  $$ |$$    $$/ /     $$/   $$  $$/ $$ | $$$ |$$    $$/   $$  $$/ $$    $$/ $$       |$$ | $$$ |$$    $$ |$$ | $$ | $$ |$$       |$$    $$ |
//  $$/   $$/  $$$$$$$/ $$/      $$/ $$/   $$/  $$$$$$/  $$/      $$/  $$$$$$/  $$$$$$$/     $$$$/  $$/   $$/  $$$$$$/     $$$$/  $$$$$$$/   $$$$$$$/ $$/   $$/  $$$$$$$/ $$/  $$/  $$/  $$$$$$$/  $$$$$$$/ 
//                                                                                                                                                                                                          
//                                                                                                                                                                                                          
//
//@version=5
indicator('Multi Level Zigzag', shorttitle='Multi Level ZigZag', overlay=true, max_bars_back=1000, max_lines_count=500, max_labels_count=500)
useAlternativeSource = input.bool(false, title='', group='Source', inline='src')
source = input.source(close, title='Alternative Source', group='Source', inline='src')

showStatTable = input.bool(true, title='Show Stats', group='Misc')
max_array_size = input.int(50, step=20, title='Max Array Size', group='Misc')
useZigZagChain = input.bool(false, 'Chain Zigzags', group='Misc')
waitForConfirmation = input.bool(false, 'Wait For Confirmation', group='Misc')

showZigZag1 = input.bool(true, title='L1 Length', group='Zigzag', inline='main')
zigzag1Length = input.int(3, step=1, minval=3, title='', group='Zigzag', inline='main')
zigzag1Color = input.color(color.rgb(66, 165, 245, 0), title='', group='Zigzag', inline='main')

showZigZag2 = input.bool(true, title='L2 Length', group='Zigzag', inline='sub1')
zigzag2Length = input.int(2, step=1, minval=2, title='', group='Zigzag', inline='sub1')
zigzag2Color = input.color(color.rgb(153, 204, 102, 0), title='', group='Zigzag', inline='sub1')

showZigZag3 = input.bool(true, title='L3 Length', group='Zigzag', inline='sub2')
zigzag3Length = input.int(2, step=1, minval=2, title='', group='Zigzag', inline='sub2')
zigzag3Color = input.color(color.rgb(251, 192, 45, 0), title='', group='Zigzag', inline='sub2')

showZigZag4 = input.bool(true, title='L4 Length', group='Zigzag', inline='sub3')
zigzag4Length = input.int(2, step=1, minval=2, title='', group='Zigzag', inline='sub3')
zigzag4Color = input.color(color.rgb(244, 143, 177, 0), title='', group='Zigzag', inline='sub3')

var zigzagpivots1 = array.new_float(0)
var zigzagpivotbars1 = array.new_int(0)
var zigzagpivotdirs1 = array.new_int(0)

var zigzagpivots2 = array.new_float(0)
var zigzagpivotbars2 = array.new_int(0)
var zigzagpivotdirs2 = array.new_int(0)

var zigzagpivots3 = array.new_float(0)
var zigzagpivotbars3 = array.new_int(0)
var zigzagpivotdirs3 = array.new_int(0)

var zigzagpivots4 = array.new_float(0)
var zigzagpivotbars4 = array.new_int(0)
var zigzagpivotdirs4 = array.new_int(0)

var zigzag1lines = array.new_line(0)
var zigzag2lines = array.new_line(0)
var zigzag3lines = array.new_line(0)
var zigzag4lines = array.new_line(0)

add_to_array(arr, val, maxItems) =>
    array.unshift(arr, val)
    if array.size(arr) > maxItems
        array.pop(arr)

pivots(length) =>
    highsource = useAlternativeSource ? source : high
    lowsource = useAlternativeSource ? source : low
    float phigh = ta.highestbars(highsource, length) == 0 ? highsource : na
    float plow = ta.lowestbars(lowsource, length) == 0 ? lowsource : na
    [phigh, plow, bar_index, bar_index]

outerpivots(startIndex, length, zigzagpivots, zigzagpivotbars) =>
    zigzagminimal = array.slice(zigzagpivots, startIndex, length - 1)
    lastPivot = array.get(zigzagpivots, startIndex)
    lastPivotBar = array.get(zigzagpivotbars, startIndex)
    highestPivot = array.max(zigzagminimal)
    lowestPivot = array.min(zigzagminimal)
    float phigh = lastPivot == highestPivot ? lastPivot : na
    float plow = lastPivot == lowestPivot ? lastPivot : na
    int phighbar = lastPivot == highestPivot ? lastPivotBar : na
    int plowbar = lastPivot == lowestPivot ? lastPivotBar : na
    [phigh, plow, phighbar, plowbar]

addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, value, bar, dir) =>
    newDir = dir
    if array.size(zigzagpivots) >= 2
        LastPoint = array.get(zigzagpivots, 1)
        newDir := dir * value > dir * LastPoint ? dir * 2 : dir
        newDir
    add_to_array(zigzagpivots, value, max_array_size)
    add_to_array(zigzagpivotbars, bar, max_array_size)
    add_to_array(zigzagpivotdirs, newDir, max_array_size)

zigzagcore(phigh, plow, phighbar, plowbar, zigzagpivots, zigzagpivotbars, zigzagpivotdirs) =>
    pDir = 1
    newZG = false
    doubleZG = phigh and plow
    if array.size(zigzagpivots) >= 1
        pDir := array.get(zigzagpivotdirs, 0)
        pDir := pDir % 2 == 0 ? pDir / 2 : pDir
        pDir

    if (pDir == 1 and phigh or pDir == -1 and plow) and array.size(zigzagpivots) >= 1
        pivot = array.shift(zigzagpivots)
        pivotbar = array.shift(zigzagpivotbars)
        pivotdir = array.shift(zigzagpivotdirs)
        value = pDir == 1 ? phigh : plow
        bar = pDir == 1 ? phighbar : plowbar

        useNewValues = value * pivotdir > pivot * pivotdir
        value := useNewValues ? value : pivot
        bar := useNewValues ? bar : pivotbar
        newZG := newZG or useNewValues
        addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, value, bar, pDir)

    if pDir == 1 and plow or pDir == -1 and phigh
        value = pDir == 1 ? plow : phigh
        bar = pDir == 1 ? plowbar : phighbar
        dir = pDir == 1 ? -1 : 1
        newZG := true
        addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, value, bar, dir)

    [newZG, doubleZG]

zigzag(length, zigzagpivots, zigzagpivotbars, zigzagpivotdirs) =>
    [phigh, plow, phighbar, plowbar] = pivots(length)
    zigzagcore(phigh, plow, phighbar, plowbar, zigzagpivots, zigzagpivotbars, zigzagpivotdirs)

outerzigzag(outerzigzagLength, zigzagpivots, zigzagpivotbars, outerzigzagpivots, outerzigzagpivotbars, outerzigzagpivotdirs, ignore) =>
    newOuterZG = false
    newDoubleOuterZG = false
    startIndex = waitForConfirmation ? 1 : 0
    if array.size(zigzagpivots) >= outerzigzagLength * 2 + startIndex
        [phigh, plow, phighbar, plowbar] = outerpivots(startIndex, outerzigzagLength * 2 + startIndex, zigzagpivots, zigzagpivotbars)
        [newZG, doubleZG] = zigzagcore(phigh, plow, phighbar, plowbar, outerzigzagpivots, outerzigzagpivotbars, outerzigzagpivotdirs)
        newOuterZG := newZG
        newDoubleOuterZG := doubleZG
        newDoubleOuterZG
    [newOuterZG, newDoubleOuterZG]

draw_zg_line(idx1, idx2, zigzaglines, zigzagpivots, zigzagpivotbars, zigzagcolor, zigzagwidth, zigzagstyle) =>
    if array.size(zigzagpivots) > 2
        y1 = array.get(zigzagpivots, idx1)
        y2 = array.get(zigzagpivots, idx2)
        x1 = array.get(zigzagpivotbars, idx1)
        x2 = array.get(zigzagpivotbars, idx2)
        zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=zigzagcolor, width=zigzagwidth, style=zigzagstyle)
        if array.size(zigzaglines) >= 1
            lastLine = array.get(zigzaglines, 0)
            if x2 == line.get_x2(lastLine) and y2 == line.get_y2(lastLine)
                line.delete(lastLine)
        array.unshift(zigzaglines, zline)
        if array.size(zigzaglines) > max_array_size * 10
            line.delete(array.pop(zigzaglines))

draw_zigzag(doubleZG, zigzaglines, zigzagpivots, zigzagpivotbars, zigzagcolor, zigzagwidth, zigzagstyle) =>
    if doubleZG
        draw_zg_line(1, 2, zigzaglines, zigzagpivots, zigzagpivotbars, zigzagcolor, zigzagwidth, zigzagstyle)

    if array.size(zigzagpivots) >= 2
        draw_zg_line(0, 1, zigzaglines, zigzagpivots, zigzagpivotbars, zigzagcolor, zigzagwidth, zigzagstyle)

getCellColorByDirection(dir) =>
    dir == 2 ? color.green : dir == 1 ? color.lime : dir == -1 ? color.orange : dir == -2 ? color.red : color.silver

[level1ZG, doublel1ZG] = zigzag(zigzag1Length, zigzagpivots1, zigzagpivotbars1, zigzagpivotdirs1)
[level2ZG, doublel2ZG] = outerzigzag(zigzag2Length, zigzagpivots1, zigzagpivotbars1, zigzagpivots2, zigzagpivotbars2, zigzagpivotdirs2, level1ZG)
[level3ZG, doublel3ZG] = outerzigzag(useZigZagChain ? zigzag3Length : zigzag2Length + zigzag3Length, useZigZagChain ? zigzagpivots2 : zigzagpivots1, useZigZagChain ? zigzagpivotbars2 : zigzagpivotbars1, zigzagpivots3, zigzagpivotbars3, zigzagpivotdirs3, useZigZagChain ? level2ZG : level1ZG)
[level4ZG, doublel4ZG] = outerzigzag(useZigZagChain ? zigzag4Length : zigzag2Length + zigzag3Length + zigzag4Length, useZigZagChain ? zigzagpivots3 : zigzagpivots1, useZigZagChain ? zigzagpivotbars3 : zigzagpivotbars1, zigzagpivots4, zigzagpivotbars4, zigzagpivotdirs4, useZigZagChain ? level2ZG : level1ZG)
if level1ZG and showZigZag1
    draw_zigzag(doublel1ZG, zigzag1lines, zigzagpivots1, zigzagpivotbars1, zigzag1Color, 1, line.style_solid)

if level2ZG and showZigZag2
    draw_zigzag(doublel2ZG, zigzag2lines, zigzagpivots2, zigzagpivotbars2, zigzag2Color, 1, line.style_solid)

if level1ZG and showZigZag3
    draw_zigzag(doublel3ZG, zigzag3lines, zigzagpivots3, zigzagpivotbars3, zigzag3Color, 1, line.style_solid)

if level2ZG and showZigZag4
    draw_zigzag(doublel4ZG, zigzag4lines, zigzagpivots4, zigzagpivotbars4, zigzag4Color, 1, line.style_solid)



stats = table.new(position=position.top_right, columns=8, rows=max_array_size + 2, border_width=1)
text_size = size.tiny
if barstate.islast and showStatTable

    table.cell(table_id=stats, column=0, row=0, text='Price', bgcolor=color.black, text_color=color.white, text_size=text_size)
    table.cell(table_id=stats, column=1, row=0, text='BarIndex', bgcolor=color.black, text_color=color.white, text_size=text_size)
    table.cell(table_id=stats, column=2, row=0, text='Zigzag2', bgcolor=color.black, text_color=color.white, text_size=text_size)
    table.cell(table_id=stats, column=3, row=0, text='Zigzag3', bgcolor=color.black, text_color=color.white, text_size=text_size)
    table.cell(table_id=stats, column=4, row=0, text='Zigzag4', bgcolor=color.black, text_color=color.white, text_size=text_size)
    zg2Index = 0
    zg3Index = 0
    zg4Index = 0
    for i = 0 to array.size(zigzagpivots1) - 1 by 1
        bgcolor = getCellColorByDirection(array.get(zigzagpivotdirs1, i))
        z1Price = array.get(zigzagpivots1, i)
        z1Bar = array.get(zigzagpivotbars1, i)
        table.cell(table_id=stats, column=0, row=i + 1, text=str.tostring(z1Price), bgcolor=bgcolor, text_size=text_size)
        table.cell(table_id=stats, column=1, row=i + 1, text=str.tostring(z1Bar), bgcolor=bgcolor, text_size=text_size)


        if array.size(zigzagpivots2) > zg2Index
            z2Price = array.get(zigzagpivots2, zg2Index)
            z2Bar = array.get(zigzagpivotbars2, zg2Index)

            if z2Bar == z1Bar
                table.cell(table_id=stats, column=2, row=i + 1, text='', bgcolor=zigzag2Color, text_size=text_size)
                zg2Index := zg2Index + 1

                if array.size(zigzagpivots3) > zg3Index
                    z3Price = array.get(zigzagpivots3, zg3Index)
                    z3Bar = array.get(zigzagpivotbars3, zg3Index)

                    if z3Bar == z2Bar
                        table.cell(table_id=stats, column=3, row=i + 1, text='', bgcolor=zigzag3Color, text_size=text_size)
                        zg3Index := zg3Index + 1

                        if array.size(zigzagpivots4) > zg4Index
                            z4Price = array.get(zigzagpivots4, zg4Index)
                            z4Bar = array.get(zigzagpivotbars4, zg4Index)

                            if z4Bar == z3Bar
                                table.cell(table_id=stats, column=4, row=i + 1, text='', bgcolor=zigzag4Color, text_size=text_size)
                                zg4Index := zg4Index + 1
                                zg4Index

Overview

Each level can be toggled and configured with custom lengths and colors. Settings allow users to chain consecutive ZigZags, select an alternative price source, wait for pivot confirmation, and display an on-screen statistics table. Because it is based on ZigZag swing points, the unconfirmed trailing legs repaint as new extremes develop on live bars.

Details

Published by

WISEPLAT on GitHub

Code credit

HeWhoMustNotBeNamed, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Support & resistance, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
useAlternativeSourceboolfalseuseAlternativeSource
Alternative Sourcesourceclosesource
Show StatsbooltrueshowStatTable
Max Array Sizeint50max_array_size
Chain ZigzagsboolfalseuseZigZagChain
Wait For ConfirmationboolfalsewaitForConfirmation
L1 LengthbooltrueshowZigZag1
zigzag1Lengthint3zigzag1Length
zigzag1Colorcolorcolor.rgb(66, 165, 245, 0)zigzag1Color
L2 LengthbooltrueshowZigZag2
zigzag2Lengthint2zigzag2Length
zigzag2Colorcolorcolor.rgb(153, 204, 102, 0)zigzag2Color
Show all 18 settings
SettingTypeDefaultVariable
L3 LengthbooltrueshowZigZag3
zigzag3Lengthint2zigzag3Length
zigzag3Colorcolorcolor.rgb(251, 192, 45, 0)zigzag3Color
L4 LengthbooltrueshowZigZag4
zigzag4Lengthint2zigzag4Length
zigzag4Colorcolorcolor.rgb(244, 143, 177, 0)zigzag4Color
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener

Function - Linear Regression

by ricardosantos79
261 stars

This indicator fits a linear regression through stored pivot highs and lows and draws the resulting channel on the price chart. A function returns predicted values, maximum and minimum deviations, and the average absolute deviation. Confirmed two-bar pivots up

Indicator v5 TrendSupport & resistance
Updated 4 years ago · None stated GitHub repository of Function - Linear Regression

AI Trend

by dearvn
257 stars

AI Trend is an indicator that plots pivot points, trend lines, and support and resistance levels directly on the price chart. It marks high and low pivots based on user-defined length, draws trend lines that check for violations at specified points, and identi

Indicator v5 TrendSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of AI Trend

Ichimoku Cloud

by harryguiacorn
219 stars

This indicator plots Ichimoku Cloud elements on the price chart, including Tenkan-sen, Kijun-sen, Senkou Span A and B lines with optional Chikou Span. It signals trend changes via Tenkan-sen and Kijun-sen crosses and places arrows at Kijun-sen direction shifts

Indicator v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ichimoku Cloud
219 stars

This indicator identifies local swing highs and swing lows to construct a Zig Zag pattern on the main price chart. It evaluates pivot points based on a customizable number of surrounding left and right bars. Using persistent variables, the script tracks previo

Indicator v4 Support & resistanceTrend Repaints
Updated 5 years ago · None stated GitHub repository of Teaching: Finding Highs and Lows 6

Dynamic Linear Regression

by TradersPost
218 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 3 months ago · None stated GitHub repository of Dynamic Linear Regression

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers