Wave Structure PRO v2 [Viprasol]Wave Structure PRO v2 is an automated Elliott Wave structure engine. It builds a ZigZag from confirmed pivots, searches for a valid 1-2-3-4-5 impulse and the following A-B-C correction, validates every candidate against Elliott's three hard rules, and scores how closely each wave matches its ideal Fibonacci proportion. On top of the count it draws the Elliott base channel, Wave 3 / Wave 5 Fibonacci targets, the next-wave retrace zone, and the exact price level where the count becomes invalid.
This is a structure assistant, not a prediction oracle. Elliott counting is inherently ambiguous, and this engine recounts as new pivots confirm. Everything it shows is derived from confirmed swing points, and it tells you honestly when no valid count exists.
HOW IT WORKS
ZigZag Pivot Engine:
Swing highs and lows are detected with a symmetric pivot window (default 8 bars left and right). A pivot only enters the structure after it is confirmed, and consecutive same-direction extremes are merged so the ZigZag always alternates high-low-high-low. The engine keeps the most recent 32 pivots as its working structure.
Sliding-Window Count Search:
The engine scans across the entire pivot structure for the most recent valid count — it does not require the pattern to end exactly at the newest pivot. A completed impulse whose correction is still developing stays on the chart and is marked "prior" in the panel, so a single awkward swing at the right edge does not wipe the analysis. At each candidate position a full 9-pivot impulse + A-B-C structure is preferred over a 6-pivot impulse alone.
Hard-Rule Validation:
Every candidate impulse must pass Elliott's three non-negotiable rules before it is accepted:
1. Wave 2 never retraces more than 100% of Wave 1
2. Wave 3 is never the shortest among Waves 1, 3, and 5
3. Wave 4 never enters the price territory of Wave 1
The A-B-C correction is additionally validated for direction and structure (B stays below the impulse extreme, C extends beyond A).
Fibonacci Quality Score:
Each wave is measured against its textbook ideal — Wave 2 near 0.5-0.618 of Wave 1, Wave 3 extending 1.618+ of Wave 1, Wave 4 near 0.382 of Wave 3, Wave 5 near equality with Wave 1. The four fits combine into a 0-100 "textbook fit" score. Extended fifth waves are scored against the alternative ideal of 0.618 x (Wave 1 + Wave 3), so a legitimately extended fifth is recognized instead of being punished, and the panel flags it as "extended 5th".
Invalidation Level:
For every accepted count the engine draws the price at which the structure stops being valid — a correction that retraces 100% of the impulse start invalidates the count. The exact level is shown on the chart, in the panel, and in the data window, giving you an objective line in the sand instead of a subjective opinion.
Alternation Check:
Waves 2 and 4 are compared as retracements of Wave 1 — when their depths differ meaningfully the panel confirms the alternation guideline is present, and shows an explicit "absent" flag when it is not.
KEY FEATURES
- Automatic 1-5 impulse and A-B-C correction detection with wave labels on the chart
- Sliding-window search — finds the most recent valid count anywhere in the structure, marked "prior" when its final pivot is not the newest swing
- Elliott's 3 hard rules enforced on every count — invalid structures are never labeled
- 0-100 Fibonacci quality score with per-wave ratio annotations at each pivot
- Extended fifth wave recognition with alternative 0.618 x (W1+W3) scoring path
- On-chart invalidation level with price label
- Elliott base channel (2-4 trendline with parallel through Wave 3)
- Wave 3 and Wave 5 Fibonacci extension targets with configurable multiples
- Next-wave retrace target zone (0.382-0.618 of the full impulse)
- Analysis panel: count state, quality, all four wave ratios, alternation, rule status, invalidation price
- Data-window outputs (quality, direction, stage, invalidation) usable by strategies and screeners via input.source
- Transition-based alerts that fire on state changes, not on every pivot refresh
HOW TO USE
Setup:
1. Add to any chart — works on all markets and timeframes
2. Use a standard candlestick chart (not Heikin Ashi)
3. Tune "Swing Sensitivity" to the wave degree you trade: higher values = larger-degree waves, lower values = smaller subdivisions
4. Defaults (sensitivity 8) suit 1H-4H charts on liquid instruments
Reading the Chart:
- Numbered labels 1-5 mark the impulse pivots; A-B-C labels mark the correction (orange)
- Small ratio numbers at pivots 2, 3, 4, 5 show each wave's Fibonacci proportion
- Dotted / dashed blue lines = Wave 3 and Wave 5 extension targets
- Cyan channel = Elliott base channel projected forward
- Purple box = expected retrace zone for the next corrective wave
- Red line = invalidation level; if price crosses it, the count is wrong
- Panel header: up/down arrow shows count direction; "prior" means the count completed before the newest swing
Reading the Panel:
- Quality 70+ = clean textbook structure; below 50 = forced fit, treat with caution
- "NO COUNT" genuinely means no valid structure exists right now — the engine never shows leftover metrics from a dead count
- The Invalidation row gives the exact price that voids the current count
SETTINGS
ZigZag: Swing sensitivity (pivot bars left/right), ZigZag visibility and color.
Waves: Wave label toggles for 1-5 and A-B-C, bullish/bearish/corrective colors, label size.
Fibonacci & Quality: Ratio annotations toggle, target visibility, Wave 3 and Wave 5 extension multiples, target color.
Channel & Target Zone: Base channel toggle and color, retrace zone toggle and color.
Invalidation: Level visibility and color.
Analysis Panel: Show/hide, position.
Alerts: Quality threshold for the high-quality alert, dynamic alert() messages toggle.
ALERTS
1. Count found — a new valid wave count appeared (fires once per count, not on every pivot extension)
2. Count invalidated — the active count stopped being valid
3. 1-5 + A-B-C complete — the correction finished, full cycle in place
4. High-quality count — a new count scored above your quality threshold
With "Dynamic alert() Messages" enabled, alert() notifications include the symbol, timeframe, direction, quality score, and invalidation price. Create the alert with condition "Any alert() function call".
LIMITATIONS & DISCLAIMER
- Elliott Wave counting is subjective by nature; this engine applies one rigorous, rule-based interpretation and recounts as new pivots confirm
- Pivots confirm with a delay equal to the swing sensitivity — labels appear after the swing completes, never in real time at the extreme
- The count can change when a developing swing extends; the transition alerts are designed around this, firing on genuine state changes only
- Wave degree is determined by your sensitivity setting; the engine does not track multiple degrees simultaneously
- Quality scoring measures Fibonacci proportion fit, not probability of continuation
- This indicator is for educational and analytical purposes only — it is not financial advice. Always use proper risk management.
ORIGINALITY
All code is original Viprasol work. Elliott Wave theory itself is public knowledge (R.N. Elliott); no third-party script was reused. v2 supersedes Wave Structure PRO with a stale-state fix, sliding-window count search, invalidation levels, extended-fifth scoring, data-window outputs, and transition-based alerts. Индикатор

Wave Sniper# Wave Sniper — Elliott Wave Flat & Confluence Detector
**by SRUS**
Wave Sniper is an advanced Elliott Wave overlay that automatically detects **flat corrections**, **3-wave pullbacks**, and **multi-timeframe wave structure** — then scores each setup for quality and confluence before marking it on your chart.
Built for traders who want clean wave-based entries without manually counting every pivot across timeframes.
---
## What It Detects
### Flat Corrections (A–B–C)
- **Regular Flat** — B retraces ~90–100% of A, C completes near A
- **Expanded Flat** — B exceeds A (up to 138.2%), C extends 123.6–161.8% of A
- **Running Flat** — B exceeds A, C fails to reach A (truncated C)
Each flat is validated with Fibonacci ratios, optional B-wave close validation, RSI momentum divergence, and volume confirmation at the C pivot.
### 3-Wave Pullbacks
- **Continuation** — three-wave pullback in the direction of the prevailing trend
- **Reversal** — three-wave structure signaling a potential turn
### 5-Wave Retest
After a flat completes, Wave Sniper tracks whether price forms a valid 5-wave extension and flags **retest opportunities** at the prior correction zone.
### Multi-Timeframe Wave Engine (15m · 1H · 4H · Daily)
Independent pivot engines run on four higher timeframes, each maintaining its own wave count state:
`WAVE_1` through `WAVE_5`, `WAVE_A/B/C`, impulse complete, correction complete.
---
## Signal System
### Triangle Markers
Confirmed setups print a **small triangle** at the C pivot:
- ▲ Green/Purple = Long bias
- ▼ Red = Short bias
Triangle color and line weight reflect the **confluence tier** — not just pattern type.
### Confluence Tiers (HTF Bonus)
| Tier | HTF Bonus | Visual |
|------|-----------|--------|
| CASCADE | 100+ | Boldest lines + chart flash |
| TRIPLE | 70–99 | Strong color, width 3 |
| WAVE | 40–69 | Medium color, width 2 |
| Single | Below 40 | Gray tint, width 1 |
**Base pattern score (0–100)** rates Fib accuracy, momentum, volume, and B-wave validation.
**HTF bonus (0–130)** adds points when chart and higher timeframes align on wave direction, impulse structure, RSI divergence, and volume behavior.
Full scoring breakdown is shown in the **info panel** (top right).
---
## Key Features
**Wave 4 Watch System**
- Detects when price enters the 23.6–38.2% Fib retrace zone of HTF Wave 3
- Confirms with RSI behavior, volume contraction, and a completing 3-wave structure
- Draws W4 MIN / W4 MAX levels and `W4 WATCH` / `W4 ✅ LOAD W5` labels
**HTF Fib Zones**
- Auto-draws Wave 4 expected retrace boxes per active timeframe
- Projects W5 targets: MIN, STANDARD, 161.8%, 261.8%
**⚡ Prime Zone**
When an HTF Wave 4 Fib zone overlaps a confirmed flat correction zone on your chart timeframe, a bright **PRIME ZONE** box highlights the overlap — highest-probability confluence area.
**Auto-Invalidation**
Patterns that break structure fade to gray and are removed from active tracking.
**Adaptive Pivots**
Pivot strength auto-adjusts to ATR and timeframe so detection stays consistent across instruments and chart periods.
**Focus Mode**
Toggle to show flats only and reduce chart clutter.
**Lookback Filter**
Auto / 1 Day / 1 Week / 1 Month / All — control how far back patterns are drawn.
---
## Info Panel
Live readout includes:
- Daily · 4H · 1H · 15m wave states
- HTF Bias (Long/Short)
- Prime Zone status
- Current chart wave state
---
## Alerts
Built-in alert conditions:
- ⚡ Wave 4 Approaching
- ✅ Wave 4 Confirmed — W5 Loading
- 🔥 Cascade Signal — All TFs Aligned
- ⚡ Prime Zone Active
- 🔁 Wave Count Invalidated (per TF)
- 🎯 Wave 5 Target Hit (MIN / 161.8%)
- Flat detected (Regular / Expanded / Running)
- 3-Wave Continuation / Reversal
- 5-Wave retest confirmed
- B-wave confirmed — watching for C
---
## Recommended Settings
| Use Case | Suggestion |
|----------|------------|
| Scalping (1m–5m) | Enable 15m + 1H layers, Min Score 65, Min HTF Bonus 40 |
| Swing (15m–1H) | All HTF layers on, Min Score 60, Min HTF Bonus 30 |
| Position (4H–D) | Daily + 4H layers, Wave Degree = Intermediate |
| Clean chart | Focus Mode ON, Max Visible = 3 |
---
## How to Read a Setup
1. **Triangle appears** at C pivot → flat or pullback confirmed
2. Check **info panel** for HTF alignment and tier
3. Watch for **W4 zone** or **Prime Zone** for entry refinement
4. Use **W5 projection lines** for targets
5. Set alerts for CASCADE or Prime Zone for hands-free monitoring
---
## Disclaimer
Wave Sniper is a **technical analysis tool**, not financial advice. Elliott Wave counting is interpretive — always confirm with your own analysis, risk management, and market context. Past pattern performance does not guarantee Индикатор

