ABCD Pattern Finder**Detailed Indicator Description**
Your indicator is an **ABCD Pattern Finder** for TradingView. It scans price action for swing-based **AB=CD harmonic-style patterns**, confirms whether the pattern meets your rules, then plots the pattern and related trade levels directly on the chart.
**Core Purpose**
The indicator is designed to find situations where price makes:
**A to B:** an initial impulse move.
**B to C:** a retracement or pullback.
**C to D:** a second move that is approximately equal to the A-to-B move.
When the C-to-D leg completes and passes the filter rules, the indicator treats point **D** as the trade-confirmation area. It then displays an entry reference, stop loss, and three take-profit levels.
**Bullish and Bearish Logic**
A **bullish setup** is one where the completed pattern suggests a potential long trade after point D.
A **bearish setup** is one where the completed pattern suggests a potential short trade after point D.
The indicator uses the sequence of highs and lows to decide whether the pattern is bullish or bearish. It does not simply mark every four-point swing; the swing sequence must form a valid ABCD structure.
**Zigzag Inputs**
**Pivot Bars Left** controls how many bars to the left must be considered when confirming a swing high or swing low.
**Pivot Bars Right** controls how many bars to the right must pass before a pivot is confirmed.
Higher values make the indicator less sensitive and produce fewer patterns. Lower values make it more sensitive and produce more patterns, but with more noise.
**Pattern Quality Inputs**
**Min CD/AB Time Ratio** sets the minimum amount of time the CD leg must take compared with the AB leg. This prevents CD from forming too quickly.
**Max CD/AB Time Ratio** sets the maximum amount of time CD can take compared with AB. This prevents slow, dragged-out CD legs from qualifying.
**AB=CD Equality Tolerance** controls how close the CD leg must be to the AB leg in price size. A value of **0.10** means CD can be within plus or minus 10% of AB.
**Min BC Retracement of AB** sets the shallowest acceptable pullback from B to C.
**Max BC Retracement of AB** sets the deepest acceptable pullback from B to C.
**Min AB Size ATR Multiple** requires the AB leg to be large enough compared with ATR. This helps filter out small, low-quality patterns.
**ATR Length** controls the ATR calculation used for volatility-based filtering and stop placement.
**Disallow Pattern Overlap** prevents a new pattern from being confirmed inside the range of an already confirmed pattern.
**Trade Inputs**
**Stop ATR Buffer Beyond D** places the stop loss beyond point D by a volatility-based buffer. A larger value gives the trade more room, while a smaller value creates a tighter stop.
**TP1 Fibonacci Level** sets the first profit target based on the A-to-D range.
**TP2 Fibonacci Level** sets the second profit target.
**TP3 Fibonacci Level** sets the third profit target.
The default target structure is TP1 at **0.618**, TP2 at **1.0**, and TP3 at **1.382** of the A-to-D range.
**Display Inputs**
**Trade Display Bars Forward** controls how far the entry, stop, and target lines extend to the right of the current candle.
**Show Trade Levels** turns entry, stop loss, and target lines on or off.
**Show ABCD Lines** turns the A-B, B-C, and C-D pattern lines on or off.
**Show ABCD Labels** turns the A, B, C, and D labels on or off.
You can also customize colors for the confirmed pattern, entry line, stop line, and target lines.
**Historical Pattern Inputs**
**Show Historical AB=CD Patterns** controls whether older confirmed patterns remain visible.
**Historical Closed Lookback** controls how many recently closed patterns are included in the historical visual/stat window.
**Closed Trade Lookback** lets you visually rewind and highlight a previous closed trade. A value of **0** shows the most recent trade. A value of **1** shows the trade before that.
**Closed Trade Lookback Color** controls the color used when reviewing an older closed trade.
**Confirmation Triangles**
The indicator can plot a triangle when a pattern is confirmed.
A bullish confirmation uses the bullish triangle color.
A bearish confirmation uses the bearish triangle color.
You can turn these triangles on or off and choose their size: **Tiny, Small, Normal, or Large**.
**AD Line Inputs**
The indicator can draw a line from point **A** to point **D**, extended to the right.
You can control whether this line appears, plus its color, width, and style: **Solid, Dashed, or Dotted**.
**Stats Window**
The stats window displays historical performance for TP1, TP2, and TP3.
For each target, it shows:
**Wins:** how many closed trades reached that target.
**Closed:** how many closed trades were evaluated.
**Rate:** the win rate for that target.
The stats are recalculated using your current trade input settings, so changing stop or target values updates the displayed historical results.
**Alerts**
The indicator includes two alerts:
**New ABCD Pattern Detected** triggers when a valid pattern is found.
**ABCD Pattern Entry at D** triggers when the pattern confirmation/entry condition occurs at point D.
Penunjuk

