Indicator · Pine Script v5 · On the chart

Zig Zag Ratio Simplified

by WISEPLAT· code credited to RozaniGhani-RG

Zig Zag Ratio Simplified plots ZigZag trend lines connecting swing highs and lows on the price chart.

View on GitHub

Repaints

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code170
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

170 lines of Pine Script v5 from ZigZag - ishod/Zig Zag Ratio Simplified - 7.pine.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Zig Zag Ratio Simplified - 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/
// © RozaniGhani-RG

//@version=5
indicator('Zig Zag Ratio Simplified', 'ZZRS', overlay = true)

// 0. Inputs
// 1. Variables
// 2. Switches
// 3. Custom Functions
// 4. Calculations
// 5. Constructs

// ============================================================================= 0.  Inputs {
T0        = 'Default : 10\nMin : 2\nMax : 50'
i_i_len   = input.int(          10, 'Length', minval = 2, maxval = 50, tooltip = T0)
i_s_dir   = input.string(   'Both', 'Show Colored Ratios', options = ['Both', 'Main', 'Sub', 'none'])
i_b_stat  = input.bool(      false, 'Show Ratio Status')
i_b_HL    = input.bool(      false, 'Show High Low Labels')
G1        = 'HELPER'
T1        = '1) Tick to show table\n2) Small font size recommended for mobile app or multiple layout'
T2        = 'Table must be tick before change table position'
i_b_table = input.bool(     false,  'Show Helper |', group = G1, inline = 'Table1')
i_s_font  = input.string('normal',      'Font size', group = G1, inline = 'Table1', options = ['tiny',  'small', 'normal', 'large', 'huge'], tooltip = T1)
i_s_Y     = input.string('bottom', 'Table Position', group = G1, inline = 'Table2', options = [ 'top', 'middle', 'bottom'])
i_s_X     = input.string(  'left',               '', group = G1, inline = 'Table2', options = ['left', 'center', 'right'],                   tooltip = T2)
// }
// ============================================================================= 1.  Variables {
// ————————————————————————————————————————————————————————————————————————————— 1.1 Highest / Lowest {
float PH = ta.highestbars(high, i_i_len) == 0 ? high : na
float PL = ta.lowestbars(low,   i_i_len) == 0 ? low  : na
// }
// ————————————————————————————————————————————————————————————————————————————— 1.2 Dir {
var int dir = 0, dir := PL and na(PH) ? -1 : PH and na(PL) ? 1 : dir
// }
// ————————————————————————————————————————————————————————————————————————————— 1.3 Bool {
bool bool_both = dir == -1 or dir == 1, bool bool_pos  = dir ==  1,      bool bool_neg  = dir == -1
// }
// ————————————————————————————————————————————————————————————————————————————— 1.4 Array {
var max_array_size = 10,                 var zigzag = array.new_float(0),  oldzigzag  = array.copy(zigzag)
// }
// ————————————————————————————————————————————————————————————————————————————— 1.5 Others {
var line line_zz        = na, var line line_ratio   = na
var linefill fill_ratio = na
var label label_zz      = na, var label label_ratio = na
var string ratio_true   = na, var string ratio_icon = na, var string str_stat = na
var float ratio         = na
var color color_ratio   = na
var TBL = table.new(i_s_Y + '_' + i_s_X, 2, 5, border_width = 1)
// }
// }
// ============================================================================= 2.  Switches {
[sw_up, sw_dn] = switch i_b_HL
    false => [color.new(color.teal, 100), color.new(color.red, 100)]
    true  => [color.new(color.teal,   0), color.new(color.red,   0)]
bool_dir = switch i_s_dir
    'Both' => bool_both
    'Main' => bool_pos
    'Sub'  => bool_neg
// }
// ============================================================================= 3.  Custom Functions {
add_to_zigzag(float[] pointer, float value, int bindex) =>
    array.unshift(pointer, bindex)
    array.unshift(pointer, value)
    if array.size(pointer) > max_array_size
        array.pop(pointer)
        array.pop(pointer)
update_zigzag(float[] pointer, float value, int bindex, int dir) =>
    if array.size(pointer) == 0
        add_to_zigzag(pointer, value, bindex)
    else
        if dir == 1 and value > array.get(pointer, 0) or dir == -1 and value < array.get(pointer, 0)
            array.set(pointer, 0, value)
            array.set(pointer, 1, bindex)
        0.