Campaign Map - Contreras Law Version en espanol mas abajo. · English version first, Spanish below.
─────────────────────────────────
CAMPAIGN MAP — CONTRERAS' LAW
WHAT IT MEASURES
This indicator builds the historical distribution of a symbol's
campaign corrections (peak→trough declines confirmed by reversal) and
places the CURRENT correction inside that map: is it normal breathing,
a deep pullback, or statistically unusual territory?
THE OBSERVATION BEHIND IT
Contreras' Law (Jacinto Contreras, June 2026): in US large-cap
technology stocks, the typical depth of campaign corrections converges
to a structural constant (~14-15% median at campaign scale),
regardless of the symbol. What differentiates each stock is not its
median but its historical maximum tail (observed: from ~25% to ~53%
depending on the symbol, across ~11 years of hourly data on 9 names).
Operational takeaway: MONITOR WITH THE MEDIAN, SIZE WITH THE TAIL.
HOW IT WORKS
· A reversal-threshold zigzag detects campaign peaks and troughs.
· Only COMPLETED corrections (confirmed by reversal) enter the
statistics: median, 75th percentile, and historical maximum.
· The main line plots the depth of the ongoing correction, colored by
zone: normal (teal), deep (orange), unusual (red).
· Summary table with the symbol's map and current status.
· Two alerts: median cross and P75 cross.
HOW TO USE IT
· Below the median: normal breathing; the pullback alone carries no
trend-change information.
· Between median and P75: deep but normal correction.
· Above P75: statistically unusual territory. The correct reading is
NOT "it must bounce now" — it is: look for exhaustion evidence
(divergences, capitulation) and demand confirmation.
· The historical maximum (the tail) is the worst-case reference for
position sizing and campaign stops.
INPUTS
· Reversal (%): rally confirming the end of a bearish campaign.
8% = campaign scale (default). 3% = swing scale.
· Minimum depth (%): smaller corrections are excluded from the map.
10% campaign / 5% swing.
LIMITATIONS (read before use)
· Statistics do NOT repaint (completed corrections only), but the
ONGOING correction is provisional by nature: its campaign peak may
extend until the reversal confirms.
· The median convergence was observed in US large-cap tech on the
hourly timeframe; it may not hold in other sectors, assets or
timeframes. Verify it on your symbol before relying on it.
· Enough campaigns (>8-10) are required for the map to be
statistically meaningful; the indicator shows "calibrating…" until
then.
· This is a MEASUREMENT and context tool. It does not generate buy or
sell signals and guarantees no outcome. Not financial advice.
─────────────────────────────────
VERSIÓN EN ESPAÑOL
MAPA DE CAMPAÑAS — LEY DE CONTRERAS
QUÉ MIDE
Este indicador construye la distribución histórica de las correcciones
de campaña de un valor (caídas máximo→mínimo confirmadas por reversión)
y sitúa la corrección actual dentro de ese mapa: ¿es una respiración
normal, una corrección profunda o territorio inusual?
LA OBSERVACIÓN QUE LO ORIGINA
Ley de Contreras (Jacinto Contreras, junio de 2026): en valores
tecnológicos estadounidenses de alta capitalización, la profundidad
típica de las correcciones de campaña converge en una constante
estructural (~14-15% de mediana, escala campaña), independiente del
símbolo. Lo que diferencia a cada valor no es su mediana, sino su cola
máxima histórica (observado: desde ~25% hasta ~53% según el símbolo,
sobre ~11 años de datos horarios en 9 valores).
Moraleja operativa: VIGILAR CON LA MEDIANA, DIMENSIONAR CON LA COLA.
CÓMO FUNCIONA
· Un zigzag por umbral de reversión detecta picos y valles de campaña.
· Solo las correcciones COMPLETADAS (confirmadas por reversión) entran
en la estadística: mediana, percentil 75 y máximo histórico.
· La línea principal muestra la profundidad de la corrección en curso,
coloreada según la zona: normal (verde), profunda (naranja),
inusual (rojo).
· Tabla resumen con el mapa del símbolo y el estado actual.
· Dos alertas: cruce de la mediana y cruce del P75.
CÓMO USARLO
· Por debajo de la mediana: respiración normal; el retroceso no es,
por sí solo, información de cambio de tendencia.
· Entre mediana y P75: corrección profunda pero dentro de lo normal.
· Por encima del P75: territorio estadísticamente inusual. La lectura
correcta no es "ya tiene que rebotar", sino: buscar señales de
agotamiento (divergencias, capitulación) y exigir confirmación.
· El máximo histórico (la cola) es la referencia de peor caso para
dimensionar posición y stops de campaña.
PARÁMETROS
· Reversión (%): rally que confirma el fin de una campaña bajista.
8% = escala campaña (por defecto). 3% = escala swing.
· Profundidad mínima (%): correcciones menores no entran al mapa.
10% campaña / 5% swing.
LIMITACIONES (léelas antes de usar)
· Las estadísticas NO repintan (solo correcciones completadas), pero
la corrección EN CURSO es provisional por naturaleza: su máximo de
campaña puede extenderse hasta que la reversión confirme.
· La convergencia de medianas está observada en tecnológicas USA de
alta capitalización en marco horario; en otros sectores, activos o
marcos puede no cumplirse. Compruébalo en tu símbolo antes de usarlo.
· Se necesitan suficientes campañas (>8-10) para que el mapa tenga
valor estadístico; el indicador muestra "calibrando…" mientras tanto.
· Es una herramienta de MEDICIÓN y contexto. No genera señales de
compra/venta ni garantiza resultado alguno. No es asesoramiento
financiero. Индикатор

Self-Validating Elliott Wave EngineSELF-VALIDATING ELLIOTT WAVE ENGINE
A probabilistic Elliott Wave framework that does three things most wave tools do not: it weighs SEVERAL competing counts at once instead of asserting one, it CALIBRATES its own confidence against what actually happened on the instrument you are viewing, and it tells you honestly when no count is trustworthy. It is decision-support and context - not a signal generator, and never a claim of certainty.
WHY THESE PARTS BELONG TOGETHER (one engine, not a bundle)
Elliott Wave analysis is unavoidably ambiguous: the same swings can support an impulse, a zigzag, a flat or a triangle, and practitioners disagree constantly. A tool that draws one count and hides that ambiguity is misleading. This script is built as a single pipeline whose stages exist specifically to manage that ambiguity, and removing any one stage breaks it:
1. Structure - an alternating swing (ZigZag) series is built from confirmed pivots, and each pivot is tagged with momentum (RSI) and relative volume. This is the raw evidence every wave rule is tested against; without a clean swing series there is nothing to count.
2. Multi-count pattern engine - from that swing series the script forms several competing labelled hypotheses at once (impulse forming wave 3/4/5 or complete, zigzag, flat, contracting triangle). Because Elliott is ambiguous, evaluating alternatives is the whole point, not an add-on.
3. Scoring - each hypothesis is graded on Fibonacci fit, proportion and the alternation guideline (waves 2 and 4 should differ in form), and "wave energy" (does wave 3 thrust hardest, in trend direction, on rising volume?). These are combined deliberately: Fibonacci ratios alone mislabel corrections as impulses; momentum alone is directionless noise; only together do they discriminate real structure.
4. Regime context - a trend/range/compression read (from ADX and ATR) tilts the priors, because impulses are more likely in trends and corrections in ranges. It changes the odds, it does not override the structure.
5. Market-structure confirmation - an independent break-of-structure / change-of-character check raises or lowers the chosen count, so the wave read must agree with raw price action to score well.
6. Calibrated forecast - the forward zone is built from THIS chart's own distribution of historical retracement depths, not fixed ratios pulled from a textbook, so it reflects how the specific instrument actually behaves.
7. Outcome calibration - every forward call (target + invalidation + confidence) is logged and later checked: did price reach target before invalidation? Outcomes are bucketed by confidence, so the confidence number on screen can be mapped to a MEASURED hit-rate. This is the stage that makes the tool self-validating, and it is impossible without all the stages above feeding it.
So the components are not stacked for convenience - they form one loop: build competing hypotheses, score them on structure and momentum, tilt by regime, confirm against price structure, forecast from the instrument's own history, then grade that forecast against reality and report the measured reliability. That is why this is one indicator rather than seven separate overlays.
HOW IT WORKS ON THE CHART
- Wave labels and connecting lines draw the primary (highest-scoring) count's structure.
- A dashed projection line and a shaded forecast zone mark where the primary count expects price to go, with the zone width calibrated from the chart's own retrace history.
- A dashboard reports: the primary count with its probability share, its position and stage, the two best alternative counts, the raw confidence, the measured calibrated hit-rate once enough cases have resolved, the regime, the market-structure state (and whether it confirms or warns), the hard-rule pass/fail, wave energy, an opportunity read (confidence shaped by reward-to-risk and structure), and the target / invalidation levels.
HOW TO USE IT
- Read the ambiguity, not a single answer. The secondary and tertiary counts and their probabilities tell you how clear or murky the structure currently is.
- Trust "Calibrated" over "Confidence". Confidence is the raw structural score; the calibrated figure is the measured success rate for that confidence level on resolved cases - the honest number.
- Respect "stand aside". When confidence is below your threshold the panel says so instead of forcing a count. That is a feature.
- Use target and invalidation as context for your own plan. Invalidation is the level that would break the primary count; the forecast zone is where it expects to resolve. The script places no orders.
- Combine with your own method. The market-structure and regime rows are there so the wave read can be cross-checked against plain price action.
SETTINGS OVERVIEW
- Structure: swing sensitivity (pivot legs), max swings stored, and pivot source - wicks (high/low) or bodies (close), so it suits how you read a given market.
- Scoring weights: Fibonacci fit, proportion/look, wave-3 momentum.
- Context: ADX length and trend threshold.
- Forecast: inner/outer percentiles of the retrace distribution, minimum swings to calibrate, minimum resolved cases before the calibrated hit-rate is trusted.
- Display: minimum confidence for a "clean" count, label/zone/panel toggles, bull/bear colours.
- Alerts: new wave, count flip, invalidation breach, forecast-zone entry (via "Any alert() function call").
Pivot source is selectable and volume is used only when a symbol reports it, so the engine runs on futures, equities, forex, crypto and indices on any timeframe.
ORIGINALITY
Most Elliott tools draw a single count and stop. This one runs a bounded multi-count search, scores each hypothesis on structure plus momentum plus volume, tilts by regime and confirms against market structure, forecasts from the instrument's own retrace distribution, and - uniquely - measures its own realised hit-rate per confidence level so the number on screen is grounded in outcomes rather than asserted. It quantifies and reports its own reliability.
REPAINT NOTICE AND LIMITATIONS (honest)
- Swing detection uses confirmed pivots, which finalise a fixed number of bars after they form. The most recent leg is therefore always provisional and can change. This is inherent to Elliott structure detection and is disclosed deliberately, not hidden.
- Counts are probabilistic hypotheses, not predictions. Two analysts - and this engine on two settings - can read the same chart differently.
- Calibration is a long-run estimate over resolved cases on this chart; early on, and after a regime change, it needs samples before it means anything, and past hit-rate is not a future guarantee.
- This is context and decision-support. It is not a trading system and issues no orders.
DISCLAIMER
This script is for research and education only. It is not financial advice, not a recommendation, and not a solicitation to trade. It places no orders and guarantees no outcome. Markets carry risk; test any tool on your own data and timeframe and make your own decisions.
Индикатор

