fintech-algorithms
Using a coding agent? Give it the skill: npx skills add IslamBaraka90/Fintech-Algorithms-Library What it does →

ZigZag Segmentation

Install and import#

bash
npm install fintech-algorithms
ts
import { zigzagSegment } from "fintech-algorithms/geometric-chart-patterns/pivots-and-levels/zigzag-segmentation";

Signature#

zigzagSegment(closes, threshold, minBars)

Segments a series into alternating swings that exceed a percentage threshold. Useful for structure, and routinely misused: the final swing is provisional and can be revised by the next bar.

Parameters#

NameTypeNotes
closesnumber[]Observation series in chronological order, oldest first.
thresholdnumberMinimum retracement, as a fraction, before a reversal is accepted.
min: 0
minBarsnumberMinimum bars a swing must span.
min: 1 · integer: true

Returns#

{ pivots, states }

The pivots with a per-bar state, which is what shows the last swing is still open rather than settled.

Errors#

  • When threshold is not positive — throws

Complexity: time O(n), space O(n).

Worked example#

verified This is the worked example published in the article, replayed by the test suite on every run. The output cannot drift.

Input#

closes
[100, 103, 106, 101, 100]
threshold
0.05
minBars
2

Call#

zigzagSegment(closes, threshold, minBars)

Returns#

object with 1 field: pivots

{
  "pivots": [
    {
      "kind": "low",
      "event_index": 0,
      "confirmation_index": 2,
      "price": 100
    },
    {
      "kind": "high",
      "event_index": 2,
      "confirmation_index": 4,
      "price": 106
    }
  ]
}

Diagrams#

ZigZag Segmentation — failure atlas
ZigZag Segmentation — family handoff
ZigZag Segmentation — knowledge time
ZigZag Segmentation — parameter boundary

Calculation flow#

ZigZag Segmentation calculation flow
stateDiagram-v2
    [*] --> Searching
    Searching --> Up: low reverses upward by tau and min bars
    Searching --> Down: high reverses downward by tau and min bars
    Up --> Up: strictly higher close moves provisional high
    Up --> Down: decline reaches tau and confirms high
    Down --> Down: strictly lower close moves provisional low
    Down --> Up: advance reaches tau and confirms low

How it works#

This page states the contract — how to call it correctly. The article explains the concept: why it works, and where it breaks.

Read the article →

References#

  • Zig Zag indicator — QuantConnect
  • LEAN ZigZag source — QuantConnect
  • Pine Script Concepts: Repainting — TradingView

The rest of the Pivots and Levels family#