TradingView
TradingView
12 Th12 2022 13:33

ZigZag 

Polygon / United States DollarCoinbase

Mô tả

█  OVERVIEW


This library is a Pine Script™ programmer’s tool containing custom user-defined types and functions to calculate ​Zig Zag indicators within their scripts. It is not a stand-alone indicator.

Pine Script™ libraries are publications that contain reusable code for importing into Pine Script™ indicators, strategies, and other libraries. For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script™ User Manual.



█  CONCEPTS


​Zig Zag​

​Zig ​Zag​ is a popular indicator that filters out minor price fluctuations to denoise data and emphasize trends. Traders commonly use ​​Zig Zag​ for trend confirmation, identifying potential ​support and ​resistance​, and pattern detection​. It is formed by identifying significant local high and low points in alternating order and connecting them with straight lines, omitting all other data points from their output. There are several ways to calculate the ​Zig Zag​'s data points and the conditions by which its direction changes. This script uses ​pivots as the data points, which are the highest or lowest values over a defined number of bars before and after them. The direction only reverses when a newly formed ​​pivot​ deviates from the last ​​Zig Zag​ point in the opposite direction by an amount greater than or equal to a specified percentage.

To learn more about ​Zig Zag​ and how to calculate it, see this entry from the Help Center.



█ FOR Pine Script™ CODERS


Notes

This script's architecture utilizes user-defined types (UDTs) to create custom objects which are the equivalent of variables containing multiple parts, each able to hold independent values of different types. UDTs are the newest addition to Pine Script™ and the most advanced feature the language has seen to date. The feature's introduction creates a new runway for experienced coders to push the boundaries of Pine. We recommend that newcomers to the language explore the basics first before diving into UDTs and objects.


Demonstration Code

Our example code shows a simple use case by displaying a ​​Zig Zag​ with user-defined settings. A new ​ZigZag object is instantiated on the first bar using a Settings object to control its attributes. The fields for the Settings object are declared using variables assigned to input.* functions, allowing control of the field values from the script's settings. The `update()` function is invoked on each bar to update the ​​ZigZag object's fields and create new lines and labels when required.



Look first. Then leap.



█ TYPES


This library contains the following types:


Settings
  Provides calculation and display attributes to ​ZigZag objects.
  Fields:
    devThreshold: The minimum percentage deviation from a point before the ​ZigZag will change direction.
    depth: The number of bars required for ​pivot detection.
    lineColor: Line color.
    extendLast: Condition allowing a line to connect the most recent ​pivot with the current ​close.
    displayReversalPrice: Condition to display the ​pivot ​price in the ​pivot label.
    displayCumulativeVolume: Condition to display the cumulative ​volume for the ​pivot segment in the ​pivot label.
    displayReversalPriceChange: Condition to display the change in price or percent from the previous ​pivot in the ​pivot label.
    differencePriceMode: Reversal change display mode. Options are "Absolute" or "Percent".
    draw: Condition to display lines and labels.

​Point
  A coordinate containing time and price information.
  Fields:
    tm: A value in UNIX time.
    price: A value on the Y axis (price).

​Pivot
  A level of significance used to determine directional​ movement or potential support​ and resistance.
  Fields:
    ln: A line object connecting the `start` and `end` ​Point objects.
    lb: A label object to display ​pivot values.
    isHigh: A condition to determine if the ​pivot is a ​​pivot high.
    vol: ​​Volume for the ​pivot segment.
    start: The coordinate of the previous ​Point.
    end: The coordinate of the current ​Point.

​ZigZag
  An object to maintain ​Zig Zag​ settings, ​pivots, and ​volume.
  Fields:
    settings: Settings object to provide calculation and display attributes.
    pivots: An array of ​​​Pivot objects.
    sumVol: The ​​volume sum for the ​​​pivot segment.
    extend: ​​Pivot object used to project a line from the last ​​​pivot to the last bar.