Индикатор

ShareScope Weiss Wave approximation v1ShareScope Weis Wave Approximation v1
Overview
This indicator is an attempt to reproduce the behaviour of the Weis Wave implementation available in ShareScope using TradingView Pine Script.
The objective is not to recreate every interpretation of David H. Weis's work, but rather to approximate the wave-construction and cumulative volume behaviour observed in ShareScope's Volume Weis Wave indicator.
Methodology
The indicator organises market volume into directional price waves using a percentage-based ZigZag reversal threshold.
A wave remains active while price continues moving in the current direction. When price reverses by the specified percentage amount, the current wave is completed and a new wave begins. Volume is accumulated throughout the life of each wave and displayed as a cumulative histogram.
Available options include:
• ZigZag Value (%) – percentage reversal required to start a new wave.
• Use High/Low – uses candle extremes rather than closing prices when determining wave reversals.
• Symmetric Calculation – applies proportional reversal mathematics so that up and down reversals are geometrically symmetrical.
The calculation updates dynamically as new price data arrives and completed waves become fixed only after the reversal threshold has been reached.
What This Indicator Is Not
Please note - This is not an ATR-based Weis Wave model.
Some modern Weis Wave implementations use Average True Range (ATR), volatility measurements, adaptive thresholds or other dynamic methods to determine wave reversals. This indicator does not use ATR, volatility bands, adaptive filters, moving averages or volume-based reversal logic.
Wave changes are driven solely by the selected percentage reversal threshold, consistent with the behaviour described for ShareScope's Weis Wave implementation.
Notes
David H. Weis never published a single definitive formula for constructing Weis Waves and various software platforms implement the concept differently. As a result, indicators carrying the "Weis Wave" name may produce substantially different results depending on the wave-construction methodology used.
This script focuses specifically on approximating ShareScope's percentage-based wave model rather than ATR-based, volatility-based or proprietary alternatives.
For research and comparison purposes, several exportable data series are included:
• Wave Direction
• New Wave Trigger
• Active Wave Volume
• ZigZag Value
• Current Swing Extreme
These outputs can be accessed through TradingView's Data Window and CSV export facilities.
Индикатор

Elliott Structure Pro RC [Gabremoku]Elliott Structure Pro RC is a market structure and wave-mapping overlay designed to detect candidate Elliott impulse patterns using pivot logic, ZigZag structure, validation rules, invalidation levels, and projected Fibonacci targets.
This script does not claim to produce definitive Elliott Wave counts. Instead, it scans recent pivot structure and highlights the most coherent bullish or bearish candidate sequence based on alternating swing logic, structural progression, and optional Elliott validation filters. That framing is important because Elliott Wave interpretation is inherently subjective, while the classic impulse model still relies on a few widely accepted structural rules.
What it shows
🔺 ZigZag market structure — the script builds a cleaned pivot path from swing highs and lows, filtering out smaller fluctuations to make structure easier to read. ZigZag-style logic is commonly used to reduce chart noise and highlight meaningful turning points.
🏷️ HH / HL / LH / LL tags — every pivot can be classified into higher high, higher low, lower high, or lower low structure, helping the user read trend progression directly from price swings.
🌊 Candidate Elliott 1–5 sequence — the script scans recent pivots and searches for the best bullish or bearish 5-wave impulse candidate.
❌ Invalidation tracking — once a candidate is found, the script projects an invalidation level and can flag when the structure has been broken.
🔤 Optional ABC correction — after a 5-wave sequence, the indicator can also look for a basic A-B-C corrective continuation.
📏 Fibonacci projections — projected target levels for Wave 3 and Wave 5 are plotted using configurable Fibonacci multipliers. Fibonacci extensions are commonly used in Elliott analysis to estimate probable Wave 3 and Wave 5 zones.
🪧 Dashboard — shows state, mode, pivot count, direction, validation strictness, ABC status, broken structure state, and target visibility.
Core logic
The script begins with pivot highs and pivot lows, then compresses them into a cleaner alternating sequence. From there, it builds a structural map and scans the most recent pivots to find a valid 6-point sequence that can represent a 5-wave bullish or bearish impulse candidate.
In practical terms, it combines:
market structure
ZigZag logic
Elliott candidate matching
rule-based validation
invalidation and target projection
That makes it useful as a structure-reading tool first, and an Elliott helper second.
Validation model
The script offers two operating styles:
Semplificato
Avanzato
In simplified mode, the indicator focuses more on structural coherence and swing progression. In advanced mode, it can apply stricter Elliott-style validation rules such as:
Wave 3 not shortest
Wave 4 no overlap with Wave 1 territory
invalid candidate marking when rules are not respected
Those rules align with widely cited core Elliott impulse rules. In standard impulse structures, Wave 3 may not be the shortest of Waves 1, 3, and 5, and Wave 4 should not overlap Wave 1 territory except in special formations such as certain diagonals.
Fibonacci targets
The indicator also projects two practical target references:
Wave 3 target
Wave 5 target
In Elliott analysis, Wave 3 is often projected using Fibonacci expansion of Wave 1, with 1.618 being one of the most common reference ratios, while Wave 5 is often estimated from prior impulse relationships or partial trend expansion logic.
Your script uses configurable multipliers, which is a good choice because different markets and timeframes can produce different expansion behaviors.
How to use
A practical workflow is:
Let the script identify the active pivot structure.
Check whether the chart is printing HH/HL or LH/LL logic.
Watch for a highlighted bullish or bearish 1–5 candidate.
Use the invalidation level to judge whether the count remains structurally valid.
Use projected Fib targets as reference zones, not guaranteed endpoints.
If enabled, monitor whether a simple ABC correction starts forming after the impulse.
This is best used as a decision-support overlay, especially for traders who already read market structure and want an automated way to visualize possible wave candidates.
Features
✅ Pivot-based market structure engine
✅ ZigZag overlay with configurable sensitivity
✅ HH / HL / LH / LL classification
✅ Candidate bullish and bearish Elliott impulse detection
✅ Simplified or advanced scan mode
✅ Optional strict Elliott validation
✅ Wave 3 not shortest filter
✅ Wave 4 overlap validation
✅ Broken-structure detection
✅ Invalidation level plotting
✅ Optional ABC correction detection
✅ Fibonacci Wave 3 / Wave 5 projections
✅ Dashboard and optional bar coloring
✅ Gradient-based swing visualization
Notes
This indicator is designed to identify candidate Elliott structures, not to replace discretionary wave analysis. Elliott interpretation is partly rule-based and partly interpretative, so projected counts and targets should always be confirmed with broader market context, price action, and risk management.
Author: Gabremoku
Pine Script v6 Индикатор

