Indicator · Pine Script v4 · On the chart

ZigZag Supertrend

by WISEPLAT· code credited to HeWhoMustNotBeNamed

This overlay indicator draws a ZigZag from recent pivot highs and lows and feeds those extremes into a Supertrend-style calculation that uses ATR.

View on GitHub

Repaints

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

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

ZigZag Supertrend - 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 Supertrend", shorttitle="ZZ-Supertrend", overlay=true, max_lines_count=500, max_labels_count=500)
source=input(close)
Length = input(5, minval=0, step=5)
DeviationThreshold = 0
history = input(2, step=1, minval=2)
waitForConfirmation = input(true)
waitForClose = input(true)

atrPeriods = input(22, step=5)
atrMult = input(1, step=0.5)
var zigzaglines = array.new_line(0)
var zigzagpivots = array.new_float(0)
int max_array_size = history

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
    eDir

add_to_zigzaglines(x1, y1 , x2, y2, dir)=>
    eDir = get_edir(dir, y2)
    zgColor = color.new(#FFFFFF, 100)
    zline = line.new(x1=x1, y1=y1, 
         x2 = x2, y2=y2,
         color=zgColor, width=2, style=line.style_solid)
    array.unshift(zigzaglines, zline)

add_to_zigzag(dir, dirchanged, ph, pl, index, highSource, lowSource)=>
    value = (dir == 1? ph : pl)
    
    lowestVal = lowest(lowSource, Length)
    highestVal = highest(highSource, Length)
    lowestBar = lowestbars(lowSource, Length)
    highestBar = highestbars(highSource,Length)
    y1= dir == 1? lowestVal : highestVal
    x1 = bar_index + (dir == 1? lowestBar : highestBar)
    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))
                skip := false
                
        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_zigzaglines(x1, y1 , x2, y2, dir)
    if array.size(zigzaglines) > max_array_size
        line.delete(array.pop(zigzaglines))

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)

get_high_low()=>
    array.clear(zigzagpivots)
    startIndex = waitForConfirmation? 1 : 0
    if(array.size(zigzaglines) > startIndex)
        for i=startIndex to array.size(zigzaglines)-1
            zgLine = array.get(zigzaglines, i)
            y1 = line.get_y1(zgLine)
            y2 = line.get_y2(zgLine)
            array.unshift(zigzagpivots,y1)
            array.unshift(zigzagpivots,y2)
        
    top = array.max(zigzagpivots)
    bottom = array.min(zigzagpivots)
    [top, bottom]

supertrend_zg(top, bottom)=>
    dir = 1
    prevDir = nz(dir[1], dir)
    
    atrDiff = atr(atrPeriods) * atrMult
    buyStop = bottom - atrDiff
    buyStopPrev = nz(buyStop[1], buyStop)
    sellStop = top + atrDiff
    sellStopPrev = nz(sellStop[1], sellStop)
    
    buyStop := prevDir == 1? max(buyStop, buyStopPrev) : buyStop
    sellStop := prevDir == -1? min(sellStop, sellStopPrev) : sellStop
    
    bullishCrossover = crossover(waitForClose? close : high, sellStopPrev)
    bearishCrossunder = crossunder(waitForClose? close : low, buyStopPrev)
    dir := (prevDir == 1 and bearishCrossunder)? -1 :
                 (prevDir == -1 and bullishCrossover)? 1:
                 prevDir
    [dir, buyStop, sellStop]
    
highSource = source == close? high : source
lowSource = source == close? low : source

zigzag(Length, DeviationThreshold, highSource, lowSource)
[top, bottom] = get_high_low()
[dir, buyStop, sellStop] = supertrend_zg(top, bottom)

plot(dir == 1? buyStop : na, color= color.green, title="BuyStop",linewidth=2, style=plot.style_linebr)
plot(dir == -1? sellStop : na, color= color.red, title="SellStop",linewidth=2, style=plot.style_linebr)
alertcondition(dir != dir[1], "Supertrend direction update", "Supertrend direction reversal observed")

Overview

Pivot length, stored history, and ATR period and multiplier change how swings and the trend band form. Optional waits for confirmation and bar close delay updates. Lines sit on the price chart. The last ZigZag segment can be replaced when a more extreme pivot appears, so recent swings can change.

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, Volatility & bands, Support & resistance

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
sourcesourceclosesource
Lengthint5Length
historyint2history
waitForConfirmationbooltruewaitForConfirmation
waitForClosebooltruewaitForClose
atrPeriodsint22atrPeriods
atrMultint1atrMult
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

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

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

ATR Trailing Stop

by mihakralj
99 stars

Calculates an ATR-based trailing stop overlaid on the price chart to assist with trend identification and stop placement. Using a specified ATR period and multiplier, it projects upper and lower bounds around the closing price. The stop line ratchets up during

Indicator v5 TrendVolatility & bands
Updated 4 weeks ago · Apache-2.0 GitHub repository of ATR Trailing Stop

Moon Dev Lunar Sniper

by moondevonyt
92 stars

Moon Dev Lunar Sniper is a multi-indicator overlay that scores confluence across fast and slow EMAs, RSI, MACD, DMI, and BB width to fire signals only when score meets the minimum threshold. It plots buy and sell signals on the price chart, highlights cosmic b

Indicator v6 TrendOscillators & momentum Repaints
Updated 8 weeks ago · Custom licence GitHub repository of Moon Dev Lunar Sniper

SuperTrend & Pivots

by dcaoyuan
55 stars

This overlay indicator plots a SuperTrend line on the price chart using a fixed ATR length of 10 and a factor of 3. When the trend direction is up it draws a green line and a light green fill toward the candle midpoint; when down it draws a red line and a ligh

Indicator v6 TrendVolatility & bands
Updated 6 months ago · Apache-2.0 GitHub repository of SuperTrend & Pivots

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