calc_ratio(float[] _float) =>
    math.abs(array.get(_float, 0) - array.get(_float, 2)) / math.abs(array.get(_float, 2) - array.get(_float, 4))
get_color(float _float) =>
    _float  >= 0.371 and _float <= 0.930 ? color.red :
     _float >= 1.130 and _float <= 3.618 ? color.blue :
     _float >  0.930 and _float <  1.130 ? color.purple :
     color.gray
get_stat(float _float) =>
    _float  >= 0.371 and _float <= 0.930 ? '\nRETRACEMENT'         :
     _float >= 1.130 and _float <= 3.618 ? '\nPROJECTION'          :
     _float >  0.930 and _float <  1.130 ? '\nDOUBLE\nTOP\nBOTTOM' :
     na
get_icon(float _float) =>
    _float  >= 0.371 and _float <= 0.930 ? '✅' :
     _float >= 1.130 and _float <= 3.618 ? '✅' :
     _float >  0.930 and _float <  1.130 ? '❌' :
     '❌'
string_HL(int _int, float[] _float) =>
    _int == 1 ?
     array.get(_float, 0) > array.get(_float, 4) ? 'HH' : 'LH' :
     array.get(_float, 0) < array.get(_float, 4) ? 'LL' : 'HL'
line_HL(int _int, float[] _float) =>
    _int == 1 ?
     array.get(_float, 0) > array.get(_float, 2) ? color.teal : color.red :
     array.get(_float, 0) < array.get(_float, 2) ? color.red  : color.teal
switch_color(int _int, float[] _float) =>
    _int == 1 ?
     array.get(_float, 0) > array.get(_float, 4) ? sw_up : sw_dn :
     array.get(_float, 0) < array.get(_float, 4) ? sw_dn : sw_up
row_text(int _column, int _row, string _str1, string _str2, color _color) =>
    table.cell(TBL, _column,     _row, _str1, text_color = color.white, bgcolor = _color, text_size = i_s_font)
    table.cell(TBL, _column + 1, _row, _str2, text_color = color.white, bgcolor = _color, text_size = i_s_font)
// }
// ============================================================================= 4.  Calculations {
dirchanged = ta.change(dir)
if PH or PL
    if dirchanged
        add_to_zigzag(zigzag, dir == 1 ? PH : PL, bar_index)
    else
        update_zigzag(zigzag, dir == 1 ? PH : PL, bar_index, dir)
// }
// ============================================================================= 5.  Constructs {
if array.size(zigzag) >= 6
    if array.get(zigzag, 0) != array.get(oldzigzag, 0) or array.get(zigzag, 1) != array.get(oldzigzag, 1)
        if array.get(zigzag, 2) == array.get(oldzigzag, 2) and array.get(zigzag, 3) == array.get(oldzigzag, 3)
            line.delete(line_zz)
            line.delete(line_ratio)
            label.delete(label_zz)
            label.delete(label_ratio)
        line_zz    := line.new(
                             x1    = math.round(array.get(zigzag, 1)),
                             y1    =            array.get(zigzag, 0),
                             x2    = math.round(array.get(zigzag, 3)),
                             y2    =            array.get(zigzag, 2),
                             color = dir == 1 ? color.teal : color.red,
                             width = 2)
        line_ratio := line.new(
                             x1    = math.round(array.get(zigzag, 1)),
                             y1    =            array.get(zigzag, 0),
                             x2    = math.round(array.get(zigzag, 5)),
                             y2    =            array.get(zigzag, 4),
                             color = color.new(color.blue, 100))
        fcol       = line_HL(     1, zigzag)
        text_HL    = string_HL(   1, zigzag)
        txtcol     = switch_color(1, zigzag)
        label_zz  := label.new(
                                 x         = math.round(array.get(zigzag, 1)),
                                 y         =            array.get(zigzag, 0),
                                 text      = text_HL,
                                 color     = color.new(color.blue, 100),
                                 textcolor = txtcol,
                                 style     = dir == 1 ? label.style_label_down : label.style_label_up)
        ratio       := calc_ratio(zigzag)
        color_ratio := get_color(ratio)
        ratio_true  := get_stat(ratio)
        ratio_icon  := get_icon(ratio)
        str_stat    := i_b_stat ? ratio_true : na
        label_ratio := label.new(
                             x         = math.round(array.get(zigzag, 3)),
                             y         = math.avg(  array.get(zigzag, 0), array.get(zigzag, 4)),
                             text      = str.tostring(ratio, '0.000 ') + ratio_icon + str_stat,
                             color     = color.new(color.blue, 100),
                             textcolor = color_ratio,
                             style     = label.style_label_center,
                             tooltip   = str.tostring(ratio, '0.000 ') + ratio_icon + ratio_true)
        if bool_dir
            fill_ratio := linefill.new(line_zz, line_ratio, color.new(color_ratio, 85))
        else
            fill_ratio := linefill.new(line_zz, line_ratio, color.new(color_ratio, 100))