Fibonacci Retracement Statistics by VolProfexFIBONACCI RETRACEMENT STATISTICS BY VOLPROFEX
=============================================
DESCRIPTION
-----------
Fibonacci Retracement Statistics is an analysis tool that
automatically detects price swings, tracks retracements within each trend,
and calculates how often price retraces to various Fibonacci levels. The
indicator labels every completed swing with its swing number and deepest
fib level reached (e.g. "▲ #12 78.6%"), and displays a statistics table
showing the count and percentage of swings reaching each level.
All visual elements (trend boxes, fib lines, retracement boxes, labels, and
the statistics table) are drawn only on the last chart bar, keeping the
indicator performant during real-time scrolling. Retracement labels update
in real time so you always see the current value for the active swing.
HOW IT WORKS
------------
1. SWING DETECTION (ATR-Deviation ZigZag)
A volatility-adaptive ZigZag engine finds pivot highs and lows. A pivot
is confirmed when price moves against the current leg by at least
ATR(period) × deviation multiplier. A minimum swing size filter discards
insignificant wiggles. A spike filter rejects reversals triggered by
bars with extreme wick-to-body ratios.
2. HIGHER-TIMEFRAME (HTF) CONTEXT (optional)
When enabled, the indicator loads data from a higher timeframe (default: 1h)
and runs the same ZigZag engine on it. Completed HTF swings are drawn as
translucent boxes on the chart. Local swings are filtered to only count
when their direction matches the HTF swing they fall inside. This removes
counter-trend noise within the larger structure.
A separate gate ("Exclude Retracements outside HTF swing") further filters
retracement contributions: only retracements where both the trend leg and
the counter-trend leg fall inside the same completed HTF box are counted
in statistics and drawn on the chart.
3. TREND & RETRACEMENT TRACKING
Alternating pivot types (high → low → high → ...) create directional
trends. For each unfinalised trend, the indicator tracks the extreme
retracement price bar by bar. When the trend completes, the retracement
percentage is calculated using the actual counter-trend leg. This value is
then compared against each enabled Fibonacci level.
4. FIBONACCI LEVEL COUNTING
A cumulative counting system tallies how many trends have retraced to
each enabled level. Levels available include: 23.6%, 38.2%, 50.0%, 61.8%,
78.6%, 88.6%, 100.0%, 127.2%, 138.2%, 150.0%, 161.8%, plus up to 5
custom levels (0–500%). The statistics table is split into UP and DOWN
sections, each with its own Level / Count / Percent columns.
5. INTRADAY TIME WINDOW (optional)
On intraday charts, you can set a session window (e.g. 09:30–16:00) to
restrict which swings are analysed. Choose between "Pivot Confirmed Inside"
(the confirming bar's timestamp must fall in the window) or "Full Cycle
Inside" (both the pivot start and confirmation must fall in the window).
A visual box overlay can be enabled to highlight the active window.
6. SPIKE FILTER
Optionally discard ZigZag reversals triggered by bars where the upper or
lower wick exceeds the body by a user-defined ratio. This helps avoid
false pivot signals from sudden, low-liquidity spikes.
SETTINGS REFERENCE (defaults optimised for BTCUSDT, 5m chart, 1h HTF)
---------------------------------------------------------------------
── SWING ENGINE ──
- ATR Period: 14
Period for ATR calculations. Shared by local ZigZag and HTF swing detection.
- ZigZag Deviation Multiplier (ATR ×): 3.0
Pivot confirmed when price reverses by ATR × this value.
- Min Swing Size (ATR multiple): 0.8
Legs smaller than ATR × this are discarded. Set 0 to disable.
── HTF CONTEXT ──
- Use Higher Timeframe Swing Context: ON
When enabled, local swings are counted only when their direction matches the
current HTF swing bias.
- HTF Timeframe: 60
Higher timeframe for context. Must be higher than the chart timeframe.
- HTF Swing Deviation (ATR ×): 3.5
ATR multiplier for HTF pivot reversals.
- HTF Min Swing Size (ATR ×): 1.5
Minimum leg size for HTF swings. Set 0 to disable.
- Exclude Retracements outside HTF swing: ON
When enabled, only retracements fully contained within a completed HTF swing
box contribute to statistics and visual output.
- Show HTF Swings: ON
Draws HTF major swing boxes on the chart (Blue = upswing, Red = downswing).
- HTF Bull Color / HTF Bear Color: Blue (50% transp) / Red (50% transp)
── FIBONACCI LEVELS ──
- Levels enabled by default: 23.6%, 38.2%, 50.0%, 61.8%, 78.6%, 100.0%,
138.2%, 161.8%
- 5 custom level slots, each 0.0–500.0%. Set to 0.0 to disable. Default: all 0.0
── FILTERS ──
- Trend Direction: Both
Options: Both / Uptrends Only / Downtrends Only
- Use Intraday Time Window: OFF
When ON, applies a daily clock window on intraday charts.
- Window Session: 0930-1600
- Window Mode: Pivot Confirmed Inside
Options: Pivot Confirmed Inside / Full Cycle Inside
- Window Timezone: Exchange (uses the symbol's exchange timezone)
- Show Time Window Box: OFF
Visual box highlighting the active intraday window.
- Enable Spike Filter: ON
Discard reversals triggered by spike bars.
- Max Wick-to-Body Ratio: 4.0
Threshold for spike detection (wick ≥ this × body).
── DISPLAY ──
- Show Trend Boxes: ON (Border Width: 1)
Bullish: Teal / Bearish: Maroon
- Show Fib Lines: ON (Width: 1, Style: Dashed, Color: Gray at 60% transp)
- Show Fib Labels: ON (Position: Right, Vertical: Center, Size: Small, Color: White)
- Show Retracement Boxes: ON (Color: Orange at 40% transp)
- Show Retracement Labels: ON (Position: Center, Vertical: Below, Size: Small, Color: Yellow)
- Max Trends Drawn: 50 (1–500)
── TABLE ──
- Table Position: Top Right
- Font Size: Small
VISUAL OUTPUT
-------------
1. Trend Boxes: Translucent coloured boxes spanning each completed swing leg.
2. Fib Lines & Labels: Dashed (or solid/dotted) lines at each Fibonacci level
with optional percentage labels on every completed swing.
3. Retracement Boxes: Overlay boxes on the counter-trend leg with a connecting
diagonal line, colour-coded by trend direction.
4. Retracement Labels: Labels on each retracement showing:
- Arrow direction (▲ = uptrend, ▼ = downtrend)
- Filtered swing number
- Deepest Fibonacci level reached
5. HTF Swing Boxes: Larger translucent boxes showing higher-timeframe swing
structure (blue = up, red = down).
6. Statistics Table: A table in one of four corners displaying:
- Level | Count | Percent for uptrends (teal header)
- Level | Count | Percent for downtrends (maroon header) Индикатор

Cody Zig ZagCody Zig Zag Indicator - Complete Explanation
This is a Zig Zag indicator that replicates the MetaTrader 4 (MT4) version, which works differently than TradingView's built-in Zig Zag. Here's what it does:
🎯 What is a Zig Zag Indicator?
It filters out minor price movements to show only significant swing highs and swing lows, helping you identify trends and chart patterns (head & shoulders, double tops/bottoms, etc.).
⚙️ User Settings (Inputs)
Setting Default What It Does
Depth 6 Lookback period to find local highs/lows
Deviation 5 Minimum price change (in ticks) to form a new swing point
Backstep 2 Minimum bars between swing points
Line Thickness 2 Zig Zag line width
Bull Color Lime Color for upward moves
Bear Color Red Color for downward moves
Repaint Levels true If ON, lines/labels adjust real-time; if OFF, they lock on close
🔍 How It Works (The "Bake" Section)
Step 1: Find Potential Pivot Points
p_lw = Most recent low within Depth bars
p_hg = Most recent high within Depth bars
Checks if price moved enough (Deviation * tick size) to qualify
Step 2: Determine Direction
down = Boolean (true = bearish/downward leg, false = bullish/upward leg)
Tracks whether we're connecting a high→low (down) or low→high (up)
Step 3: Draw Zig Zag Lines
Connects alternating swing highs and swing lows
Labels each point as:
HH = Higher High
LH = Lower High
LL = Lower Low
HL = Higher Low
🏷️ Labels Explained
When price makes a new swing point, you'll see:
HH (Higher High) - Bullish continuation signal
LH (Lower High) - Bearish reversal signal
LL (Lower Low) - Bearish continuation signal
HL (Higher Low) - Bullish reversal signal
📊 Visual Features
Colored Zig Zag lines: Green for up-legs, Red for down-legs
Background color: Green during bullish legs, Red during bearish legs (90% transparent)
Labels: Tiny triangles pointing up/down with text
⚠️ Repaint Behavior (Important!)
Repaint = ON (default) Repaint = OFF
Lines/labels update in real-time Locks on bar close
Can "repaint" history More reliable for backtesting
Good for real-time trading No historical repainting
Warning: Zig Zag indicators naturally repaint because they need future bars to confirm pivot points. The repaint option controls HOW they repaint.
🚨 Alerts
This script triggers alerts when:
Direction Changed - Zig Zag switches from up to down or down to up
Bullish Direction - Switches from down to up
Bearish Direction - Switches from up to down
📈 How to Use
Identify Trend: Upward Zig Zag = Uptrend; Downward = Downtrend
Find Patterns: Look for HH/HL patterns (bullish) or LH/LL patterns (bearish)
Divergence: Compare Zig Zag swings with oscillator indicators
Support/Resistance: Swing points act as natural S/R levels
⚡ Quick Summary
This indicator draws a line connecting significant price swings, ignoring small noise. It's great for:
Visualizing trend structure
Identifying chart patterns
Finding entry/exit levels
Spotting trend reversals Индикатор

Cody Zig Zag Cody Zig Zag – MT4-Style Zig Zag for TradingView
The ZigZag indicator that actually works like the classic MT4 version!
🔍 Overview
Cody Zig Zag is a powerful, fully customizable ZigZag indicator that replicates the exact behavior of the popular MetaTrader 4 (MT4) ZigZag. Unlike TradingView's built-in ZigZag, this version behaves identically to what MT4 traders know and love – making it perfect for Elliott Wave traders, support/resistance hunters, and breakout specialists.
⚙️ Input Parameters (Just like MT4!)
Parameter Default Description
Depth 12 Minimum number of bars between swing points
Deviation 5 Minimum price movement (in ticks) to form a new swing
Backstep 2 Minimum bars between swing points of the same type
Line Thickness 2 Visual weight of the ZigZag line
Bull Color Lime Color for upward swings
Bear Color Red Color for downward swings
Repaint Levels True Enables real-time repainting (MT4 style)
🎯 Key Features
✅ TRUE MT4 BEHAVIOR – Exact replication of MetaTrader 4's classic ZigZag algorithm
✅ INTELLIGENT LABELS – Automatically identifies HH (Higher High), LH (Lower High), LL (Lower Low), and HL (Higher Low)
✅ REAL-TIME UPDATES – Optional repainting mode for live market analysis
✅ DIRECTION BACKGROUND – Visual market direction indicator (Green = Bullish, Red = Bearish)
✅ ALERT CONDITIONS – Get notified when the ZigZag direction changes
💡 How to Use
For Beginners:
Just add the indicator to your chart – the default settings (12,5,2) work perfectly for most timeframes!
For Advanced Traders:
Lower Depth (5-8) → More swings, more detail (scalping/1min charts)
Higher Depth (12-20) → Cleaner swings, fewer signals (swing trading/4H+ charts)
Adjust Deviation → Control minimum swing size based on volatility
🎨 Visual Guide
Lime Line = Price moving UP
Red Line = Price moving DOWN
HH Label = Higher High (uptrend continuation)
LH Label = Lower High (potential reversal down)
LL Label = Lower Low (downtrend continuation)
HL Label = Higher Low (potential reversal up)
📊 Best For
📌 Elliott Wave Counting – Perfect for identifying wave structure
📌 Support & Resistance – Automatically marks swing highs/lows
📌 Breakout Trading – Visualize clear break levels
📌 Divergence Trading – Spot hidden/regular divergences with RSI/MACD
📌 Harmonic Patterns – Identify XABCD patterns easily
⏰ Alert Conditions
Direction Changed – Triggered whenever the ZigZag changes direction
Bullish Direction – When price starts moving up
Bearish Direction – When price starts moving down
🔧 Troubleshooting
Q: Why does the indicator "repaint"?
A: That's how MT4 ZigZag works! Repainting shows the most accurate real-time swing points. Turn OFF "Repaint Levels" if you prefer traditional non-repainting behavior.
Q: What timeframes work best?
A: Works on ALL timeframes! Lower Depth values (5-8) for lower timeframes, higher Depth (12-20) for higher timeframes.
Q: Can I use this for automated strategies?
A: Yes! The alert conditions can trigger tradingview alerts for manual or webhook-based trading.
🙏 Credits
Original MT4 ZigZag logic ported to Pine Script™ v6 by lucemanb
Renamed and optimized as Cody Zig Zag
📝 Keywords
ZigZag MT4 Elliott Wave Swing High Swing Low Support Resistance Divergence Breakout Harmonic Patterns Price Action Trend Reversal Higher High Lower Low Technical Analysis TradingView Indicator Free Indicator
⭐ Support & Feedback
If you find this indicator useful:
Like & Follow for more tools
Leave a review with your suggestions
Share with your trading community
Happy Trading! 🚀
Disclaimer: This indicator is for educational and analytical purposes. Past performance does not guarantee future results. Always practice proper risk management. Индикатор

AG Pro Structure Labels [AGPro Series]AG Pro HH HL LH LL Structure Labels
Overview / What it does
AG Pro HH HL LH LL Structure Labels is a clean market-structure reader built to simplify price action without turning the chart into a wall of signals. Its core purpose is straightforward: identify confirmed swing highs and swing lows, classify them as HH, HL, LH, or LL, and connect those points in a visually readable structure path so traders can understand the current sequence of price development at a glance.
Many market structure tools try to do too much at once. They mix structure, signals, zones, pattern scoring, and trade suggestions into a single publication, which can make the chart heavier and the analytical purpose less clear. This script takes the opposite route. It focuses on one job only: making confirmed swing structure easier to read, follow, and interpret in real time as the chart evolves.
That design choice is what gives this script its value. Instead of asking the user to interpret disconnected highs and lows manually, the script builds a visible structure chain from confirmed pivots and labels each important step. The result is a chart that remains visually disciplined while still communicating trend continuation, structural weakening, and flow transitions in a simple and repeatable format.
This script is especially useful for traders who want structure clarity before they bring in any other layer of analysis. It can be used as a standalone structure map, or as a first-pass chart-cleaning tool before applying other concepts such as support and resistance, trend continuation logic, pullback analysis, breakout validation, or discretionary execution rules.
Unique Edge
The unique edge of this script is not that it attempts to predict where price will go next. Its strength is that it organizes confirmed structure in a way that is visually clean, logically consistent, and immediately usable on live charts.
Unlike many AG Pro scripts that are built around event detection, confluence scoring, price-zone visualization, setup quality filtering, or breakout logic, this publication is intentionally narrower and more focused. It is not a BOS/CHoCH event detector. It is not a liquidity-sweep model. It is not an order-block or fair-value-gap engine. It is not a breakout-quality, retest-quality, or pattern-quality scorer. It is also not a fixed reference-level tool such as a prior-day or prior-week high/low mapper. This script is a structure readability tool first and foremost.
That distinction matters.
Previous AG Pro releases often revolve around a specific trading event: a sweep, a break, a retest, a zone reaction, a continuation pattern, or a multi-factor confluence state. This script does not begin from an event. It begins from the swing chain itself. It asks a simpler question: what is the current sequence of confirmed highs and lows, and what does that sequence imply about market flow right now?
Because of that, the script fills a different role in the broader AG Pro library. It is closer to a structural map than a setup engine. It helps answer whether the chart is still printing constructive highs and lows, whether the sequence has started to weaken, or whether the structure is now leaning in the opposite direction. That makes it useful both on its own and as a foundation layer beneath other tools.
Another important differentiator is presentation discipline. The structure path provides continuity between pivots, while the label set communicates classification without unnecessary chart clutter. The compact floating HUD reinforces the current flow state without dominating screen space. Together, these choices make the script visually premium while keeping the chart readable.
Methodology
The script uses a confirmed pivot framework. Swing highs and swing lows are identified using left and right lookback parameters selected by the user. Because pivots require confirmation, labels appear only after the structure point is confirmed by the specified number of bars. This helps reduce noise and keeps the structure map grounded in confirmed rather than speculative swing points.
Once a new pivot high is confirmed, it is compared with the prior confirmed pivot high. If it exceeds the previous confirmed high, it is classified as HH. If it does not, it is classified as LH. The same logic applies on the low side: if a confirmed pivot low is above or equal to the previous confirmed pivot low, it is classified as HL; if it is lower, it is classified as LL.
The script also includes an ATR-based structure filter. This filter is designed to suppress micro-swings that are too small relative to current volatility, which helps maintain visual cleanliness on choppier charts. Instead of drawing every minor fluctuation, the script attempts to keep attention on swings that are more structurally meaningful for the selected sensitivity.
A structure path, shown as a clean zigzag line, connects the confirmed pivots that pass the filter. This gives the user an immediate visual map of the sequence rather than a collection of isolated labels. In practice, this is one of the most useful parts of the script because it turns the market’s swing progression into a readable path.
The floating HUD summarizes the current market-flow bias in a minimalist format. It is not intended to act as a trade signal. Its job is to provide a quick structural read so the user can see whether the recent chain is leaning bullish, bearish, or transitional according to the internal swing logic.
Signals & Alerts
This script is not designed as a one-click entry engine. Its alerts are structural, not predictive.
The publication includes alerts for newly confirmed HH, HL, LH, and LL prints, which can help users monitor structure development without staring at the chart continuously. It also includes alerts for structure-flow transitions when the internal trend state turns bullish or bearish.
These alerts are best understood as workflow alerts. They tell the user that structure has progressed into a new confirmed condition. They do not guarantee continuation, reversal, breakout success, or trade profitability. Their purpose is to improve awareness of structural change, not to replace independent analysis.
Key Inputs
Pivot sensitivity is controlled through left and right lookback values. Higher values usually produce fewer but more mature structure points, while lower values usually produce a faster and denser structure map.
The ATR filter can be enabled to reduce insignificant swings. This can be particularly helpful on lower timeframes or during periods of uneven, noisy price movement.
Users can also control whether the structure path is drawn and can adjust the visual typography for labels and HUD elements. These inputs allow the script to stay visually flexible across different chart styles and screen densities.
How this script differs from other AG Pro scripts
This distinction is central to the publication.
Many AG Pro scripts are built to evaluate the quality of a setup. They may score breakouts, retests, continuation patterns, reversal candles, pressure conditions, or confluence states. Others are built around zones and reactions, such as supply-demand mapping, premium-discount logic, fair value gaps, order blocks, or support-resistance behavior. Others focus on structural events such as BOS/CHoCH changes, liquidity sweeps, inducement traps, or session-specific reactions.
This script does none of those things.
It does not measure the quality of a signal.
It does not score a setup.
It does not project targets.
It does not identify fixed daily or weekly reference levels.
It does not try to map every institutional concept on the chart.
It does not attempt to be an all-in-one decision engine.
Instead, it provides a cleaner foundation: confirmed HH, HL, LH, and LL sequencing with a filtered structural path and a compact market-flow summary.
That is precisely why it is different from the previous AG Pro script as well. If the previous release was anchored to fixed price levels, event detection, or context-specific reactions, this script is anchored to swing continuity. If another AG Pro script answers where price reacted, where a sweep occurred, whether a breakout was strong, or whether a setup deserves a quality score, this one answers a more basic but highly important question: what is the confirmed structure chain doing right now?
In that sense, this script is less about trading events and more about structural readability.
Limitations & Transparency
This script uses confirmed pivots, which means it is not attempting to label unconfirmed structure in advance. As a result, there is an intentional delay equal to the confirmation logic chosen by the user. That delay is not a flaw; it is part of the design tradeoff required to avoid premature structure labels.
Like any pivot-based structure tool, output will vary depending on sensitivity settings, timeframe, market volatility, and symbol behavior. A lower sensitivity may reveal more swing detail but can also make the map denser. A higher sensitivity may create a cleaner structure path but may respond more slowly to local shifts.
The ATR filter is a visual-cleanliness tool, not a universal truth engine. It can help reduce noise, but different traders may prefer different levels of structural compression depending on how aggressively or conservatively they define meaningful swings.
This script should also not be interpreted as a complete trading plan. It does not include position sizing, stop placement, target selection, execution logic, or market-specific risk rules. Users should combine it with their own framework, testing process, and judgment.
Risk Disclosure
This script is for analytical and educational use. It is not financial advice, investment advice, or a recommendation to buy or sell any instrument.
Market structure is an interpretive framework, not a guarantee of future price behavior. A bullish sequence can fail, a bearish sequence can reverse, and a clean structural print can still occur inside a broader context that changes the meaning of the move.
Always use independent judgment, apply appropriate risk management, and evaluate the script in the context of your own market, timeframe, and process.
Summary
AG Pro HH HL LH LL Structure Labels is built for traders who value structural clarity over indicator overload. Its role in the AG Pro catalog is distinct: it is not an event hunter, not a zone engine, and not a quality scorer. It is a clean structure reader designed to make confirmed swing progression easier to see, easier to follow, and easier to integrate into a disciplined chart workflow.
If your goal is to understand whether price is still producing constructive highs and lows, whether that chain is weakening, or whether the flow has shifted into a different structural condition, this script is designed for exactly that task.
Индикатор

SMC EMA CROSS ZIG ZAG# Mega Trend Suite – SMC + EMA (Lightweight Edition)
**A professional Smart Money Concepts (SMC) toolkit combined with classic EMA crossovers and VWAP.**
No Heikin Ashi, no MA Cross EMA – just clean price action, order flow, and trend confirmation.
---
## 🔍 Overview
This indicator bundles the most essential tools for **institutional-style analysis**:
- ✅ **SMC Structure** (internal & swing BOS/CHoCH)
- ✅ **Order Blocks** (bullish/bearish, with box or candle highlight)
- ✅ **Fair Value Gaps (FVG)** with auto threshold & multi‑timeframe support
- ✅ **Premium / Discount Zones** + Equilibrium line
- ✅ **Multi‑Timeframe High/Low levels** (Daily / Weekly / Monthly)
- ✅ **ZigZag** (main & internal) with HH/HL/LH/LL labels
- ✅ **VWAP** – anchored to the session
- ✅ **Two EMA sets** (9/21 & 20/50) with cross signals
- ✅ **Compact Dashboard** (SMC bias & current timeframe)
- ✅ **Full alert system** for all SMC events and EMA crosses
---
## 🧠 Key Features Explained
### 1. Smart Money Concepts (SMC)
| Component | What it does |
|-----------|---------------|
| **Swing Structure** | Detects Break of Structure (BOS) and Change of Character (CHoCH) on a higher‑length pivot (default 50). Shows labels “BOS” or “CHoCH” when price crosses a swing high/low. |
| **Internal Structure** | Same as swing, but uses a shorter length (default 10) to catch micro‑structure changes. Optional confluence filter (body vs. wick). |
| **Order Blocks (OB)** | Stores the extreme bar (parsed by volatility filter) after a valid BOS/CHoCH. Displays as zone boxes or candle highlights. Mitigation detection (close / high/low). |
| **Fair Value Gaps (FVG)** | Detects 3‑bar imbalances on a chosen timeframe (or current). Uses auto‑threshold based on historical bar delta. Extendable boxes. |
| **Premium / Discount Zones** | Calculates the range between the highest swing high and lowest swing low. Shades the upper 50% (premium) and lower 50% (discount) with an equilibrium line in the middle. |
| **MTF High/Low Levels** | Plots previous period’s high/low for Daily, Weekly, Monthly. Line style (solid/dashed/dotted) and color customizable. |
| **ZigZag** | Classic pivot‑based ZigZag with HH/HL/LH/LL labels. Separate internal ZigZag available for finer swings. |
### 2. VWAP
- Standard Volume Weighted Average Price.
- Useful for intraday bias – price above VWAP = bullish tilt.
### 3. EMA Sets
Two independent EMA pairs:
- **Set 1:** 9 & 21 (fast)
- **Set 2:** 20 & 50 (slower)
Each set plots its own lines and generates up/down triangles on crossover / crossunder. Colours, widths, and signal colours are fully adjustable.
---
## ⚙️ Input Parameters (Grouped)
### 🔧 Master Controls
- `Enable SMC Module` – turn all SMC features on/off.
### 📊 SMC – General
- `Mode` – Historical (keeps all drawings) / Present (refreshes each bar).
- `Style` – Colored / Monochrome.
### 📊 SMC – Structure & Order Blocks
- Internal / Swing lengths, label sizes, BOS/CHoCH filter (All / BOS only / CHoCH only).
- OB display mode (Both / Zone Box / Candle Highlight).
- OB mitigation source (Close / High/Low).
- OB filter (ATR / Cumulative Mean Range).
### 📊 SMC – Fair Value Gaps
- Auto threshold on/off, custom timeframe, extend bars.
### 📊 SMC – MTF High/Low Levels
- Show Daily / Weekly / Monthly – each with independent line style & colour.
### 📊 SMC – Premium / Discount Zones
- Toggle zones, custom colours for premium, equilibrium, discount.
### 📊 ZigZag Swing Lines
- Main ZigZag depth/deviation/backstep, colours, width, style, labels.
- Optional internal ZigZag with separate settings.
### 📈 VWAP & EMA Sets
- VWAP on/off, colour, width.
- Two EMA sets: each with fast/slow lengths, colours, line width, cross signal colours.
### 📊 Dashboard
- Position (Top‑Left/Right, Bottom‑Left/Right), font size.
### 🎨 Colors
- Global bull / bear / neutral colours (used in dashboard).
---
## 🖥️ Dashboard
A small table shows at a glance:
- **SMC Bias** – Bullish / Bearish / Neutral (based on swing trend).
- **Current Timeframe** – e.g., “60” for 1h, “D” for daily.
The dashboard adapts to dark/light chart background.
---
## 🚨 Alerts (30+ conditions)
All alerts are available from the TradingView alert dialog:
| Category | Alerts |
|----------|--------|
| **Internal Structure** | Bull/Bear BOS, Bull/Bear CHoCH |
| **Swing Structure** | Bull/Bear BOS, Bull/Bear CHoCH |
| **Order Blocks** | Bull/Bear Internal OB mitigated, Bull/Bear Swing OB mitigated |
| **Fair Value Gaps** | Bull FVG formed, Bear FVG formed |
| **EMA Crosses** | EMA Set 1/2 Bull Cross, Bear Cross |
---
## 🧩 How to Use
1. **Add the indicator** to any chart (any symbol, any timeframe).
2. **Keep default settings** for a clean SMC + EMA experience.
3. **For scalping / intraday:**
- Enable Internal Structure (length 5–10).
- Use VWAP as bias filter.
- Watch for FVGs on 1m–15m.
4. **For swing trading:**
- Focus on Swing Structure (length 50+).
- Use Premium/Discount zones for entries (buy in discount, sell in premium).
- Confirm with EMA Set 2 (20/50) cross.
5. **Order Blocks:**
- When price returns to a bullish OB zone, look for buying opportunities.
- When a bearish OB gets mitigated, expect continuation down.
---
## 💡 Tips
- **Monochrome style** is perfect for grayscale / minimalistic setups.
- **Present mode** keeps drawings only on the current visible bars – useful for low‑resource usage.
- **FVG auto‑threshold** works best on higher timeframes (1h+). For lower timeframes, you may turn it off and use manual threshold via the `barDelta` calculation (already built‑in).
- The **ZigZag** does not repaint – it uses confirmed pivots.
---
## 📜 Credits & Version
- **Original concept:** Mega Trend Suite (SMC + HAMA + MA Cross EMA)
- **This edition:** Removed HAMA, MA Cross EMA, and Heikin Ashi Smoothed – keeping only SMC, VWAP, and EMA sets.
- **Version:** 1.0 (Pine Script v6)
---
## ❗ Notes
- This indicator is **not a financial advice** – always use proper risk management.
- Maximum drawings (labels, lines, boxes) are set to 500 each – enough for several months of data.
- Multi‑timeframe levels (Daily/Weekly/Monthly) work correctly only if the chart has enough historical data.
---
**Happy trading!**
*Mega Trend Suite – SMC + EMA* Индикатор

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. Индикатор

Zigzag Sequence DetectorOVERVIEW
This indicator is a dynamic pattern recognition tool built strictly on market structure mechanics. It detects custom sequences of Zigzag-based pivot points in real-time. It was developed to automate the tedious process of visually tracking structural shifts and to provide a programmatic foundation for sequence-based trading. It falls into the category of Price Action and Market Structure analysis.
MAIN CONCEPT
If we consider the market as a massive text, this script can be seen as a 'scanning tool' that finds the exact sentence we are looking for it. You write a sentence consisting of the words 'HH, HL, LL, and LH', and this indicator highlights exactly where that sequence occurs in the text.
ZIGZAG & PIVOTS
The core of this tool relies on the ZigZag algorithm, which filters out market noise by only drawing lines when the price reverses by a defined threshold. It reveals the skeletal framework of price action. At the peaks and troughs of these lines lie the pivot points: Higher High (HH), Lower Low (LL), Higher Low (HL), and Lower High (LH). In trading literature, these pivots are the fundamental building blocks of Dow Theory. Tracking these points provides a raw, unfiltered narrative of whether buyers or sellers are in control.
There are many ZigZag alternatives on TradingView that can produce effective results. However, the open-source model developed by @DevLucem provides, in my opinion, the most suitable structure to work on. The original version was based on percentage deviation; I made a minor addition for Mintick-based calculation and update it to version 6 of Pine Script. Special thanks to for his inspiring work.
MECHANICS
• The internal logic uses `chart.point` objects to cleanly track price and time coordinates. As the direction shifts, these objects are copied to maintain independent references.
• `f_calc_dev()`: Dynamically calculates the deviation threshold based on the user's selection (Mintick or Percent).
• `f_parse_sequence()`: Takes the raw string input, strips whitespaces, and splits it into a clean array for processing.
• `f_check_sequence()`: Isolates the most recent elements of the historical pivot array and evaluates them against the user's target sequence array element by element.
• The `trade_direction` state machine uses a unique integer-based accumulation system rather than a simple binary (1 or -1) toggle. It increments (+1, +2) for consecutive Long signals and decrements (-1, -2) for consecutive Shorts. This makes the script highly adaptable for developers building pyramiding strategies or dynamic position sizing models.
HOW TO USE
• Load the indicator on your chart and set your noise-filtering parameters via `Depth`, `Deviation Mode`, `Deviation Value`, and `Backstep`.
• In the settings, input your desired market structures for Entries and Exits using comma-separated values (e.g., "HH,HL,LH").
• You can define Long Entry, Long Exit, Short Entry and Short Exit conditions independently.
• You can also toggle the visual outputs on or off and set the colors in the indicator settings.
THE ALTERNATING PIVOT RULE (Important Note on Sequence Building)
• By the inherent geometric laws of the ZigZag algorithm, market structure must strictly alternate between a peak (High) and a trough (Low). It is structurally impossible for two consecutive peaks or two consecutive troughs to form. Therefore, when building your custom patterns, a High-type pivot must always be followed by a Low-type pivot, and vice versa.
• Invalid Sequences: "HH, HH", "HH, LH", "LH, HH", "LH, LH", "LL, LL", "LL, HL", "HL, LL", "HL, HL". (The engine will accept these inputs, but the condition will never occur on the chart, meaning no signals will ever trigger.)
• Always ensure your custom text sequences obey this strict alternating logic before expecting valid signals.
OUTPUTS
• The script plots ZigZag lines and annotates each confirmed pivot directly on the chart.
• Upon detecting a target sequence, it displays Entry or Exit signals on the triggering bar.
• It continuously feeds raw data (such as the exact `trade_direction` integer and active signal states) into the Data Window for quantitative tracking.
• It allows for setting automated Tradingview alerts based entry and exit signals.
DISCLAIMER
• The default signal sequences are provided for demonstration purposes only; it is the user's responsibility to define meaningful patterns.
• This indicator is not a standalone trading strategy or a predictive tool.
• It mathematically identifies what has already happened based on rigid pivot definitions.
• If the `Last Leg (Repaint)` option is enabled, it evaluates the developing market structure in real-time. This means signals on the current bar can appear and vanish if the price reverses before the pivot is locked in. Индикатор

Gann-Fibonacci Swing Toolkit [BigBeluga]🔵 OVERVIEW
Gann–Fibonacci Swing Toolkit is an advanced swing-based projection tool that combines classic Gann geometry with Fibonacci ratios.
The indicator automatically detects market swings, anchors them to the most recent structure, and dynamically plots either Gann Fans or Gann Boxes to visualize price–time relationships, trend angles, retracement zones, and expansion targets.
This toolkit is designed to help traders understand not only where price may react, but also how fast it should move relative to time.
🔵 HISTORICAL BACKGROUND
The foundation of this toolkit comes from two of the most influential schools of market geometry:
W.D. Gann (early 1900s) introduced the idea that markets move according to geometric and mathematical laws, where price and time must stay in balance . His work emphasized angles (such as 1×1, 1×2, 1×3) that define how much price should advance or decline per unit of time.
Fibonacci ratios , derived from the Fibonacci sequence and popularized in trading decades later, describe natural proportional relationships observed across markets, especially during corrections and expansions.
Modern technical analysis merges these ideas by applying Fibonacci ratios to Gann’s price–time framework, creating tools that measure both distance (price) and duration (time) .
The Gann–Fibonacci Swing Toolkit follows this combined philosophy by grounding all projections in real swing structure rather than static or manually drawn anchors.
🔵 CORE CONCEPT
Swing-Based Anchoring — All calculations start from confirmed swing highs and lows detected via a rolling highest/lowest lookback.
Directional Context — The tool automatically determines bullish or bearish structure and adapts all projections accordingly.
Price–Time Geometry — Gann logic is applied by projecting price movement relative to elapsed bars, not just price distance.
🔵 KEY FEATURES
SWING DETECTION LOGIC
A swing high is confirmed when price forms a local maximum and then fails to extend higher.
A swing low is confirmed when price forms a local minimum and then fails to extend lower.
The most recent completed swing becomes the anchor point for all Gann and Fibonacci calculations.
Optional ZigZag lines visually connect completed swings for structural clarity.
GANN FAN MODE
When Fibonacci Type = Fan , the indicator plots dynamic Gann fan angles from the swing anchor.
Fan Ratios — Each fan line represents a 1/x (1/1, 1/2, 1/3, etc.), defining how much price should move per unit of time.
Trend-Aware Projection
- Bullish fans project upward from swing lows.
- Bearish fans project downward from swing highs.
Fan Fill Zones — Optional shaded regions between fan levels highlight price compression and expansion areas.
GANN BOX (FIBONACCI BOX) MODE
When Fibonacci Type = Box , the indicator builds a Gann Box using Fibonacci retracement and time ratios.
Horizontal Levels — Fibonacci price retracement levels (0.236, 0.382, 0.5, 0.618, 0.786) are projected from the swing range.
Vertical Levels — Fibonacci time divisions are applied across the swing duration to estimate timing of reactions.
Inverse Mode — Flips retracement logic to project inverted expansions instead of standard pullbacks.
OTE Zone — Optional Optimal Trade Entry zone highlights the premium/discount retracement area.
Dual-Axis Structure — Combines price and time into a single geometric framework instead of treating them separately.
MAIN FRAME LOGIC
A dynamic frame is drawn between the swing anchor and current bar, scaled by trend slope.
The frame visually represents the dominant trend channel derived from swing geometry.
VISUAL ELEMENTS
Swing anchor labels mark the exact price and bar index used for calculations.
Color-coded bullish and bearish swings improve structural readability.
Labels on fan and box levels display their exact Fibonacci ratios.
🔵 HOW TO USE
Use Gann Fans to trade dynamic trend support and resistance that evolves with time.
Use Gann Boxes to identify high-probability retracement zones and timing windows.
Combine fan angles with horizontal box levels for confluence-based entries.
Disable ZigZag if you want a cleaner chart focused only on projections.
🔵 CONCLUSION
Gann–Fibonacci Swing Toolkit is a geometry-driven market structure tool that goes beyond static Fibonacci levels.
By uniting Gann’s price–time balance with Fibonacci proportionality and anchoring everything to real swing structure, the indicator provides a deeper framework for understanding trend behavior, corrective depth, and future reaction zones — all derived directly from price action itself. Индикатор

Elliott Wave (Experimental) [UAlgo]Elliott Wave (Experimental) is an automated swing based Elliott Wave scanner that attempts to classify recent market structure into common motive and corrective wave patterns. The script first converts price into a cleaned swing sequence using pivot confirmation and a minimum swing percentage filter. It then runs a two pass detection process that prioritizes five wave patterns first and fills remaining gaps with three wave corrective structures. Each detected pattern is validated with a rule engine, assigned a confidence score using Fibonacci ratio proximity, and rendered on the chart with wave labels, wave lines, optional channels, and optional Fibonacci projection targets.
This indicator is labeled experimental by design. Elliott Wave interpretation is inherently probabilistic and can vary between analysts, so the script focuses on transparent, rule driven validation and a confidence model that helps you judge the quality of each detected structure. Instead of presenting a single rigid count, it can render multiple detected patterns in the swing history and then highlights the latest one in a dashboard with direction, confidence, rule pass ratio, and a next target estimate.
🔹 Features
1) Swing Engine with Pivot Confirmation and Minimum Move Filter
The foundation of the scanner is a zigzag style swing engine. Swings are built from pivot highs and pivot lows confirmed by a configurable lookback. A Min Swing percent filter ensures that only meaningful moves are added as new swings. When consecutive pivots of the same type appear, the engine keeps only the better extreme, which helps reduce noise.
This creates a stable swing sequence that becomes the input for all wave pattern validators.
2) Multiple Pattern Families Supported
The scanner supports a wide set of Elliott structures, each enabled or disabled by inputs:
Impulse 1 2 3 4 5
Diagonal leading or ending with contracting or expanding classification
Zigzag ABC with a 5 3 5 style model
Flat ABC with regular expanded and running classification
Triangle ABCDE with contracting or expanding detection
Combination WXY for double three style sequences
Because patterns can overlap, the script uses a two pass orchestration that gives five wave structures priority, then looks for three wave structures in unused swing segments.
3) Rule Engine with Transparent Results
Each validator returns a WavePattern object that contains:
Wave list with labeled segments
A pattern type tag
Direction bullish or bearish
Validation state
Confidence score
Detailed rule results with pass and fail status and descriptive text
Rules implement common academic guidelines, such as Wave 2 not exceeding Wave 1 origin, Wave 3 not being the shortest, diagonal overlap behavior, and triangle containment conditions.
A relaxed overlap option can be enabled to allow minor Wave 4 overlap into Wave 1 territory when analyzing leveraged or futures markets where strict cash market rules may be less reliable.
4) Fibonacci Based Confidence Scoring
When a pattern passes its core rules, it receives a confidence score based on how close key measured ratios are to common Fibonacci ideals. The score is designed to reward clean proportionality and alternation behavior, while penalizing overlap or weak impulse characteristics.
Confidence is shown in the dashboard and is also mapped to a color for fast interpretation.
5) Rich Chart Rendering with Optional Components
Detected patterns can render several layers of visuals:
Wave lines connecting swing points
Wave labels placed above highs and below lows
Optional wave channel for motive patterns
Optional Fibonacci projection levels with labels
A developing dashed leg from the last confirmed swing to the current bar to indicate the incomplete swing path
A dotted background zigzag to show the underlying swing structure that drives detection
All drawings are rebuilt on the last bar to keep the chart clean and ensure only the current best set of objects remains visible.
6) Fibonacci Projection Engine for Next Targets
The script generates forward projection levels based on pattern type:
After an impulse, it projects common correction retracement levels of the full impulse
After ABC patterns, it projects trend resumption extensions based on Wave A length
After triangles, it projects post triangle thrust targets
The first projection is used as the next target value in the dashboard.
7) Dashboard Summary for the Latest Pattern
A compact dashboard shows the latest detected pattern with:
Pattern name
Direction
Confidence percent
Active wave label
Rules passed count over total rules
Next target from the projection list
Patterns found count and total swings count
This dashboard is designed to provide a quick situational read without requiring you to inspect every label and line manually.
🔹 Calculations
1) Swing Detection and State Management
Swings are detected using pivot highs and lows with symmetric confirmation:
float ph = ta.pivothigh(high, i_pLen, i_pLen)
float pl = ta.pivotlow(low, i_pLen, i_pLen)
When a pivot is found, a WavePoint is constructed at the pivot bar index and time, then passed into the swing engine. The engine enforces alternation and minimum percent change:
If the new pivot is the same type as the last swing, the more extreme point replaces it
If the pivot is the opposite type, it is only accepted if percent change exceeds Min Swing percent
This percent change filter is computed as:
absolute difference between swing prices divided by last swing price times 100
The swing list is capped to a maximum size to limit memory and improve stability.
2) Two Pass Pattern Orchestration with Segment Claiming
The scanner evaluates swing sequences and constructs patterns in two passes:
Pass 1 scans for five wave patterns such as impulse diagonal and triangle. If a valid pattern is found, its swing segment is marked as used so later scans do not overlap it.
Pass 2 scans the remaining unused segments for three wave patterns such as zigzag flat and combination.
This approach reduces overlapping detections and prioritizes larger motive structures.
3) Impulse Validation Rules and Measurements
Impulse detection uses six swing points p0 through p5, producing five waves. It validates:
Wave 2 does not retrace beyond Wave 1 origin
Wave 3 is not the shortest among Waves 1 3 5
Wave 4 does not overlap Wave 1 territory unless relaxed mode is enabled
Wave 3 exceeds the end of Wave 1
Wave 5 generally progresses beyond Wave 3 with tolerance for truncation strength
Wave 3 shows impulse like momentum using a slope proxy based on wave length divided by bar length
Wave ratios are then computed for confidence scoring:
Wave 2 retracement relative to Wave 1
Wave 3 extension relative to Wave 1
Wave 4 retracement relative to Wave 3
Wave 5 extension relative to Wave 3
Wave 5 equality relative to Wave 1
Fibonacci closeness is computed by measuring distance to a list of ideal ratios and converting it into a percent score.
4) Diagonal Validation and Contracting Expanding Classification
Diagonal validation also uses six points. It enforces overlap between Wave 4 and Wave 1 as a defining feature, plus containment rules and the requirement that Wave 5 exceeds Wave 3. It then classifies:
Contracting diagonal when wave lengths shrink in a structured way
Expanding diagonal when wave lengths grow in a structured way
A confidence score is computed using retracement ratios and a momentum decrease check for contracting diagonals.
5) Corrective Pattern Validators
Zigzag ABC validator checks:
Wave B does not exceed Wave A origin
Wave A has a stronger slope than Wave B as an impulse proxy
Wave C ends beyond Wave A
Wave B retracement remains within a tolerance range
Flat ABC validator checks:
Wave B retraces at least 90 percent of Wave A
Classifies regular expanded or running based on whether B exceeds the origin and whether C exceeds A
Requires C to reach or exceed A for regular and expanded cases
Triangle ABCDE validator checks:
Contracting triangle containment of C within A D within B and E within C plus shrinking wave sizes
Expanding triangle growth conditions
Corrective character proxy based on overlap
Combination WXY validator checks:
X does not exceed W origin
W is not triangle like using a size relationship proxy
W and Y proportionality and sideways character checks
X retracement within corrective bounds
Each validator returns rule results and a confidence score when valid.
6) Fibonacci Projection Logic
After detection, the script adds projections to the latest pattern:
For impulse patterns, it projects correction retracement levels of the full impulse: 38.2 percent, 50 percent, 61.8 percent
For ABC patterns, it projects 100 percent and 161.8 percent extensions based on Wave A length
For triangles, it projects thrust targets based on Wave A length
Projection prices are computed by adding or subtracting a multiple of a reference wave length from the last wave end price, depending on detected direction.
7) Rendering and Object Management
On the last bar, the script deletes previous drawing objects and renders the current scan results. Rendering includes:
Wave lines with motive waves in bullish or bearish color and corrective waves in corrective color
Wave labels placed above highs and below lows
Optional wave channel using the wave 2 to wave 4 line and a parallel through wave 3
Fibonacci projection lines and labels extending forward
A developing dashed leg from last confirmed swing to current price proxy
A dotted zigzag reference connecting all swings
This ensures the chart remains responsive and avoids accumulating outdated drawings. Индикатор