ABCD Harmonic Projection [WillyAlgoTrader]📐 ABCD Harmonic Projection is an overlay indicator that automatically detects ABCD harmonic patterns from ZigZag pivots, validates them against Fibonacci ratio constraints (BC/AB retracement + CD/AB extension), scores each pattern with a 4-factor quality engine (0–100), projects the D-point completion zone, and draws Target and Stop zones with Fibonacci extension and retracement levels — with full TP/SL outcome tracking and separate bull/bear win rate statistics.
The ABCD pattern is one of the foundational harmonic structures: four alternating swing points (A→B→C→D) where the BC leg retraces a Fibonacci portion of the AB leg, and the CD leg extends from C toward a projected D-point that is a Fibonacci ratio of the AB leg. When price reaches the D-point, the pattern completes — and a reversal or continuation move is expected. This indicator automates the entire detection-to-target workflow: find the swings, measure the ratios, validate the geometry, project the target, and track the outcome.
🧩 WHY THESE COMPONENTS WORK TOGETHER
Manually identifying ABCD patterns requires eyeballing four pivot points, measuring two Fibonacci ratios, estimating the D-point projection, and drawing the target zone — across multiple instruments and timeframes. Most traders miss patterns or miscalculate ratios.
This indicator chains each step into an automated pipeline:
ZigZag pivot detection → 4-point ABCD extraction → BC/AB ratio validation → CD/AB extension calculation → D-point projection → 4-factor quality scoring → Target Zone + Stop Zone placement → Fibonacci extension/retracement overlay → TP/SL outcome tracking → Win rate statistics
The ZigZag engine ensures only confirmed alternating swings are used (no noise pivots). The ratio validation filters patterns to only those within Fibonacci-valid ranges. The quality scoring ranks patterns by how close they are to ideal geometry. The D-point projection gives a specific price target — not a vague area. And the Target/Stop zones provide precise trade management levels anchored to the pattern's own geometry.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ ZigZag pivot engine with direction management.
The indicator uses a directional ZigZag that enforces strict alternation: after a swing high, only a swing low is accepted (and vice versa). If price makes a higher high during an existing up-leg, the previous swing high is updated in place (not duplicated). This prevents the common problem of multiple consecutive highs being treated as separate pivots.
Pivots are detected using ta.pivothigh/ta.pivotlow with configurable lookback (default 8 bars). The ZigZag stores prices, bar indices, and directions in parallel arrays — providing the last 200 pivots for pattern scanning.
2️⃣ Fibonacci-validated ABCD pattern detection.
When a new pivot is confirmed and at least 4 pivots exist, the indicator extracts the most recent A, B, C points and validates:
— BC/AB retracement ratio : must be between minBcAbRatio (default 0.382) and maxBcAbRatio (default 0.886). Classic ABCD ratios are 0.382, 0.500, 0.618, 0.786, and 0.886. Patterns outside this range are rejected.
— ATR minimum swing filter : the AB leg must be at least 1× ATR in size — filtering out noise patterns during low-volatility bars.
— Minimum leg depth : AB must span at least 3 bars — ensuring the pattern has temporal structure, not just a single spike.
Pattern direction: if B > A → bullish ABCD (D projected above C). If B < A → bearish ABCD (D projected below C).
The D-point is projected from C using the average of the configurable CD/AB ratio range: projectedD = C + direction × |AB| × avgCdAbRatio.
3️⃣ 4-factor pattern quality scoring (0–100).
Each detected pattern receives a quality score from four dimensions:
— 📐 Fibonacci precision (45 pts) : how close BC/AB is to the nearest standard Fibonacci level (0.382, 0.500, 0.618, 0.786, 0.886, 1.000, 1.272, 1.618). Exact Fib ratio = full points. 0.05 away = partial. 0.18+ away = zero. This is the most heavily weighted factor because Fibonacci alignment is the core of harmonic pattern validity.
— ⏱️ Time symmetry (25 pts) : the ratio of estimated CD bars to AB bars. Perfect symmetry (CD bars = AB bars) = 25 points. Asymmetric patterns (one leg much longer) score lower.
— ⚖️ Price symmetry (20 pts) : BC retracement depth relative to 0.618 — deeper retests (closer to 0.618) score higher. Very shallow pullbacks (e.g., 0.236) receive fewer points.
— 📏 Leg maturity (10 pts) : AB leg length in bars — patterns with 8+ bars get full points, 5+ get 7, 3+ get 3. Single-bar spikes score zero.
Patterns below the Min Pattern Score threshold (default 40) are not displayed.
4️⃣ Fibonacci extension levels projected from C.
Four AB extension levels are drawn from point C in the direction of the pattern:
— 0.786 × |AB| — shallow completion
— 1.000 × |AB| — classic equal-leg ABCD
— 1.272 × |AB| — extended completion
— 1.618 × |AB| — maximum extension
The 1.0 level is drawn thicker (2px, less transparency) as it represents the ideal equal-leg completion. Each level includes a price label. Additionally, the measured BC/AB retracement ratio is displayed at the midpoint of the BC leg for reference.
5️⃣ Fibonacci retracement levels within C→D (partial TP targets).
For active patterns, three retracement levels are drawn between C and the projected D:
— 0.382 of CD range — first partial profit target
— 0.500 of CD range — mid-target
— 0.618 of CD range — aggressive partial take
These provide natural exit levels before the full D-point is reached — useful for scaling out of positions progressively.
6️⃣ Target Zone + Stop Zone with geometric sizing.
On each pattern:
— TARGET ZONE : a band around the projected D-point, sized at 10% of the CD range. For bullish patterns: the zone sits just below D. For bearish: just above D. This is where the pattern completion trade expects to reach profit.
— STOP ZONE : a band around point C, also sized at 10% of CD range. For bullish patterns: below C. For bearish: above C. If price returns past C, the pattern structure is broken.
Both zones extend rightward until price touches the target zone (tracked by touch bar), or the pattern resolves (TP/SL hit). Zones use distinct colors: green for target, red for stop.
7️⃣ TP/SL outcome tracking with separate bull/bear statistics.
Each active pattern monitors:
— TP hit : price reaches the projected D-point (high ≥ D for bull, low ≤ D for bear)
— SL hit : price returns past C against the pattern direction (low ≤ C for bull, high ≥ C for bear)
— Simultaneous TP+SL on the same bar → resolved as loss (conservative)
On TP hit: R:R is calculated as |entry to TP| / |entry to SL| and accumulated. The dashboard shows separate bull and bear win rates with average R:R on wins.
8️⃣ Active-only display mode.
When "Show Active Only" is enabled (default), completed patterns (TP or SL already hit) are hidden — only the current live pattern remains on the chart. When disabled, up to maxPatterns historical patterns are shown for context. This prevents chart clutter while maintaining full statistical tracking.
9️⃣ One-active-pattern constraint.
The indicator only allows one active pattern at a time. When an active pattern exists (status = 0), no new patterns are detected. This prevents overlapping projections and conflicting zones. A new pattern can only be detected after the current one resolves (TP or SL).
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — ZigZag: Directional pivot detection with alternation enforcement. Higher highs update existing swing (no duplicate). Lower lows same. Pivots stored in parallel arrays.
Step 2 — Pattern extraction: On each new confirmed pivot: extract A (3rd-to-last), B (2nd-to-last), C (latest). Compute AB length, BC length, BC/AB ratio.
Step 3 — Validation: BC/AB within Fibonacci range? AB ≥ ATR? AB ≥ 3 bars? No active pattern already?
Step 4 — Scoring: 4 factors: Fibonacci precision (45), time symmetry (25), price symmetry (20), leg maturity (10). Score ≥ minScore → pattern accepted.
Step 5 — Projection: D = C + direction × |AB| × avgCdAbRatio. Bars capped at maxBarsProjection.
Step 6 — Drawing: On barstate.islast: delete-and-redraw all visible patterns. AB and BC legs as solid lines. CD projection as dotted. A/B/C/D labels. Score label. Target/Stop zones as boxes. Fib extension and retracement levels as dashed lines with price labels.
Step 7 — Evaluation: Each bar: check all active patterns for TP/SL hits. Update status, accumulate win/loss stats, record R:R.
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator — ABCD patterns appear automatically as colored leg lines with A/B/C/D labels
2. Yellow dotted line from C = projected path to D
3. Green "TARGET ZONE" box = where price should reach (take profit)
4. Red "STOP ZONE" box = where the pattern is invalidated (stop loss)
5. Blue dashed lines = Fibonacci extension levels (0.786, 1.0, 1.272, 1.618)
6. Blue dotted lines = partial TP targets (0.382, 0.5, 0.618 of CD)
7. "Long"/"Short" label = confirmed entry signal
👁️ Reading the chart:
— 🟢 Green legs + labels = bullish ABCD (D above C, expecting up-move)
— 🔴 Red legs + labels = bearish ABCD (D below C, expecting down-move)
— 🟡 Dotted projection line = expected path C → D
— 🟢 "TARGET ZONE" box = profit target area around projected D
— 🔴 "STOP ZONE" box = invalidation area around C
— 🔵 Dashed lines = Fib extension levels from C (0.786/1.0/1.272/1.618 of AB)
— 🔵 Dotted lines = CD retracement levels (partial TPs: 0.382/0.5/0.618)
— Score label (e.g., "72%") = pattern quality
📊 Dashboard fields:
— Patterns: active / total count
— Last Signal: direction + status (Active/TP ✓/SL ✗) + score
— Bull W/L: wins/losses and win rate for bullish patterns
— Bear W/L: wins/losses and win rate for bearish patterns
— Avg R:R: average reward-to-risk on winning bull/bear trades
— ATR: current value for reference
— Timeframe, version
🔧 Tuning guide:
— Too many patterns: increase ZigZag Length (12–21), increase Min Score (60+), enable ATR filter
— Too few patterns: decrease ZigZag Length (5–8), decrease Min Score (30), widen BC/AB ratio range
— Patterns too small: increase ATR filter or ZigZag Length
— Want only perfect geometry: narrow BC/AB to 0.500–0.786, set CD/AB to 0.9–1.1, Min Score 70+
— Extended patterns: set Max CD/AB to 1.618 or higher
⚙️ KEY SETTINGS REFERENCE
⚙️ Main:
— ZigZag Length (default 8): pivot detection lookback
— Pivot Sources : configurable high/low sources
📐 Pattern:
— Min/Max BC/AB Ratio (default 0.382/0.886): Fibonacci retracement range
— Min/Max CD/AB Ratio (default 0.786/1.618): extension range for D projection
— Min Pattern Score (default 40): quality threshold
— ATR Filter (default On): minimum swing size
— Max Patterns (default 3): display limit
— Active Only (default On): hide completed patterns
🎨 Visual:
— Buy/Sell signals, D projection, Fib levels, TP/SL zones, A/B/C/D labels, score (all toggleable)
— Auto / Dark / Light theme
🔧 Advanced:
— Max Bars for D Projection (default 200): limits distant projections
🔔 Alerts
— 🟢 LONG ABCD / 🔴 SHORT ABCD — entry, TP, SL, score, pattern type
All support plain text and JSON webhook format. Bar-close confirmed.
⚠️ IMPORTANT NOTES
— 🚫 No repainting. All signals require barstate.isconfirmed and newPivot (confirmed ZigZag pivot). Patterns are detected after the pivot bar closes. Drawings are rendered on barstate.islast using delete-and-redraw — previous bar's pattern state is final.
— 📐 The ZigZag enforces strict alternation : high → low → high → low. If price makes a higher high during an existing up-swing, the previous high is updated in place — no duplicate pivots are created. This is essential for correct A/B/C/D extraction.
— ⚖️ Only one active pattern is allowed at a time. New patterns are blocked until the current one resolves (TP or SL). This prevents conflicting signals and overlapping zones.
— 📊 The quality score is heavily weighted toward Fibonacci precision (45 out of 100 points). A pattern with BC/AB exactly at 0.618 scores much higher than one at 0.450. This reflects the harmonic principle that Fibonacci alignment is the primary measure of pattern validity.
— 🔒 Simultaneous TP+SL on the same bar is resolved as a loss (conservative) . This prevents ambiguous outcomes from inflating win rates.
— 📏 The D-point projection uses the average of the min/max CD/AB ratio range — not the exact 1.0 (equal legs). With default settings (0.786–1.618), the projected D is at 1.202× AB from C — between classic and extended. Adjust the CD/AB range to target specific completion types.
— 🛠️ This is a harmonic pattern detection and projection tool , not an automated trading bot. It identifies ABCD geometry, projects D-point targets, and provides structured trade zones — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Penunjuk

