OPEN-SOURCE SCRIPT
Обновлено Harmonic Patterns [kingthies]

Harmonic Patterns [kingthies]
What it does
PRZ (Potential Reversal Zone)
How to use
Settings overview
Alerts
Notes
This indicator scans price swings for classic X-A-B-C-D harmonic patterns and plots the structure plus a PRZ (Potential Reversal Zone) to help you frame areas where reactions are statistically more likely. It supports both bullish and bearish setups and can trigger alerts when a new D pivot confirms a pattern.
What it does
- Builds a pivot-based swing map (ZigZag-style) using a configurable Pivot Length.
- Evaluates the most recent 5 swing points (X, A, B, C, D) against harmonic ratio rules with a user-defined tolerance.
- Detects: Gartley, Bat, Butterfly, Crab, Deep Crab, Cypher, Shark (loose).
- Draws the pattern legs (X-A-B-C-D), labels the detection with ratio readouts, and projects a PRZ using 3 target levels (derived from XA/BC logic per pattern).
- Offers two rendering modes:
- Best only: picks the closest match (lowest score) to reduce clutter.
- Show all: plots every valid match (uses filled PRZ boxes to keep object usage under control).
PRZ (Potential Reversal Zone)
- PRZ is built from three target levels and expanded into a zone.
- Optional padding uses ATR (ATR multiplier) to widen/narrow the zone for volatility.
- Display modes: Off, Box, Lines, Both.
- Zones can be extended forward by a configurable number of bars to keep the area visible as price develops.
How to use
- Start with Confirm only when D pivot forms enabled (recommended) to reduce false positives while patterns are still forming.
- Adjust Pivot Length based on timeframe:
- Lower values = more swings, more signals, more noise.
- Higher values = cleaner structures, fewer signals.
- Use Ratio Tolerance to control strictness:
- Lower tolerance = fewer, higher-confidence matches.
- Higher tolerance = more matches, potentially lower quality.
- Treat harmonics as context, not a standalone entry system:
- Look for confluence (HTF levels, structure, volume, momentum/RSI divergence, etc.).
- Use your own confirmation and risk plan (invalidations beyond PRZ / beyond D).
Settings overview
- Swings (Pivot ZigZag)
- Pivot Length: pivot sensitivity.
- Use Wicks: uses High/Low; if off, uses Close.
- Max Stored Swings: limits stored pivots for performance/object control.
- Harmonic Detection
- Ratio Tolerance (%): allowed deviation around ideal ratios.
- Confirm only when D pivot forms: reduces repaint-like behavior.
- When multiple match: Best only vs Show all.
- Pattern Filters enable/disable each pattern type.
- PRZ
- PRZ Display: Off / Box / Lines / Both.
- PRZ Padding (ATR multiplier): volatility-adjusted zone padding.
- PRZ Extend (bars): how far to project the zone.
- Visuals
- Draw Legs: draws X-A-B-C-D.
- Show Pattern Label: prints pattern name, direction, ratios, and score.
- Label Offset: shift label forward if you want more space.
Alerts
- “Bullish/Bearish Harmonic (Any)” triggers on any detected pattern.
- Per-pattern alerts are included for each supported pattern type.
Notes
- This indicator is educational and intended to assist with pattern recognition and confluence mapping.
- Harmonic patterns do not guarantee reversals—always manage risk and confirm with your own process.
Информация о релизе
Summary of changesCompile fixes
Replaced all comma-chained var declarations with individual lines
Replaced comma-chained := assignments inside if blocks with separate statements
Removed nested function definition (pushPattern was inside the else block, illegal in Pine v6)
Removed unused getActivePattern and updateBestOnlyLegsAndPrz cruft
Logic fixes
Added strict X-A-B-C-D pivot alternation check (isBullStruct / isBearStruct) so only valid zig-zag sequences evaluate
Fixed confirmOnD: now actually waits pivotLen bars for pivot confirmation instead of being a no-op
Cypher: rewrote to use proper BC/XA extension (1.13-1.414) and 0.786 retracement of XC. Also requires C to extend beyond A
Shark: rewrote to use BC/XA extension and 0.886-1.13 XA retracement (correct PRZ logic for the structure)
Butterfly PRZ: corrected confluence to XA 1.272 ∩ BC 1.618-2.24 (was mixing inconsistent levels)
Tolerance cleanup
Added nearRatio() for single-value targets (e.g., exact 0.618, 0.886)
inRangeTol() retained for natural ranges only
Visual fixes
"Show all" mode now staggers labels vertically using ATR to prevent overlap
Legs drawn once per detection in show-all mode (was drawn per pattern, causing 28 overlapping lines)
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Eric Thies
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Eric Thies
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.