Price Simplification [LuxAlgo]The Price Simplification indicator provides a streamlined representation of price action by reducing complex market movements into essential trend segments using the Ramer-Douglas-Peucker (RDP) algorithm.
This indicator calculates its output based on a fixed window of historical data. Consequently, the line segments are displayed retrospectively and are subject to repainting as new bars develop and the calculation window shifts.
🔶 USAGE
The indicator is designed to help traders identify the core structure of price movement by filtering out "noise"—small fluctuations that do not significantly impact the overall trend. By simplifying the price into a series of connected segments, it becomes easier to visualize support/resistance levels, trend slopes, and market geometry.
Users can adjust the level of simplification to suit their needs:
A lower ATR Multiplier will result in a line that follows price closely, capturing more minor swings.
A higher ATR Multiplier will produce a more aggressive simplification, highlighting only the most significant market turns.
🔹 Extension Line
The script includes an "Extend Last Segment" feature. When enabled, it projects the trajectory of the final simplified segment into the future using a dashed line. This projection begins one bar after the most recent data point, providing a visual guide for the current price momentum without overlapping the historical simplification.
🔶 DETAILS
The core logic of this tool relies on the Ramer-Douglas-Peucker (RDP) algorithm, a classic algorithm used in computer graphics and cartography to reduce the number of points in a curve.
The algorithm works through an iterative process:
It starts with a line segment connecting the first and last points of the lookback window.
It identifies the point between these two ends that is furthest from the segment (perpendicular distance).
If this maximum distance is greater than a specified threshold, that point is kept as a "key point," and the algorithm splits the segment into two parts, repeating the process for each.
If no point is further than the threshold, all intermediate points are discarded, and the segment remains a straight line.
To ensure the simplification remains consistent across different assets and timeframes, the script normalizes price coordinates using the Average True Range (ATR) . This means the threshold for keeping a point is relative to the current market volatility rather than a fixed price value.
🔶 SETTINGS
Window Size : The number of recent bars used to apply the RDP algorithm to.
ATR Multiplier : The sensitivity of the simplification. Higher values lead to fewer segments and a simpler line.
ATR Length : The period used to calculate the ATR for price normalization.
Line Color : The color of the simplified polyline.
Line Width : The thickness of the polyline and extension.
Extend Last Segment : When enabled, projects the slope of the final segment forward as a dashed line starting one bar after the last point.
Индикатор