ABCD Harmonic Pattern Strategy (Bull + Bear) This script is a strategy implementation of the classic ABCD Harmonic Pattern, designed for market structure analysis, backtesting, and educational research.
The ABCD pattern is one of the foundational harmonic price patterns in technical analysis. Its Fibonacci ratio relationships were formalized and standardized within harmonic trading theory by Scott M. Carney, whose work helped define modern harmonic pattern rules.
This strategy is conceptually inspired by educational ABCD pattern logic shared by the TradingView author theEccentricTrader.
The code, structure, execution logic, filters, and risk management have been independently developed, reconstructed, and extended into a complete TradingView strategy.
What this strategy does
Detects bullish and bearish ABCD harmonic patterns based on price structure and Fibonacci ratios.
Reconstructs ABCD market structure logic for both directions instead of using a simple visual inversion.
Draws the ABCD legs, structure labels (A, B, C, D), and projection levels directly on the chart.
Generates long and short trade entries using confirmed ABCD structures.
Includes optional confluence filters, such as:
Higher-timeframe EMA trend filter
RSI strength filter
ATR volatility filter
Volume confirmation
Candle body confirmation
Minimum bounce distance from point D
Provides built-in risk management, including:
Configurable Stop Loss
Configurable Take Profit
Optional trailing stop
Designed for backtesting, parameter optimization, and analytical research.
Why this strategy is different
This script is not a simple indicator conversion nor a basic bullish/bearish mirror.
The ABCD pattern logic has been recreated at the structural level to better reflect how bullish and bearish market formations behave in real price action.
Key differences
Reconstructed bullish and bearish structures
Bullish and bearish ABCD patterns are independently defined using market structure logic, not just inverted visually.
Each direction has its own pivot relationships and validation rules to produce a more faithful representation of the ABCD pattern.
Structure-aware pattern validation
Pattern confirmation is based on price swings, structure continuity, and Fibonacci alignment, helping reduce distorted or forced patterns.
Strategy-based execution
Unlike indicator-only ABCD tools that only visualize patterns, this script uses strategy.entry and strategy.exit, enabling full backtesting and performance analysis.
Confluence-driven entries
Trade entries can require multiple confirmation layers beyond the pattern itself, helping reduce low-quality signals and overtrading.
Integrated risk management
Stop Loss, Take Profit, and optional trailing logic are applied consistently for both long and short positions.
Non-repainting design
Pattern detection and entries rely on confirmed bars (barstate.isconfirmed) and higher-timeframe data with lookahead_off, ensuring signals do not repaint historically.
Improved and controlled visualization
Pattern drawings, projections, and entry markers are managed with strict object limits to comply with TradingView performance and publishing requirements.
How to use
Add the strategy to a chart and select a symbol and timeframe.
Enable or disable filters under “Entry Filters (Confluence)”.
Configure Stop Loss, Take Profit, and trailing behavior under “TP/SL”.
Use pattern drawings and entry markers as visual and analytical confirmation, not as standalone trade signals.
Important notes
This script is provided for educational and research purposes only.
It does not provide financial or investment advice.
No profitability or performance is implied or guaranteed.
Past performance does not indicate future results.
Always test across multiple markets and timeframes and apply proper risk management.
Credits
ABCD Harmonic Pattern: Harmonic trading principles as formalized by Scott M. Carney.
Conceptual inspiration: Educational ABCD pattern logic shared by @theEccentricTrader on TradingView.
Pattern reconstruction, strategy logic, and risk management: Independent development. Strategi