█ FUNCTIONS


This library contains the following functions:


last​Pivot(this)
  Returns the last ​​​Pivot of `this` ​​ZigZag if there is at least one ​​Pivot to return, and `na` otherwise.
  Parameters:
    this: (series ​​ZigZag) A ​​ZigZag object.
  Returns: (​Pivot) The last ​​Pivot in the ​​ZigZag.

update(this)
  Updates `this` ​​​ZigZag object with new ​pivots, ​volume, ​lines, labels.
  Parameters:
    this: (series ​​ZigZag) a ​​ZigZag object.
  Returns: (bool) true if a new ​Zig​ Zag​ line is found or the last Zig​ Zag​​ line has changed.

newInstance(settings)
  Instantiates a new ​ZigZag​ object with `settings`. If no settings are provided, a default ​ZigZag​​ object is created.
  Parameters:
    settings: (series Settings) A Settings object.
  Returns: (​ZigZag) A new ​ZigZag​ instance.

Phát hành các Ghi chú

v2

Minor update to function comments.

Phát hành các Ghi chú

v3

A `barIndex` field was added to the `Point` type to allow tracking the bar_index where a ​​pivot occurs:

​Point
  A coordinate containing bar, price, and time information.
  Fields:
    tm: A value in UNIX time.
    price: A value on the Y axis (price).
    barIndex: A `bar_index`.

Phát hành các Ghi chú

v4

This version release comes with the following changes:

 • When the ​Zig​ Zag depth was less than 2, the ​Zig​ Zag calculation would fail. The new logic prevents setting a depth of less than 2.
 • The script now has the option to detect ​​pivot​ highs and ​pivot​ lows in a single bar. This option enhances the ​Zig​ Zag functionality, enabling it to capture double ​pivots​.
 • The library has been modified to utilize user-defined methods​. Pine Script™ methods are special functions associated with instances of specific types that offer a simpler, more convenient syntax.

This update includes the following type and methods:

Settings
  Provides calculation and display attributes to ​ZigZag objects.
  Fields:
    devThreshold: The minimum percentage deviation from a point before the ​Z​igZag will change direction.
    depth: The number of bars required for ​​pivot detection.
    lineColor: Line color.
    extendLast: Condition allowing a line to connect the most recent​​ ​pivot with the current close.
    displayReversalPrice: Condition to display the ​pivot ​price in the ​pivot label.
    displayCumulativeVolume: Condition to display the cumulative ​volume for the ​pivot segment in the ​​pivot label.
    displayReversalPriceChange: Condition to display the change in price or percent from the previous ​​pivot in the ​​pivot label.
    differencePriceMode: Reversal change display mode. Options are "Absolute" or "Percent".
    draw: Condition to display lines and labels.
    allowZigZagOnOneBar: Condition to allow double ​pivots to occur ​ie. when a large bar makes both a ​​pivot high and a ​pivot low.

lastPivot(this)
  Returns the last ​Pivot of `this` ​ZigZag if there is at least one ​Pivot to return, and `na` otherwise.
  Can be used as a method.
  Parameters:
    this: (series ​ZigZag) A ​ZigZag object.
  Returns: (​Pivot) The last ​Pivot in the ​ZigZag.

update(this)
  Updates `this` ​ZigZag object with new ​pivots, ​volume, lines, labels. NOTE: The function must be called on every bar for accurate calculations.
  Can be used as a method.
  Parameters:
    this: (series ​ZigZag) a ​ZigZag object.
  Returns: (bool) true if a new ​Zig Zag line is found or the last ​Zig Zag line has changed.

Phát hành các Ghi chú

v5

Fixed a minor bug that would occasionally cause the Zig Zag to register incorrect pivot points.

Phát hành các Ghi chú

v6

Fixed a minor bug that would occasionally cause the Zig Zag to register incorrect pivot points on symbols with negative prices.

Phát hành các Ghi chú