Auto Fibonacci Lines Depending on ZigZag %In the world of technical analysis, few tools are as powerful—or as misused—as Fibonacci Retracements. The Auto Fibonacci Lines Depending on ZigZag % is not just an indicator; it is a complete, automated trading system designed to eliminate subjectivity and bring institutional-grade precision to your charts.
This script automates the identification of significant market structures using a ZigZag algorithm. Once a market swing is mathematically confirmed (based on your deviation settings), it instantly projects a complete suite of Retracement and Extension levels. This allows you to stop guessing where to draw your lines and start focusing on price action.
🧠 The Logic Behind the Indicator
Understanding how your tools work is the first step to trusting them. This script operates on a three-step logic loop:
ZigZag Identification:
The script continuously monitors price action relative to the last known pivot point. It uses a user-defined Deviation % to filter out market noise. A new "Leg" is only confirmed when price reverses by this specific percentage. This ensures that the Fibonacci lines are only drawn on significant market moves, not random chop.
Automated Anchor Points:
Once a downward trend is confirmed (e.g., price drops 30% from the top), the script automatically anchors the Fibonacci tool to the Swing High (Start) and the Swing Low (End). It does this without you needing to click or drag anything.
Dynamic Cleanup:
Markets evolve. A key feature of this script is its self-cleaning mechanism. As soon as a new trend leg is confirmed, the script automatically deletes the old, invalidated Fibonacci lines and draws a fresh set for the new structure. This keeps your chart clean and focused on the now.
🎓 How to Trade This System
This indicator is color-coded to simplify your decision-making process. It moves beyond standard "rainbow" charts by categorizing price levels into three distinct actionable zones.
1. The "Reload Zone" (White Lines: 0.618 - 0.786) ⚪
Role: High-Probability Support / Entry
In institutional trading, the 0.618 (Golden Ratio) to 0.786 region is often where algorithms step in to defend a trend.
Why it works : This is the "discount" area where smart money re-accumulates positions before the next leg up.
2. The "Decision Wall" (Blue Lines: 1.382 - 1.5) 🔵
Role: Strong Resistance / Trend Check
This is a unique feature of this suite. The 1.382 and 1.5 levels often act as a "ceiling" for weak breakouts.
Strategy : If you entered in the White Zone, the Blue Zone is your first major hurdle. If price stalls here, consider securing partial profits.
Warning : A rejection from the Blue Lines often leads to a double-top formation. However, a clean break above the Blue Lines usually signals a parabolic move is beginning.
3. The "Extension Zone" (Yellow, Red, Purple > 1.618) 🟡🔴
Role : Take Profit / Exhaustion
Levels above 1.5 (starting with the 1.618 Golden Extension) are statistical extremes.
Strategy : These are Strict Take Profit levels. Do not FOMO (Fear Of Missing Out) into new long positions here. The probability of a reversal increases drastically as price climbs through these levels (2.618, 3.618, 4.618).
📐 The Mathematical Edge: Logarithmic vs. Linear
One of the most critical features of this script is the ability to toggle between Logarithmic and Linear calculations.
Why use Logarithmic?
If you are trading Crypto (Bitcoin, Altcoins) or high-growth Tech Stocks, linear Fibonacci levels are mathematically incorrect over large moves. A 50% drop from $100 is different than a 50% drop from $10.
This script calculates the percentage difference (Log Scale), ensuring your targets are accurate even during 100%+ parabolic runs.
Why use Linear?
For mature markets like Forex (EURUSD) or Indices (SPX500) where volatility is lower, Linear scaling is the industry standard.
🛠️ Configuration & Best Practices
Deviation % : This is the heartbeat of the indicator.
Swing Trading : Set to 20-30%. This filters out noise and only draws Fibs on major macro moves.
Scalping : Set to 3-5%. This will catch smaller intraday waves.
Text Place : Keeps your chart clean by pushing labels to the right, ensuring they don't overlap with the current price action.
👤 Who Is This Indicator For?
The Disciplined Trader : Who wants to remove emotional bias from their charting.
The Crypto Investor : Who needs accurate Logarithmic targets for long-term holding.
The Confluence Trader : Who combines these automated levels with Order Blocks, RSI, or Volume to find the perfect entry.
⚠️ RISK DISCLAIMER & TERMS OF USE
For Educational Purposes Only:
This script and the strategies described herein are provided strictly for educational and informational purposes. They do not constitute financial, investment, or trading advice. The "Auto Fibonacci Lines" indicator is a tool for technical analysis and should not be used as the sole basis for any trading decision.
No Guarantees:
Past performance of any trading system or methodology is not necessarily indicative of future results. Financial markets are inherently volatile, and trading involves a high level of risk. You could lose some or all of your capital.
User Responsibility:
By using this script, you acknowledge that you are solely responsible for your own trading decisions and risk management. The author assumes no liability for any losses or damages resulting from the use of this tool or the information provided. Always consult with a qualified financial advisor before making investment decisions. Индикатор