Harmonic Patterns (Experimental) [Kodexius]Harmonic Patterns (Experimental) is a multi pattern harmonic geometry scanner that automatically detects, validates, and draws classic harmonic structures directly on your chart. The script continuously builds a pivot map (swing highs and swing lows), then evaluates the most recent pivot sequence against a library of harmonic ratio templates such as Gartley, Bat, Deep Bat, Butterfly, Crab, Deep Crab, Cypher, Shark, Alt Shark, 5-0, AB=CD, and 3 Drives.
Unlike simple “pattern exists / pattern doesn’t exist” indicators, this version scores candidates by accuracy . Each pattern includes “ideal” ratio targets, and the script computes a total error score by measuring how far the observed ratios deviate from the ideal. When multiple patterns could match the same pivot structure, the script selects the best match (lowest total error) and displays that one. This reduces clutter and makes the output more practical in real market conditions where many ratio ranges overlap.
The end result is a clean, information rich visualization of harmonic opportunities that is:
-Pivot based and swing aware
-Ratio validated with configurable tolerance
-Direction filtered (bullish, bearish, or both)
-Ranked by accuracy to prefer higher quality matches
Note: This is an experimental pattern engine intended for research, confluence and chart study. Harmonic patterns are probabilistic and can fail often. Always combine with your own risk management and confirmation tools.
🔹 Features
🔸Pivot Detection
The script uses pivot functions to detect structural turning points:
-Pivot Left Bars controls how many bars must exist on the left of the pivot
-Pivot Right Bars controls confirmation delay on the right (smaller value reacts faster)
Additionally, a Min Swing Distance (%) filter can ignore tiny swings to reduce noise. Pivots are stored separately for highs and lows and capped by Max Pivots to Store to keep the script efficient.
🔸Pattern Library (XABCD and Beyond)
Supported structures include:
-Gartley, Bat, Deep Bat, Butterfly, Crab, Deep Crab
-Cypher (uses XC extension and CD retracement logic)
-Shark and Alt Shark (0-X-A-B-C mapping)
-5-0 (AB and BC extensions with CD retracement)
-AB=CD (symmetry and proportionality checks)
-3 Drives (6 point structure, drive and retracement ratios)
Each pattern is defined by ratio ranges and also “ideal” ratio targets used for scoring.
🔸 Pattern Fibonacci Rules (Detailed Ratio Definitions)
This script validates each harmonic template by measuring a small set of Fibonacci relationships between the legs of the pattern. All measurements are computed using absolute price distance (so the ratios are direction independent), and then a directional sanity check ensures the geometry is positioned correctly for bullish or bearish cases.
How ratios are measured
Most patterns in this script use the standard X A B C D harmonic structure. Four ratios are evaluated:
1) XB retracement of XA
This measures how much price retraces from A back toward X when forming point B .
xbRatio = |B - A| / |A - X|
2) AC retracement of AB
This measures how much point C retraces the AB leg.
acRatio = |C - B| / |B - A|
3) BD extension of BC
This measures the “drive” from C into D relative to the BC leg.
bdRatio = |D - C| / |C - B|
4) XD retracement of XA
This is the most important “completion” ratio in many patterns. It measures where D lands relative to the original XA swing.
xdRatio = |D - A| / |A - X|
Important: the script applies a user defined Fibonacci Tolerance to each accepted range, meaning the pattern can still pass even if ratios are slightly off from the textbook values.
🔸 XABCD Pattern Ratio Templates
Below are the exact ratio rules used by the templates in this script.
Gartley
-XB must be ~0.618 of XA
-AC must be between 0.382 and 0.886 of AB
-BD must be between 1.272 and 1.618 extension of BC
-XD must be ~0.786 of XA
In practice, Gartley is a “non extension” structure, meaning D usually remains inside the X boundary .
Bat
-XB between 0.382 and 0.50 of XA
-AC between 0.382 and 0.886 of AB
-BD between 1.618 and 2.618 of BC
-XD ~0.886 of XA
Bat patterns typically complete deeper than Gartley and often create a sharper reaction at D.
Deep Bat
-XB ~0.886 of XA
-AC between 0.382 and 0.886 of AB
-BD between 1.618 and 2.618 of BC
-XD ~0.886 of XA
Deep Bat uses the same completion zone as Bat, but requires a much deeper B point.
Butterfly
-XB ~0.786 of XA
-AC between 0.382 and 0.886 of AB
-BD between 1.618 and 2.618 of BC
-XD between 1.272 and 1.618 of XA
Butterfly is an extension pattern . That means D is expected to break beyond X (in the completion direction).
Crab
-XB between 0.382 and 0.618 of XA
-AC between 0.382 and 0.886 of AB
-BD between 2.24 and 3.618 of BC
-XD ~1.618 of XA
Crab is also an extension pattern . It often produces a very deep D completion and a strong reaction zone.
Deep Crab
-XB ~0.886 of XA
-AC between 0.382 and 0.886 of AB
-BD between 2.0 and 3.618 of BC
-XD ~1.618 of XA
Deep Crab combines a deep B point with a strong XA extension completion.
🔸 Cypher Fibonacci Rules (XC Based)
Cypher is not validated with the same four ratios as XABCD patterns. Instead it uses an XC based completion model:
1) B as a retracement of XA
xb = |B - A| / |A - X| // AB/XA
Must be between 0.382 and 0.618 .
2) C as an extension from X relative to XA
xc = |C - X| / |A - X| // XC/XA
Must be between 1.272 and 1.414 .
3) D as a retracement of XC
xd = |D - C| / |C - X| // CD/XC
Must be ~ 0.786 .
This makes Cypher structurally different: the “completion” is defined as a retracement of the entire XC leg, not XA.
🔸 Shark and Alt Shark Fibonacci Rules (0-X-A-B-C Mapping)
Shark patterns are commonly defined as 0 X A B C . In this script the pivots are mapped like this:
0 = pX, X = pA, A = pB, B = pC, C = pD
So the final pivot (stored as pD) is labeled as C on the chart.
Three ratios are validated:
1) AB relative to XA
ab_xa = |B - A| / |A - X|
Must be between 1.13 and 1.618 .
2) BC relative to AB
bc_ab = |C - B| / |B - A|
Must be between 1.618 and 2.24 .
3) OC relative to OX
oc_ox = |C - 0| / |X - 0|
For Shark it must be between 0.886 and 1.13 .
For Alt Shark it must be between 1.13 and 1.618 (a deeper / more extended completion).
🔸 5-0 Fibonacci Rules
5-0 is validated as a sequence of extensions and then a fixed retracement:
1) AB extension of XA
ab_xa = |B - A| / |A - X|
Must be between 1.13 and 1.618 .
2) BC extension of AB
bc_ab = |C - B| / |B - A|
Must be between 1.618 and 2.24 .
3) CD retracement of BC
cd_bc = |D - C| / |C - B|
Must be approximately 0.50 .
Note that for 5-0 the script does not rely on an XA completion ratio like 0.786 or 1.618. The defining completion is the 0.5 retracement of BC.
🔸 AB=CD Fibonacci Rules
AB=CD is a symmetry pattern and is treated differently from the harmonic templates:
1) AB and CD length symmetry
The script checks if CD is approximately equal to AB within tolerance.
2) BC proportion
BC/AB is expected to fall in a common Fibonacci retracement zone:
-approximately 0.618 to 0.786 (with a looser tolerance in code)
3) CD/BC expansion
CD/BC is expected to be an expansion ratio:
-approximately 1.272 to 1.618 (also with a looser tolerance)
This allows the script to capture both classic equal leg AB=CD and common “expanded” variations.
🔸 3 Drives Fibonacci Rules (6 Point Structure)
3 Drives is a 6 point structure and is validated using retracement ratios and extension ratios:
Retracement rules
Retracement 1 must be between 0.618 and 0.786 of Drive 1
Retracement 2 must be between 0.618 and 0.786 of Drive 2
Extension rules
Drive 2 must be between 1.272 and 1.618 of Retracement 1
Drive 3 must be between 1.272 and 1.618 of Retracement 2
This pattern is meant to capture rhythm and proportional repetition rather than a single XA completion ratio.
🔸 Why the script can show “ratio labels” on legs
If you enable Show Fibonacci Values on Legs , the script prints the measured ratios near the midpoint of each leg (or diagonal, depending on pattern type). This makes it easy to visually confirm:
-Which ratios caused the pattern to pass
-How close the structure is to ideal harmonic values
-Why one template was preferred over another via the accuracy score
🔸 Fibonacci Tolerance Control
All ratio checks use a single tolerance input (percentage). This tolerance expands or contracts the acceptable ratio ranges, letting you decide whether you want:
-Tight, high precision matches (lower tolerance)
-Broader, more frequent matches (higher tolerance)
🔸 Direction Filter (Bullish Only / Bearish Only / Both)
You can restrict scanning to bullish patterns, bearish patterns, or allow both. This is useful if you are aligning with higher timeframe bias or only trading one side of the market.
🔸 Best Match Selection (Anti Clutter Logic)
When a new pivot confirms, the script evaluates all enabled patterns against the latest pivot sequence and keeps the one with the smallest total error score. This is especially helpful because many harmonic templates overlap in real time. Instead of drawing multiple conflicting labels, you get one “most accurate” candidate.
🔸 Clean Visual Rendering and Optional Details
The drawing system can display:
-Main structure lines (X-A-B-C-D or special mappings)
-Dashed diagonals for geometric context (XB, AC, BD, XD)
-Pattern fill to visually highlight the structure zone
-Point labels (X,A,B,C,D or 0..5 for 3 Drives, 0-X-A-B-C for Shark)
-Leg Fibonacci labels placed around midpoints for fast ratio reading
All colors (bullish and bearish line and fill) are configurable.
🔸 Pattern Spacing and Display Limits
To keep charts readable, the script includes:
-Max Patterns to Display to limit on-chart drawings
-Min Bars Between Patterns to avoid repeated signals too close together in the same direction
Older patterns are automatically deleted once the display limit is exceeded.
🔸 Alerts
When enabled, alerts trigger on new confirmed detections:
-Bullish Pattern Detected
-Bearish Pattern Detected
Alerts fire once per bar when a new pattern is confirmed by a fresh pivot.
🔹 Calculations
This section summarizes the core logic used under the hood.
1) Pivot Detection and Swing Filtering
The script confirms pivots using right side confirmation, then optionally filters them by minimum swing distance relative to the last opposite pivot.
// Pivot detection
float pHigh = ta.pivothigh(high, pivotLeftBars, pivotRightBars)
float pLow = ta.pivotlow(low, pivotLeftBars, pivotRightBars)
// Example swing distance filter (conceptual)
abs(newPivot - lastOppPivot) / lastOppPivot >= minSwingPercent
Pivots are stored in capped arrays (high pivots and low pivots), ensuring performance and stable memory usage.
2) Ratio Measurements (Retracement and Extension)
The engine measures harmonic ratios using two core helpers:
Retracement measures how much the third point retraces the previous leg.
Extension measures how much the next leg extends relative to the previous leg.
// Retracement: (p3 - p2) compared to (p2 - p1)
calcRetracement(p1, p2, p3) =>
float leg = math.abs(p2.price - p1.price)
float retr = math.abs(p3.price - p2.price)
leg != 0 ? retr / leg : na
// Extension: (p4 - p3) compared to (p3 - p2)
calcExtension(p2, p3, p4) =>
float leg = math.abs(p3.price - p2.price)
float ext = math.abs(p4.price - p3.price)
leg != 0 ? ext / leg : na
For a standard XABCD pattern the script evaluates:
-XB retracement of XA
-AC retracement of AB
-BD extension of BC
-XD retracement of XA
3) Tolerance Based Range Check
Ratio validation uses a flexible range check that expands min and max by the tolerance percent:
isInRange(value, minVal, maxVal, tolerance) =>
float tolMin = minVal * (1.0 - tolerance)
float tolMax = maxVal * (1.0 + tolerance)
value >= tolMin and value <= tolMax
This means even “fixed” ratios (like 0.786) still allow a user controlled deviation.
4) Positional Sanity Check for D (Beyond X or Not)
Some harmonic patterns require D to remain within X (non extension patterns), while others require D to break beyond X (extension patterns). The script enforces that using a boolean flag in each template.
Conceptually:
-If the pattern is an extension type, D should cross beyond X in the expected direction
-If the pattern is not extension type, D should stay on the correct side of X
This prevents visually incorrect “ratio matches” that violate the intended geometry.
5) Template Definitions (Ranges + Ideal Targets)
Every pattern includes ratio ranges plus ideal values. The ideal values are used only for scoring quality, not for pass/fail. Example concept:
-Ranges determine validity
-Ideal targets determine ranking
6) Accuracy Scoring (Total Error)
When a candidate passes all validity checks, the script computes an accuracy score by summing absolute deviations from ideal ratios:
calcError(value, ideal) =>
math.abs(value - ideal)
// Total error is the sum of the four leg errors (as available for the pattern)
totalError =
calcError(xbRatio, xbIdeal) +
calcError(acRatio, acIdeal) +
calcError(bdRatio, bdIdeal) +
calcError(xdRatio, xdIdeal)
Lower score means closer to the “textbook” harmonic proportions.
7) Best Match Resolution (Choosing One Winner)
When multiple enabled patterns match the same pivot structure, the script selects the one with the lowest totalError:
updateBest(currentBest, newCandidate) =>
result = currentBest
if not na(newCandidate)
if na(currentBest) or newCandidate.totalError < currentBest.totalError
result := newCandidate
result
This is a major practical feature because it reduces clutter and highlights the highest quality interpretation.
8) Bullish and Bearish Scanning Logic
The scanner runs when pivots confirm:
-Bullish patterns are evaluated on a newly confirmed pivot low (potential D)
-Bearish patterns are evaluated on a newly confirmed pivot high (potential D)
From that D pivot, the script searches backward through stored pivots to build a valid pivot sequence (X,A,B,C,D). If 3 Drives is enabled, it also attempts to find the extra preceding point needed for the 6 point structure.
9) Rendering: Lines, Fill, Labels, and Leg Fib Text
After detection the script draws:
-Primary legs with thicker lines
-Geometric diagonals with dashed lines (for XABCD types)
-Optional fill between selected legs to emphasize the structure area
-A summary label showing direction, pattern name, and ratios
-Optional point labels and leg ratio labels placed near midpoints
To avoid overlapping with candles, the script offsets labels using ATR:
float yOff = math.max(ta.atr(14) * 0.15, syminfo.mintick * 10)
10) Pattern Lifecycle and Cleanup
To respect chart limits and keep visuals clean, the script deletes old drawings once the maximum visible patterns threshold is exceeded. This includes lines, fills, and labels. Penunjuk