v7

This version's release includes the following changes:

 • We've eliminated the `Point` user-defined type from the library, as it's now unnecessary. The UDTs and functions in this library version utilize Pine's new chart.point built-in type. Additionally, all parts of the code that handle creation and modification of lines and labels now use chart.point objects to determine their coordinates. The transition to utilizing this type does not affect the functional output of the library in any way.
 • We've refined the library's code comments, annotations, and variable names for clarity and readability.

Removed:

Point
  A coordinate containing bar, price, and time information.


Bình luận
RozaniGhani-RG
Thank you very much.
I never though that library can be written in this way.
PineCoders
@RozaniGhani-RG, We are happy you like it and appreciate your support! Happy coding 💚
oslikpjat
How to return extremum x and y ? want to plot vertical lines from extremum .
cant manage to do this .
what code after
import TradingView/ZigZag/3 as zz
.......
var zz.ZigZag zigZag = zz.newInstance(settings)
zz.update(zigZag)
try bifferent options , not work for me
zz.Point pp = zz.Point.new()
hiLine := line.new(pp.barIndex[1], pp.price[1],pp.barIndex, pp.price[1], color = color.rgb(224, 116, 116), width = 1)
niquedegraaff
Somehow, ZigZagLib.lastPivot(zzBig) always gives me a na. No matter what.
```
var lastPivot = ZigZagLib.lastPivot(zzBig)
if not na(lastPivot)
line.set_color(lastPivot.ln, lastPivot.start.price > lastPivot.end.price ? color.green : lastPivot.start.price < lastPivot.end.price ? color.red : color.gray)
```
moonypto
niquedegraaff
@moonypto, It was a mistake on my end.
moonypto
@niquedegraaff, I see :) hows trading so far?
lets-scalp
@niquedegraaff, okay what was the mistake? I keep getting "na" as well.
mrmanifolder
Please help.

I have been struggling to extract the last zig zag pivot price in a plottable data format for quite some time. The following (in quotation marks) is a minimal code example of my attempt that feels the closest:

"
//@version=5
indicator("Zig Zag Pivot Data Extractor", overlay = true, max_lines_count = 500, max_labels_count = 500)

import TradingView/ZigZag/6 as ZigZagLib

// Create Zig Zag instance from user settings.
var zigZag = ZigZagLib.newInstance(
ZigZagLib.Settings.new(
input.float(5.0, "Price deviation for reversals (%)", 0.00001, 100.0, 0.5, "0.00001 - 100"),
input.int(10, "Pivot legs", 2),
input(#2962FF, "Line color"),
input(true, "Extend to last bar"),
input(true, "Display reversal price"),
input(true, "Display cumulative volume"),
input(true, "Display reversal price change", inline = "priceRev"),
input.string("Absolute", "", ["Absolute", "Percent"], inline = "priceRev"),
true)
)

// Update 'zigZag' object on each bar with new ​pivots, ​volume, lines, labels.
zigZag.update()

// Attempt to extract price of previous pivot
zz_pivots = array.get(zigZag.pivots,0)
zz_prevPivot_price = zz_pivots.start.price

// Attempt to plot price of previous pivot
plot( zz_prevPivot_price , style = plot.style_stepline_diamond , color = color.rgb(255,255,255,50) , linewidth = 2 )
"

The code compiles but I get the following study error: "Error on bar 0: In 'array.get()' function. Index 0 is out of bounds, array size is 0."

Strangely, when I try to check the size of array 'zigZag.pivots' ( by adding "plot( array.size(zigZag.pivots) , style = plot.style_stepline_diamond )" and commenting out the above plot command ), it shows that the array zigZag.pivots is of size > 0 and monotonically increasing with the number of plotted pivots, which seems to contradict the study error.
Some guidance would be greatly appreciated. Thanks in advance!
Seykool
@mrmanifolder, I am having the same issue
Thêm nữa