Индикатор

Zig Zag ++ SG (Premium)🔥 Zig Zag ++ SG
Professional Market Structure & Cycle Analyzer
Zig Zag ++ SG is an advanced, research-grade market structure indicator built on top of a refined ZigZag engine, designed for traders and investors who want to understand price cycles, not chase candles.
This is not a buy-sell arrow tool.
It is a decision-support system used to analyze trend strength, exhaustion, pullback depth, and cycle behavior across any market and timeframe.
🧠 What Makes Zig Zag ++ SG Different?
Most ZigZag indicators only draw lines.
Zig Zag ++ SG answers the real questions:
Is the trend getting stronger or weaker?
Are higher highs still meaningful?
How deep are pullbacks in percentage terms?
Which stocks recover fast vs stay weak?
Is this accumulation, distribution, or reversal?
It does this by combining:
Market Structure (HH / HL / LH / LL)
Consecutive structure counting
Gain & fall percentage per swing
Clean visual logic (no repaint confusion)
📌 Core Features
✅ 1. Automatic Market Structure Detection
Labels every major swing as:
HH – Higher High
HL – Higher Low
LH – Lower High
LL – Lower Low
This instantly shows whether the market is:
Trending
Consolidating
Distributing
Reversing
✅ 2. Consecutive Structure Count (ON by default)
Each structure type is counted sequentially:
HH (1), HH (2), HH (3)…
HL (1), HL (2)…
This reveals:
Trend maturity
Exhaustion zones
Early breakdown warnings
Example:
HH (4) = trend may be overextended
HL (3) = healthy trend continuation
✅ 3. Gain & Fall % on Every Swing (ON by default)
Every HH, HL, LH, LL shows:
Exact % move from the previous pivot
This allows you to:
Compare pullback depth across stocks
Identify leaders (shallow HLs)
Spot weak stocks (deep HLs / LHs)
Study cycle symmetry
Example label:
HL (2)
-6.4%
✅ 4. Clean, Readable Visual Design
🟩 Green labels → White text
🟥 Red labels → High-contrast white text
Optional background trend shading (OFF by default)
Works perfectly in dark & light mode
Designed for long chart study sessions, not flashy screenshots.
✅ 5. Safe Repaint Logic (Transparent by Design)
Uses ZigZag logic intentionally
No fake “non-repainting” claims
Ideal for analysis, research & planning
What you see is structurally correct
This indicator is for thinking traders, not signal chasers.
⚙️ Best Settings (Recommended)
🔹 Intraday Trading
Timeframe: 5m / 15m
Depth: 8–10
Deviation: 3–5
Backstep: 2
🔹 Swing Trading (Most Popular)
Timeframe: Daily
Depth: 12–15
Deviation: 5
Backstep: 2
🔹 Long-Term / Investing
Timeframe: Weekly
Depth: 15–20
Deviation: 5–8
Backstep: 3
💡 Tip:
Lower depth = more swings
Higher depth = cleaner, major cycles
📈 How to Use Zig Zag ++ SG (Practically)
🔹 Trend Strength
HH (3+) + HL (2–3)
→ Strong, healthy trend
🔹 Exhaustion Warning
HH (4+)
→ Risk of distribution or slowdown
🔹 Pullback Quality
HL −3% to −7%
→ Strong stock
HL −12% to −20%
→ Weak hands / fragile trend
🔹 Reversal Confirmation
LH followed by LL (2+)
→ Trend change likely
🧪 Who Is This Indicator For?
✅ Swing traders
✅ Positional traders
✅ Long-term investors
✅ Market structure students
✅ Stock researchers
✅ Anyone tired of noisy indicators
❌ Not for:
People wanting instant buy/sell arrows
Scalpers chasing 1-minute signals
“Magic indicator” seekers
💎 Why This Is Worth Purchasing
Built with Pine Script v6 best practices
Solves real market questions
Helps avoid:
Buying late
Selling early
Holding weak stocks too long
Encourages process-driven trading
One-time learning tool you’ll use for years
Most traders lose money not because of entries —
but because they misread structure and cycles.
Zig Zag ++ SG fixes that. Индикатор