N-Pattern Detector (Advanced Logic)Introduction
The N-Pattern Detector (Advanced Logic) is a powerful Pine Script-based tool designed to identify a specific price structure known as the "N-pattern", which often indicates trend continuation or potential breakout points in the market. This pattern combines zigzag pivot logic, retracement filters, volume confirmation, and trend alignment, offering high-probability trading signals.
It is ideal for traders who want to automate pattern detection while applying smart filters to reduce false signals in various markets — including stocks, forex, crypto, and indices.
What is the N-Pattern?
The N-pattern is a 3-leg price formation consisting of points A-B-C-D. It typically follows this structure:
Bullish N-Pattern:
A → Low Pivot
B → Higher High (Impulse)
C → Higher Low (Retracement)
D → Breakout above B (Confirmation)
Bearish N-Pattern:
A → High Pivot
B → Lower Low (Impulse)
C → Lower High (Retracement)
D → Breakdown below B (Confirmation)
The pattern essentially reflects a trend–pullback–breakout structure, making it suitable for continuation trades.
Key Features
1. Intelligent ZigZag Pivot Detection
Uses pivot highs/lows to define key swing points (A, B, C).
Adjustable ZigZag depth to control pattern sensitivity.
Filters noise and avoids false signals in volatile markets.
2. Retracement Validation
Validates the B→C leg as a proper pullback using Fibonacci-based thresholds.
User-defined min and max retracement settings (e.g., 38.2% to 78.6% of A→B leg).
3. Trend Filter via EMA
Filters patterns based on trend direction using a customizable EMA (e.g., 200 EMA).
Only detects bullish patterns above EMA and bearish patterns below EMA (optional).
4. Volume Confirmation
Ensures that impulse legs (A→B, C→D) are supported by stronger volume than the correction leg (B→C).
Adds another layer of confirmation and reliability to detected patterns.
5. Target Projections
Automatically draws 100% A→B projected target from point C.
Optional Fibonacci extensions at 1.272 and 1.618 levels for take-profit planning.
Visually plotted on the chart with colored dashed/dotted lines.
6. Clear Visuals & Labels
Connects all pattern points with colored lines.
Clearly labels points A, B, C, D on the chart.
Uses customizable colors for bullish and bearish patterns.
Includes real-time alerts when a valid pattern is detected.
How to Use It
Add to Chart
Apply the indicator to any chart and time frame. It works across all asset classes.
Adjust Inputs (Optional)
Set ZigZag Depth to control pivot detection sensitivity.
Define Min/Max Retracement levels to match your trading style.
Enable or disable Trend and Volume filters for cleaner signals.
Customize EMA length (default: 200) for trend validation.
Wait for Pattern Confirmation
The indicator constantly scans for valid N-patterns.
A pattern is confirmed only after point D forms (breakout or breakdown).
You’ll see the full pattern drawn with target levels.
Set Alerts
Alerts trigger automatically on confirmation of a bullish or bearish pattern.
You can customize these in TradingView’s alerts panel. Penunjuk

