Indicator · Pine Script v6 · On the chart

ZigZag Swing Cycle Average

by chaise-cogent

The ZigZag Swing Cycle Average indicator measures and analyzes the average duration of bullish and bearish price swings.

View on GitHub

Repaints

GitHub stars5on the repository
Pine versionv6current
Lines of code71
Settings5inputs
LicenceMIT
Last update7 months ago19 Mar 2026

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

71 lines of Pine Script v6 from src/zigzag-swing-cycle-avg-length.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

zigzag-swing-cycle-avg-length.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=6
// © chaise_cogent + https://www.tradingview.com/script/bzIRuGXC-ZigZag/$0
indicator("ZigZag Swing Cycle Average", overlay=true)

// This code tried to be written using the recommendations from the Pine Script® User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/writing/style-guide/
// but failed eventually

import TradingView/ZigZag/8 as zlib

devThreshold    = input.float(3.0, 'Deviation threshold %')
depth           = input.int(12, 'Depth')
allowExtendLast = input.bool(false, 'Allow last in-progress leg')
showZigZag      = input.bool(true, 'Show ZigZag')
lineColor       = input.color(color.blue, 'Line color')
settings        = zlib.Settings.new(
      devThreshold = devThreshold, depth = depth, lineColor = lineColor, 
      extendLast = allowExtendLast, displayReversalPrice = true, displayCumulativeVolume = false,
      displayReversalPriceChange = true, differencePriceMode = "Percent", draw = showZigZag, allowZigZagOnOneBar = true)

var zlib.ZigZag zigZag = zlib.newInstance(settings)

var float upward_avg           = 0
var float downward_avg         = 0
var int   upward_bar_sum       = 0
var int   upward_cycle_count   = 0
var int   downward_bar_sum     = 0
var int   downward_cycle_count = 0

zlib.update(zigZag)

var resultsTable = table.new(position.bottom_right, 4, 3, frame_width  = 1, border_width = 1, border_color = color.gray, bgcolor = color.white)

array<zlib.Pivot> pivots = zigZag.pivots

if barstate.islast
    for [index, pivot] in pivots
        int bar_count_difference = pivot.end.index - pivot.start.index
        if index <= array.size(pivots) - (allowExtendLast ? 1 : 2)
            log.info(
               'i={0}, bar-start{1}, bar-end={2}, px-start={3}, px-end={4}', 
               index, pivot.start.index, pivot.end.index, pivot.start.price, pivot.end.price
               )
            // Upward trend
            if pivot.start.price < pivot.end.price
                upward_bar_sum := upward_bar_sum + bar_count_difference
                upward_cycle_count += 1
            // Downward trend
            else
                downward_bar_sum := downward_bar_sum + bar_count_difference
                downward_cycle_count += 1
    
    upward_avg := upward_bar_sum / upward_cycle_count
    downward_avg := downward_bar_sum / downward_cycle_count

    table.clear(resultsTable, 0, 0, 3, 2)
    table.cell(resultsTable, 0, 0, 'Direction', text_formatting = text.format_bold)
    table.cell(resultsTable, 1, 0, 'Avg Cycle Len', text_formatting = text.format_bold)
    table.cell(resultsTable, 2, 0, 'Total Bars', text_formatting = text.format_bold)
    table.cell(resultsTable, 3, 0, 'Cycles', text_formatting = text.format_bold)
    table.cell(resultsTable, 0, 1, 'Up', text_formatting = text.format_bold)
    table.cell(resultsTable, 0, 2, 'Down', text_formatting = text.format_bold)

    table.cell(resultsTable, 1, 1, str.tostring(math.round(upward_avg, 0)))
    table.cell(resultsTable, 2, 1, str.tostring(upward_bar_sum))
    table.cell(resultsTable, 3, 1, str.tostring(upward_cycle_count))

    table.cell(resultsTable, 1, 2, str.tostring(math.round(downward_avg, 0)))
    table.cell(resultsTable, 2, 2, str.tostring(downward_bar_sum))
    table.cell(resultsTable, 3, 2, str.tostring(downward_cycle_count))

Overview

ZigZag Swing Cycle Average utilizes TradingView's built-in ZigZag library to detect pivot legs based on configurable percentage deviation thresholds and depth parameters. On the latest bar, the script calculates the total bars, number of cycles, and average cycle lengths for both upward and downward swings. It presents these analytics in a clean summary table positioned in the bottom-right corner while optionally rendering the ZigZag lines directly on the price chart.

Details

Published by

chaise-cogent on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Screeners & dashboards, 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
Deviation threshold %float3.0devThreshold
Depthint12depth
Allow last in-progress legboolfalseallowExtendLast
Show ZigZagbooltrueshowZigZag
Line colorcolorcolor.bluelineColor
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 6 weeks ago · None stated GitHub repository of SPX Midnight Box + Snag Logic
218 stars

TradersPost Trading Checklist is an overlay indicator that evaluates a suite of popular technical conditions for long and short trade setups. It checks session-anchored VWAP, fast and slow EMA alignments and crosses, 200 SMA, RSI overbought or oversold conditi

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of TradersPost Trading Checklist
92 stars

This indicator classifies the market into gamma regime types (negative gamma trend, positive gamma mean-reversion, or transition) by calculating a composite score based on daily ATR ratios, session VWAP crossover frequencies, and opening range displacement. It

Indicator v5 Volatility & bandsTrend
Updated 8 weeks ago · Custom licence GitHub repository of Moon Dev GEX Regime & Trap

EMA Ribbon Overlay

by iamrichardD
57 stars

Calculates exponential moving averages for fast, pivot, and slow lengths along with optional 50, 100, and 200 simple moving average context lines. It visualizes bullish and bearish ribbon fills on the main price chart alongside MACD calculations to generate ea

Indicator v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon Overlay
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

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