OPEN-SOURCE SCRIPT
Обновлено Smart ZigZag

Its "Smart ZigZag" indicator for TradingView.
It connects significant price highs and lows to filter out market noise, but unlike a standard ZigZag, it uses a statistical, volume-weighted approach to dynamically identify trend reversals.
Here is a detailed breakdown of what this script does:
1. Main Functions & Statistical Engine
Instead of using fixed percentages or points to find pivot points, this script uses Z-Score and Standard Deviation:
- Baseline Calculation: If the asset has trading volume, it calculates a Volume Weighted Average Price (VWAP) as a baseline. If there is no volume (like on some forex or crypto pairs), it automatically falls back to an ALMA (Arnaud Legoux Moving Average).
- Dynamic Volatility Threshold: It calculates the Standard Deviation of the price relative to that baseline. It multiplies this value by your Z-Score Threshold.
- Trend Filtering: A reversal (new ZigZag leg) is only triggered if the price deviates from the previous peak/trough by more than this dynamic statistical threshold.
2. Core Operational Logic
- Minimum Bar Count (Backstep): To prevent frequent, erratic trend shifts, the script enforces a rule that a specific number of candles (default: 14) must pass before a new trend direction can be confirmed.
- Peak and Trough Updating: While a trend continues in one direction (e.g., an uptrend), the indicator will continuously update and stretch the current line to the newest, highest high. It only locks in a permanent pivot point when a valid reversal occurs in the opposite direction.
- Array Management: It uses internal arrays (zz_values and zz_bars) to efficiently keep track of historical pivot prices and time coordinates.
3. Visuals and Customization
- Real-time Drawing: The script draws dynamic trend lines directly on the chart, using green for uptrends and red for downtrends by default.
- Informative Labels: At every major peak and trough, it places a text box. Depending on user settings, these labels display the exact price level, the percentage change from the previous pivot, or both.
Summary for Traders
This tool helps you see the underlying structure of market trends. Because it utilizes Standard Deviation, the indicator automatically widens its criteria during highly volatile periods (preventing false signals) and tightens them during quiet, consolidating markets.
It connects significant price highs and lows to filter out market noise, but unlike a standard ZigZag, it uses a statistical, volume-weighted approach to dynamically identify trend reversals.
Here is a detailed breakdown of what this script does:
1. Main Functions & Statistical Engine
Instead of using fixed percentages or points to find pivot points, this script uses Z-Score and Standard Deviation:
- Baseline Calculation: If the asset has trading volume, it calculates a Volume Weighted Average Price (VWAP) as a baseline. If there is no volume (like on some forex or crypto pairs), it automatically falls back to an ALMA (Arnaud Legoux Moving Average).
- Dynamic Volatility Threshold: It calculates the Standard Deviation of the price relative to that baseline. It multiplies this value by your Z-Score Threshold.
- Trend Filtering: A reversal (new ZigZag leg) is only triggered if the price deviates from the previous peak/trough by more than this dynamic statistical threshold.
2. Core Operational Logic
- Minimum Bar Count (Backstep): To prevent frequent, erratic trend shifts, the script enforces a rule that a specific number of candles (default: 14) must pass before a new trend direction can be confirmed.
- Peak and Trough Updating: While a trend continues in one direction (e.g., an uptrend), the indicator will continuously update and stretch the current line to the newest, highest high. It only locks in a permanent pivot point when a valid reversal occurs in the opposite direction.
- Array Management: It uses internal arrays (zz_values and zz_bars) to efficiently keep track of historical pivot prices and time coordinates.
3. Visuals and Customization
- Real-time Drawing: The script draws dynamic trend lines directly on the chart, using green for uptrends and red for downtrends by default.
- Informative Labels: At every major peak and trough, it places a text box. Depending on user settings, these labels display the exact price level, the percentage change from the previous pivot, or both.
Summary for Traders
This tool helps you see the underlying structure of market trends. Because it utilizes Standard Deviation, the indicator automatically widens its criteria during highly volatile periods (preventing false signals) and tightens them during quiet, consolidating markets.
Информация о релизе
minor code fixesИнформация о релизе
- A variable length has been introduced for determining the max/min pivot distance.- The current distance between pivots is determined based on volume and, to some extent, price volatility.
- The mechanism for determining background noise has been improved, which creates a "safe price movement channel" before a new pivot is determined.
- The AUTOTUNE option has been improved and enabled by default.
- A dashboard showing the current engine status has been added.
Dashboard (information panel) - its a the "monitoring room" for the Smart ZigZag algorithm, showing you exactly how close the market is to locking in a new high or low.
1. Technical Mechanics (What the Code Does):
- User Customization: It adds settings to easily toggle the panel on/off (show_dash) and choose which corner of the chart it sits in (dash_pos).
- Performance Optimization: By using the barstate.islast condition, the script ensures that these table calculations run only once on the very last candle. This prevents chart lag.
- Dynamic Positioning: The helper function translates text inputs (like "Top Right") into built-in TradingView positions (position.top_right).
2. Dashboard Metrics Explained (What the Data Indicates)
The panel tracks three vital real-time conditions required by the statistical engine to confirm a trend shift:
- Time Window
What it tracks: The number of candles that have passed since the last confirmed peak or valley.
Format: [Current Bars Elapsed] / [Minimum Required Adaptive Backstep] (e.g., 14 / 8 bars).
Color Coding: Turns green when enough time has passed to validate a new cycle (time_condition_met). It stays red if the market is moving too fast for a reliable structural pivot.
- Price Distance
What it tracks: The absolute price distance from the last confirmed pivot, measured against the algorithm's dynamic volatility threshold (Z-Score/ALMA baseline).
Format: [Current Price Distance] / [Dynamic Volatility Threshold] (e.g., 4.20 / 3.50).
Color Coding: Turns green when the price successfully breaks out past the calculated volatility noise barrier (price_condition_met). It stays red if the asset is just chopping sideways.
3. Pivot State
CALCULATING (Red): The market is in a transition zone. Either price or time has not yet met the strict statistical criteria. The algorithm treats the current movement as market noise.READY / LOCKED (Green): Both the price threshold and time window conditions have been successfully cleared, or a brand-new pivot point has just been printed. This indicates a statistically confirmed structural reversal in the market.
Информация о релизе
Minor cosmetic changes have been made to the dashboard:1. In the Pivot row - LOCKED (high) - confirmation of the high and LOCKED (LOW) - confirmation of the low
2. Experimental additional auxiliary Stop Loss Level dynamically set for a given candle within 1-2 standard deviations of the "base noise line"
3. The SL level is set as a short dotted white line above the current candle.
PS - Several default settings for tests:
1. Ultra-Fast Scalping (1 min – 5 min)
• Minimum Backstep: 3 — Enables immediate pivot validation during rapid price spurts.
• Maximum Backstep: 10 — Limits maximum structural delay in highly volatile market
environments.
• Sample Period (StDev/Baseline): 14 — Ultra-short baseline for immediate reactivity to real-time order flow.
• Z-Score Threshold: 0.50 — Lowest allowable threshold; forces the engine to react to micro-deviations.
2. Classic Scalping / Day Trading (5 min – 15 min)
• Minimum Backstep: 5 — Balanced structural flexibility for short-term wave development.
• Maximum Backstep: 15 — Prevents excessive widening of the execution window during
minor trends.
• Sample Period (StDev/Baseline): 20 — Captures the immediate session volume profile accurately.
• Z-Score Threshold: 0.75 — Optimizes target zones by lowering the statistical barrier.
3. Intra-day / Short-term Swing Trading (15 min – 60 min(1H))
• Minimum Backstep: 8 — Standard setting to capture clean intraday liquidity sweeps.
• Maximum Backstep: 25 — Protects the chart from rendering excessive micro-pivots.
• Sample Period (StDev/Baseline): 35 — Captures an accurate rolling mean of intraday volatility.
• Z-Score Threshold: 1.0 — Standard 1.0 Standard Deviation barrier (represents the classic 68% statistical boundary).
4. Swing Trading (2h – 4h)
• Minimum Backstep: 10 — Standard buffer ensuring only valid major market swings are captured.
• Maximum Backstep: 35 — Allows deep algorithmic tracking across broader weekly ranges.
• Sample Period (StDev/Baseline): 50 — Generates a highly stable and robust statistical baseline.
• Z-Score Threshold: 1.0 — Solid protection layer against false expansion breakouts.
5. Position Trading / Macro Portfolio (1D - Daily)
• Minimum Backstep: 12 — Completely isolates structural market bottoms and cycle peaks.
• Maximum Backstep: 45 — Accommodates major expansion phases stretching across multiple quarters.
• Sample Period (StDev/Baseline): 60 — Maximizes data smoothing to capture raw institutional drift.
• Z-Score Threshold: 1.25 — Elevated barrier; prevents the dashboard from triggering LOCKED states during minor corrections inside the primary trend.
Default settings are optimal for 1H to 1D.
Информация о релизе
Added table size changeИнформация о релизе
added an extensive dashboard with progress bars and extensive explanation1. Confirmation Filters (Time & Price)
- Time Window: Counts how many bars have passed since the last pivot and compares it to the adaptive backstep requirement. The progress bar visually counts down the time.
- Price Distance: Measures the current price distance from the last pivot against the dynamic volatility threshold (Z-Score market noise).
- UI Behavior: Both rows utilize a strict background color fill (Red = condition not met, Green = condition met). The internal loading bars use your custom-selected color.
2. Structural Status (Pivot State)
- CALCULATING (Red Background): Price is actively pushing. The current peak or valley is temporary ("floating") and will continue to update if the market keeps moving in that direction.
- LOCKED (Green Background): Both Time and Price filters have simultaneously hit 100%. The pivot is permanently locked onto the chart history, drawing a new ZigZag line.
3. Trade & Risk Management - experimental - (Active SL)
This operates on a continuous reverse-trading model based on the wave direction (dir):
- Impulse Phase (Color: sl_impulse): You are trading with the current momentum. If the wave is rising (dir=1), you are in a LONG trade, and the SL trails dynamically below the current market price. If falling (dir=-1), you are in a SHORT trade, and the SL trails above the current market price.
- Safe / LOCKED Phase (Color: sl_locked): The market structure locks, triggering a position reversal. The SL instantly flips above the newly locked peak (for Short entries) or below the newly locked valley (for Long entries) to protect the new macro structural level.
and I think that's all I wanted to tell you - I consider the indicator to be finished - high profits ;)
Информация о релизе
- Automatic deviation/breakout boundary selection has been added to autotune.- Improvements to the status display panel.
As a reminder, this indicator is used to determine pivot points. It is not a trading/decision panel. The decision regarding when to buy or sell must be based on your own judgment.
Информация о релизе
- minor changes and corrections to the code- additional description of the dashboard's operation/algorithm
- a sample usage example for those asking how to use it in practice - a guide for those looking for a NO-OBLIGATION READY-MADE GUIDE - this is not a guide, but merely a guide to help you understand how the indicator works
--------------------------------------------------------
How the Dashboard and Algorithm Work
The dashboard serves as a visual verifier for the so-called "structure lock" (Locked State). Instead of drawing pivots immediately, the script waits for two market filters to be confirmed: time and price.
1. The Three Pivot States
- CALCULATING (Impulse - Red/Orange Color): A new local pivot is attempting to form. The market is moving in an impulse phase, but the minimum conditions have not yet been met. The price remains "in suspense."
- LOCKED (Locked - Green Color): The pivot has been officially approved and locked (state_is_locked := true). This occurs because the required time has passed (time_condition_met) AND the price has moved away from the last high/low by the required volatility distance (price_condition_met).
- SEARCHING NEXT PIVOT (Searching for a new point): A transitional state where the market, after locking the structure, begins to aggressively break the level in the opposite direction, negating the previous trend direction.
2. Progress Bars
- Time Window: Measures the time elapsed since the last pivot (elapsed_bars) relative to the adaptive threshold (adaptive_backstep_threshold). A green color means enough candles have passed to consider the structure mature.
- Price Distance: Shows the current distance of the price from the pivot (current_distance) relative to the dynamic volatility threshold (dynamic_threshold). A green color means the price has made the minimum required movement to justify a market phase change.
3. Dynamic Stop Loss Engine (Active SL)
The script automatically calculates an invalidation level by adding a market noise buffer (dynamic_noise_buffer) to the pivot point, which is expanded by a volume factor (norm_vol).
- In the Impulse state (CALCULATING): The SL line protects the position below/above the last pivot (classic protection against false breakouts).
- In the Locked state (LOCKED): The high/low is considered stable, and the SL line moves to a market-defined level, protecting profit or capital based on the assumption that the market has already reached its destination.
- Mirror Line: The code also generates a second SL line (mirror image), which represents a symmetrical risk level on the opposite side of the current close price.
Swing Strategy (Pivot-to-Pivot)
A swing strategy for traders capitalizing on movements from one turning point to another (from boundary to boundary). It is designed to maximize the Risk-to-Reward (R:R) ratio using the dashboard readings.
1. Entry Conditions (Trigger)
- You wait for the moment when the Pivot State changes from red (CALCULATING) to green (LOCKED).
- Entry Direction (LONG): The dashboard displays the message LOCKED (LOW) (confirmed bottom).
- Entry Direction (SHORT): The dashboard displays the message LOCKED (HIGH) (confirmed peak).
2. Protection Level (Stop Loss)
- You open the position immediately after the close of the candle where the state changed to LOCKED.
- You set your physical Stop Loss at your exchange/broker exactly at the value indicated by the dashboard in the Active SL cell (the white dotted line on the chart).
3. Target and Position Management (Take Profit & Management)
- Take Profit (100% Swing): You close half of the position (50%) at the level of the last historical opposite Pivot (meaning if you open a Long at a Locked Low, you target the previous structure peak).
- Managing the second half: You leave the remaining 50% of the position open, aiming to exit only when the dashboard changes to the opposite LOCKED state (e.g., generates a Locked High for a Long position) or when the price touches the dynamic mirror reflection line (calculated_sl_opp).
- Emergency Management: If the dashboard enters the SEARCHING NEXT PIVOT state before your first target is reached, you unconditionally close the entire position manually at the market price (as the market has negated the mathematical structure of the setup).
Информация о релизе
Probably the final version:)1. Introduced automatic selection of all parameters except min-max values (default 7-19)
2. Simplified dashboard status mechanics:
- Time Window indicates the distance to the next high, and a floating bar indicates the % time to reach the target. Due to the dynamic nature of the search, this may change slightly, either decreasing or increasing.
- After determining a low, the script will search for the high by default, BUT in the "Probability Bias" window, it actively shows the status of subsequent candles.
- "Probably Lower" means that the pivot point of the low may be shifted down.
- "Probably Higher" means that subsequent candles are searching for the high.
3. "Active SL" shows a dynamic SL level at 1-2 ATR. 4. Additional baselines are drawn – these are the result of the final calculations and are used to visually check the status:
- When the "Fast baseline" falls (red) from the "Long baseline," the message "Probably Lower" appears.
- When the "Fast baseline" rises (green), the message "Probably Higher" appears.
Информация о релизе
minor.Информация о релизе
- Time Window 0/X-averageИнформация о релизе
minorИнформация о релизе
Minor changes to the Sigmoid engine:- Introduced a "star-based" pivot strength rating: 1 – weak, 2 – normal/standard, 3 – very strong. This rating provides a visual indication of the market pressure behind the formation of the extreme point (i.e., whether the pivot is significant, normal, or weak).
- Added a buy/sell strength slider that operates ONLY between pivots; it indicates the dominant side during the creation of a new pivot or the shifting of an existing one.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.