ABCD Projection [Trendoscope®]Over the years, we have extensively explored and published numerous scripts centered around various chart patterns, including Harmonic Patterns, Reversal Patterns, Elliott Waves, and more. Our expertise in these areas has led to frequent requests for an indicator based on the ABCD pattern. Although we didn't include it as part of our Harmonic Patterns collection, the development of a dedicated ABCD Projection Indicator has always been a priority for us.
🎲 Overview of the ABCD Projection Indicator
The ABCD Projection Indicator is designed to identify and project ABCD patterns using a Zigzag-based approach. This pattern, characterized by alternating pivot highs and lows labeled as A, B, C, and D, is particularly significant in trending markets where it signifies trend continuation following deep pullbacks.
The indicator works by confirming the ABC pivots and projecting the D pivot based on the established price swings. Since ABCD patterns are most effective in trending environments, the indicator focuses on filtering patterns where the retracement from the C pivot has not compromised the trade's potential. Specifically, it ensures that the starting point (S)—where the pattern is detected—has not retraced beyond a defined threshold, preserving the opportunity to execute a trade with the goal of reaching the projected D pivot.
Additionally, the ABCD Projection Indicator considers the retracement ratio from the C pivot, which plays a crucial role in risk management. A higher retracement ratio reduces the stop distance (from pivot A to the entry point S) while increasing the distance to the target (pivot D), thereby enhancing the reward/risk ratio for trades.
🎲 Components of the ABCD Projection Indicator
The ABCD Projection Indicator comprises several key components:
A, B, C Pivots and Zigzag Wave : These elements form the foundational structure of the ABCD pattern.
S Point : This is the location where the pattern is identified, positioned a few bars away from the confirmed C pivot.
Estimated D Pivot : The D pivot is projected based on the A, B, and C price levels. The time or distance to the D pivot is influenced by the starting point S.
Mini Stats Table : Located in the top right corner, this table displays win/loss ratios and risk/reward data for both bullish and bearish scenarios.
Fibonacci Levels : Calculated from the C to D pivots, these levels are provided as a reference for additional analysis.
🎲 Indicator Settings
The settings for the ABCD Projection Indicator are minimal and intuitive, with tooltips provided to guide users through the configuration process.
Penunjuk