ATR ZigZag BreakoutATR ZigZag Breakout
This strategy uses my ATR ZigZag indicator (powered by the ZigZagCore library) to scalp breakouts at volatility-filtered highs and lows.
Everyone knows stops cluster around clear swing highs and lows. Breakout traders often pile in there, too. These levels are predictable areas where aggressive orders hit the tape. The idea here is simple:
→ Let ATR ZigZag define clean, volatility-filtered pivots
→ Arm a stop market order at those pivots
→ Join the breakout when the crowd hits the level
The key to greater success in this simple strategy lies in the ZigZag. Because the pivots are filtered by ATR instead of fixed bar counts or fractals, the levels tend to be more meaningful and less noisy.
This approach is especially suited for intraday trading on volatile instruments (e.g., NQ, GC, liquid crypto pairs).
How It Works
1. Pivot detection
The ATR ZigZag uses an ATR-based threshold to confirm swing highs and lows. Only when price has moved far enough in the opposite direction does a pivot become “official.”
2. Candidate breakout level
When a new swing direction is detected and the most recent high/low has not yet been broken in the current leg, the strategy arms a stop market order at that pivot.
• Long candidate → most recent swing high
• Short candidate → most recent swing low
These “candidate trades” are shown as dotted lines.
3. Entry, SL, and TP
If price breaks through the level, the stop order is filled and a bracket is placed:
• Stop loss = ATR × SL multiplier
• Take profit = SL distance × RR multiplier
Once a level has traded, it is not reused in the same swing leg.
4. Cancel & rotate
If the market reverses and forms a new swing in the opposite direction before the level is hit, the pending order is cancelled and a new candidate is considered in the new direction.
Additional Features
• Optional session filter for backtesting specific trading hours Стратегия

ATR ZigZag - Volatility-Filtered Market StructureDescription
This indicator draws ZigZags using an ATR based threshold for direction switching to identify major swing highs and lows. Instead of relying on fractals or fixed bar-count swings, pivots are confirmed only when price moves beyond the prior extreme by:
threshold = ATR(length) × ATR_mult
This filters noise, enforces valid swing structure (high → low → high), and adapts automatically to volatility. The ATR ZigZag is ideal for traders who want a clean, objective view of swing structure without noise. This has many uses, including mapping swing structure, drawing chart patterns, and trading around extremes.
Lag and Repainting
Pivots are confirmed only after price moves sufficiently in the opposite direction. This creates necessary lag. The ZigZag is drawn when this occurs, and will anchor to the high/low in the past. Optional detection dot plots show exactly when confirmation occurred.
What You See
ZigZag: dashed gray line, repainted to anchor at the confirmed highs and lows
Latest Pivot Levels: Dashed horizontal lines at the most recent confirmed high/low.
Optional Live Swing Leg: A real-time line from the last confirmed pivot to the current swing extreme, updating until a new pivot forms.
Optional ATR Boxes: 1×ATR shaded zones around the latest pivot for structural context.
Optional Pivot Confirmation Dots: Markers show the bar where the threshold is crossed and a swing is officially confirmed. This is to understand the lag and see when the ZigZag repainted.
Индикатор

Библиотека
