ZigZag Segmentation
Install and import#
npm install fintech-algorithmsimport { 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#
| Name | Type | Notes |
|---|---|---|
closes | number[] | Observation series in chronological order, oldest first. |
threshold | number | Minimum retracement, as a fraction, before a reversal is accepted. min: 0 |
minBars | number | Minimum 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#
[100, 103, 106, 101, 100]0.052Call#
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#
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.
References#
- Zig Zag indicator — QuantConnect
- LEAN ZigZag source — QuantConnect
- Pine Script Concepts: Repainting — TradingView