if barstate.islast
    if i_b_table
        row_text(0, 0,         'RETRACEMENT', '0.371 <= PRICE <= 0.930', color.red)
        row_text(0, 1,          'PROJECTION', '1.130 <= PRICE <= 3.618', color.blue)
        row_text(0, 2, 'DOUBLE TOP / BOTTOM',   '0.930 < PRICE < 1.130', color.purple)
// }

Overview

Zig Zag Ratio Simplified calculates ratio relationships between market swings, displaying ratio labels, high and low price tags, and an optional status helper table. Main settings allow users to set the swing evaluation length, toggle ratio displays, and customize table positioning. Note that like traditional ZigZag tools, pivot points and ratios update retroactively on live bars until confirmed.

Details

Published by

WISEPLAT on GitHub

Code credit

RozaniGhani-RG, as written in the script's header

Draws

On the price chart

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
Lengthint10i_i_len
Show Colored RatiosstringBothi_s_dir
Show Ratio Statusboolfalsei_b_stat
Show High Low Labelsboolfalsei_b_HL
Show Helper |boolfalsei_b_table
Font sizestringnormali_s_font
Table Positionstringbottomi_s_Y
i_s_Xstringlefti_s_X
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

257 stars

This indicator overlays an intraday SPX and ES chart with a midnight session range, regular-trading-hours opening levels, and a VWAP projection box. It draws the midnight high, mid, and low, flags edge rejections within an absolute tolerance, and plots optiona

Indicator v6 TrendSupport & resistance
Updated 7 weeks ago · None stated GitHub repository of SPX Midnight Box + Snag Logic
53 stars

Apex Trend & Liquidity Master calculates a trend cloud using customizable moving averages expanded by a volatility multiplier directly on the main price chart. It identifies dynamic support and resistance liquidity zones from swing high and low pivots, extendi

Indicator v6 TrendSupport & resistance
Updated 2 months ago · MPL-2.0 GitHub repository of Apex Trend & Liquidity Master

Market Monitor - 1m

by chris-c-thomas
14 stars

Market Monitor - 1m is an overlay indicator designed for multi-chart monitoring and directional bias assessment. It plots a fast, mid, and slow EMA ribbon with a fill cloud, session VWAP with standard deviation bands, and previous day key levels. It evaluates

Indicator v6 TrendMoving averages Repaints
Updated 6 months ago · MIT GitHub repository of Market Monitor - 1m
13 stars

The Adaptive Trend Finder calculates logarithmic linear regression channels overlaid on the price chart. Operating on the most recent historical bar, it fits a log-transformed regression line and standard deviation bands. It evaluates linear correlation using

Indicator v6 TrendSupport & resistance Repaints
Updated 6 months ago · MIT GitHub repository of Adaptive Trend Finder (log)

5 EMAs

by hirawatt
11 stars

5 EMAs calculates and plots five Exponential Moving Averages derived from five configurable timeframes directly onto the main price chart. It also plots the high and low lines fetched from an additional custom timeframe, accompanied by a small on-screen table

Indicator v4 Moving averagesTrend Repaints
Updated 2 years ago · MIT GitHub repository of 5 EMAs
9 stars

Adaptive Supertrend is an overlay indicator that dynamically adjusts its Supertrend band width using a composite conviction score. Conviction is derived from ATR percentile ranking, trend force from EMA distance, and chop detection, narrowing the bands during

Indicator v6 TrendVolatility & bands
Updated 3 days ago · MIT GitHub repository of Adaptive Supertrend

More Support & resistance scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers