Indicator · Pine Script v4 · On the chart

ZigZag (Using Line Array)

by WISEPLAT· code credited to HeWhoMustNotBeNamed

ZigZag (Using Line Array) plots zigzag lines on the price chart to identify swing highs and lows.

View on GitHub

GitHub stars2on the repository
Pine versionv4older, still runs
Lines of code118
Settings8inputs
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

118 lines of Pine Script v4 from ZigZag - ishod/ZigZag (Using Line Array) - 7.pine.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

ZigZag (Using Line Array) - 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=4
study("ZigZag (Using Line Array)", shorttitle="ZigZag", overlay=true, max_lines_count=500, max_labels_count=500)
source=input(close)
Length = input(10, minval=0, step=5)
DeviationThreshold = 0
showPivots = input(false)
showRatios = input(true)
bullishColor = input(color.green)
bullTrapColor = input(color.orange)
bearishColor = input(color.red)
bearTrapColor = input(color.lime)

var zigzaglines = array.new_line(0)
var zigzaglabels = array.new_label(0)
var zigzagdir = array.new_int(0)
var zigzagratios = array.new_float(0)

int max_array_size = 20

pivots(length, highSource, lowSource)=>
    float ph = highestbars(highSource, length) == 0 ? highSource : na
    float pl = lowestbars(lowSource, length) == 0 ? lowSource : na
    dir = 0
    dir := iff(ph and na(pl), 1, iff(pl and na(ph), -1, dir[1]))
    [dir, ph, pl]

get_edir(dir, y2)=>
    eDir = dir
    if(array.size(zigzaglines) > 0)
        lastLine = array.get(zigzaglines, 0)
        lastPivot = line.get_y1(lastLine)
        eDir := (dir*y2 > dir*lastPivot? 2 : 1) * dir
    lineColor = eDir == 2? bullishColor : eDir == 1? bullTrapColor : eDir == -1? bearTrapColor : bearishColor
    [eDir, lineColor]

add_to_zigzaglines(x1, y1 , x2, y2, dir)=>
    [eDir, lineColor] = get_edir(dir, y2)

    zline = line.new(x1=x1, y1=y1, 
         x2 = x2, y2=y2,
         color=lineColor, width=2, style=line.style_solid)
    array.unshift(zigzaglines, zline)

add_to_zigzaglabels(x1, x2, y1, y2, dir)=>
    [eDir, lineColor] = get_edir(dir, y2)
    pivotLabel = eDir == 2? "HH" : eDir == 1? "LH" : eDir == -1? "HL" : "LL"
    lastLineLen = 0.0
    currentLineLen = abs(y2-y1)
    if(array.size(zigzaglines) > 0)
        lastLine = array.get(zigzaglines, 0)
        lastLineLen := abs(line.get_y2(lastLine) - line.get_y1(lastLine))

    ratio = round(lastLineLen != 0 ? currentLineLen/lastLineLen : 0, 3)
    labelText = (showPivots ? pivotLabel : "") +
                         (showPivots and showRatios ? " - " : "") +
                         (showRatios ? tostring(ratio) : "")
    yloc = source == close ? (dir > 0? yloc.abovebar : yloc.belowbar) : yloc.price
    labelStyle = dir > 0? label.style_label_down : label.style_label_up
    labelSize = showRatios and showPivots? size.normal : size.small
    zlabel = label.new(x=x2, y=y2, text=labelText, xloc = xloc.bar_index, yloc = yloc, 
                     color=lineColor, size=labelSize, style=labelStyle)
    if(not showRatios and not showPivots)
        label.delete(zlabel)
    array.unshift(zigzaglabels,zlabel)
    array.unshift(zigzagdir, eDir)
    array.unshift(zigzagratios, ratio)

add_to_zigzag(dir, dirchanged, ph, pl, index, highSource, lowSource)=>
    value = (dir == 1? ph : pl)

    y1= dir == 1? lowest(lowSource, Length) : highest(highSource, Length)
    x1 = bar_index + (dir == 1? lowestbars(lowSource, Length) : highestbars(highSource,Length))
    x2 = index
    y2 = value
    skip = false
    if(array.size(zigzaglines) > 0)
        lastLine = array.get(zigzaglines, 0)
        lastValue = line.get_y2(lastLine)
        lastIndex = line.get_x2(lastLine)
        
        if(not dirchanged)
            if(dir == 1 and value < lastValue) or (dir == -1 and value > lastValue)
                skip := true
            else
                line.delete(array.shift(zigzaglines))
                label.delete(array.shift(zigzaglabels))
                array.shift(zigzagdir)
                array.shift(zigzagratios)
        if(array.size(zigzaglines) > 0)
            lastLine = array.get(zigzaglines, 0)
            lastValue = line.get_y2(lastLine)
            lastIndex = line.get_x2(lastLine)
            x1 := lastIndex
            y1 := lastValue

    outsideDeviationThreshold = ((abs(y1-y2)*100/y1) > DeviationThreshold)
    if(outsideDeviationThreshold and not skip)
        add_to_zigzaglabels(x1, x2, y1, y2, dir)
        add_to_zigzaglines(x1, y1 , x2, y2, dir)
    if array.size(zigzaglines) > max_array_size
        array.pop(zigzaglines)
        array.pop(zigzaglabels)
        array.pop(zigzagdir)
        array.pop(zigzagratios)

zigzag(length, DeviationThreshold, highSource, lowSource)=>
    [dir, ph, pl] = pivots(length, highSource, lowSource)
    dirchanged = change(dir)
    if(ph or pl)
        add_to_zigzag(dir, dirchanged, ph, pl, bar_index, highSource, lowSource)

highSource = source == close? high : source
lowSource = source == close? low : source

zigzag(Length, DeviationThreshold, highSource, lowSource)

Overview

Bullish and bearish pivots are drawn with green and red lines respectively, while trap zones use orange and lime colors. Labels display pivot labels like HH or HL and ratios between consecutive swings when enabled. The Length parameter controls the swing detection period, and the source input allows choosing different price data. It draws on the main chart pane using lines and labels. The script uses array management for dynamic line and label creation, with limits on maximum counts to prevent performance issues.

Details

Published by

WISEPLAT on GitHub

Code credit

HeWhoMustNotBeNamed, as written in the script's header

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Trend, Support & resistance

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

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

SettingTypeDefaultVariable
sourcesourceclosesource
Lengthint10Length
showPivotsboolfalseshowPivots
showRatiosbooltrueshowRatios
bullishColorcolorcolor.greenbullishColor
bullTrapColorcolorcolor.orangebullTrapColor
bearishColorcolorcolor.redbearishColor
bearTrapColorcolorcolor.limebearTrapColor
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