You add a zigzag to a chart, and for a moment it looks like the cleanest map of price you have ever seen: straight legs, clear swing highs, clear swing lows. Then you scroll back an hour later and the last leg has moved. Or worse, you scroll back through history and every leg lands exactly on the turning point, which no indicator could have known at the time. Both problems come from the same place, and fixing them is mostly a matter of deciding when a swing is allowed to exist.
This guide builds a zigzag in Pine Script v6 on top of confirmed pivots, so a leg that has been drawn stays where it was drawn. Along the way it explains what a zigzag really is, why the classic version repaints, what you give up by making it honest, and how to extend it into a swing-labelling layer. If you would rather see the swings on a chart before you write any code, there is also a section on doing that with the PineScripter chart agent, and a way to turn the result into an indicator.
What a zigzag actually is
A zigzag is not an indicator in the sense that an RSI is. It does not transform price into a new series. It filters price: it throws away every bar that is not a meaningful turning point and connects the turning points that remain with straight lines. What you see is a simplified path through the chart, alternating between a swing high and a swing low, high, low, high, low, never two highs in a row.
The word meaningful carries all the weight. Something has to decide which turning points count. The classic zigzag decides by size: a new swing is recorded only after price has reversed by some percentage, or by some multiple of the average true range, from the last extreme. Another approach decides by shape: a bar counts as a swing high if it is the highest bar within a window of bars on each side. The first method is a threshold zigzag and the second is a pivot zigzag. They produce similar drawings on a clean trend and different drawings in a chop.
Because the output is a path of straight legs, a zigzag is mostly a reading aid. Traders use it to see structure without candle noise, to measure how large recent swings were, to anchor retracement tools, and as the raw material for higher-level ideas such as higher highs and lower lows or support and resistance zones drawn from swings. It describes where price has been. It says nothing about where price goes next, and nothing in this article should be read as if it did.
Why the classic zigzag repaints
Think about what a threshold zigzag has to do on the live bar. Price makes a new high, so the current leg extends upward and its end point moves with every tick. Eventually price falls far enough to cross the reversal threshold, and only then does the indicator know that the previous high was a swing high and a new downward leg has begun. Until that moment, the end of the last leg is a guess that keeps being revised.
That revision is repainting in the plainest sense: the line you saw on bar 100 is not the line that is stored for bar 100 once the chart reloads. The built-in zigzag tools on most platforms behave this way, and it is not a bug. A drawing tool that shows you the current best estimate of the path is useful. It is only a problem when you test an idea against it, because the history you see was drawn with knowledge that did not exist at the time. Any rule built on those legs will look better on past data than it could have been in real time. The repainting guide covers the general family of this problem, and the lookback bias article shows how it inflates an indicator that looks perfect in hindsight.
The pivot approach is easier to make honest, but it has its own trap, which is delay. A pivot high needs bars on its right side to prove that nothing higher followed it, so it can only be known after those bars have closed. That delay is not an implementation flaw you can tune away. It is the price of being sure.
Pivots as the honest foundation
Pine Script v6 gives you the building blocks as ta.pivothigh() and ta.pivotlow(). Each takes a source series, the number of bars to the left, and the number of bars to the right. A bar is a pivot high when its value is higher than the values of that many bars on each side. The function returns the pivot price on the bar where the pivot is confirmed and na on every other bar.
The detail that trips almost everyone is where the value appears. With five bars on the right, the function returns the pivot price five bars after the pivot actually happened, because that is when the fifth confirming bar closes. The pivot itself sits at bar_index - rightBars. If you draw the label at the current bar, it lands in the wrong place; if you draw it at the pivot bar after the fact, it appears to have always been there, which is exactly what makes a chart look prescient. The honest version draws at the pivot bar but only after the confirmation, and you accept that a viewer watching live will see it appear a few bars late. The article on why pivots arrive late goes deeper on this timing.
So the contract of a non-repainting zigzag is simple. A swing exists from the moment it is confirmed, never earlier. Once drawn, it is not moved by later price. The only legitimate edit to an existing leg is the one the structure demands: if a second pivot high is confirmed with no pivot low between them, the earlier high was not the end of the leg after all, and the leg should extend to the higher one.
Building the zigzag
The script below keeps track of the direction of the last confirmed pivot, its price, and its bar. When a new pivot arrives in the opposite direction, it draws a new leg from the last pivot to the new one. When a new pivot arrives in the same direction and is more extreme, it stretches the existing leg instead of starting a new one. A pivot in the same direction that is less extreme is ignored, since it does not change the path.
//@version=6
indicator("Zigzag (confirmed pivots)", overlay = true, max_lines_count = 500)
leftBars = input.int(5, "Pivot bars on the left", minval = 1)
rightBars = input.int(5, "Pivot bars on the right (confirmation delay)", minval = 1)
upColor = input.color(color.teal, "Up leg")
dnColor = input.color(color.maroon, "Down leg")
float ph = ta.pivothigh(high, leftBars, rightBars)
float pl = ta.pivotlow(low, leftBars, rightBars)
var int lastDir = 0 // 1 = last pivot was a high, -1 = a low
var float lastPrice = na
var int lastBar = na
var line currentLeg = na
if not na(ph)
int pBar = bar_index - rightBars
if lastDir == 1
if ph > lastPrice
line.set_xy2(currentLeg, pBar, ph)
lastPrice := ph
lastBar := pBar
else
if lastDir == -1
currentLeg := line.new(lastBar, lastPrice, pBar, ph, color = upColor, width = 2)
lastDir := 1
lastPrice := ph
lastBar := pBar
else if not na(pl)
int pBar = bar_index - rightBars
if lastDir == -1
if pl < lastPrice
line.set_xy2(currentLeg, pBar, pl)
lastPrice := pl
lastBar := pBar
else
if lastDir == 1
currentLeg := line.new(lastBar, lastPrice, pBar, pl, color = dnColor, width = 2)
lastDir := -1
lastPrice := pl
lastBar := pBarA few choices in this code are worth explaining. The else if means that when a single bar is both a pivot high and a pivot low, which can happen on a wide outside bar, only the high is processed. That keeps the alternation rule intact at the cost of occasionally skipping a swing, and it is an honest trade for a reading aid. The state is held in var variables so that it persists across bars, which is the same mechanism described in the var and varip guide. The leg end points are stored in bar index coordinates, so they do not shift when you change timeframe settings on the chart.
Notice also what the script never does: it never draws a provisional leg to the current bar. The path stops at the last confirmed pivot, and the gap between that pivot and the right edge of the chart is exactly the confirmation delay. That blank stretch is not a missing feature. It is the visible form of the fact that nobody can know the latest swing yet.
Tuning the delay against the noise
The two inputs trade sensitivity against certainty. With one bar on each side, almost every small wiggle becomes a pivot and the zigzag hugs price, but you get the confirmation after a single bar. With ten bars on each side, only larger turns survive, the path is calmer, and each swing shows up ten bars after it formed.
Using different left and right values is also legitimate. A large left value and a small right value asks for a bar that stands out against a long history but confirms quickly. The cost is that you will accept pivots that were only prominent relative to the past, and price may continue straight through them. There is no setting that gives you both a fast confirmation and a guarantee that the swing was significant. Pick the delay you can live with for the timeframe you read, and keep it fixed when you compare charts.
Timeframe changes the meaning of the same inputs. Five bars on a 15 minute chart is a little over an hour of confirmation, five bars on a daily chart is a trading week. When a swing seems to appear too late on a higher timeframe, that is the arithmetic of bars, not a defect in the code.
Labelling the structure
A path of legs is useful, but most readers want to know how each new swing compares with the one before it. A confirmed high above the previous confirmed high is a higher high, one below it a lower high, and the same logic applies to lows. The script below labels each confirmed pivot with its relationship to the previous pivot of the same kind. It uses the same pivot functions, places each label at the pivot bar, and fires an alert condition when any new swing is confirmed.
//@version=6
indicator("Swing Structure Labels", overlay = true, max_labels_count = 500)
len = input.int(5, "Pivot bars on each side", minval = 1)
float ph = ta.pivothigh(high, len, len)
float pl = ta.pivotlow(low, len, len)
var float prevHigh = na
var float prevLow = na
if not na(ph)
string highTag = na(prevHigh) ? "H" : (ph > prevHigh ? "HH" : "LH")
label.new(bar_index - len, ph, highTag, style = label.style_label_down, color = color.new(color.teal, 20), textcolor = color.white, size = size.small)
prevHigh := ph
if not na(pl)
string lowTag = na(prevLow) ? "L" : (pl < prevLow ? "LL" : "HL")
label.new(bar_index - len, pl, lowTag, style = label.style_label_up, color = color.new(color.maroon, 20), textcolor = color.white, size = size.small)
prevLow := pl
alertcondition(not na(ph) or not na(pl), "Swing confirmed", "A new swing pivot was confirmed")The labels describe structure that already happened. They do not say a trend will continue, and a run of HH and HL labels is a description of the past, nothing more. The alert condition fires on the bar where the pivot is confirmed, which is the same late bar as the label's data, so a script that reacts to it is reacting to something that is genuinely known. If you want a deeper treatment of alert timing, why alerts fire on the wrong bar is the natural next read.
Each label is a drawing object, and Pine Script limits how many it keeps. The max_labels_count and max_lines_count arguments raise the cap to 500, and the oldest objects are removed as new ones are created. On a long history you will only see the most recent swings, which is usually what you want, and the drawing objects article explains how the limits work and how to manage them.
Checking that it does not repaint
Do not take the claim on trust. There are three quick checks, and they take a couple of minutes each.
First, add the script, note the position of the last few legs, and reload the chart. Confirmed legs must be in the same place. Second, watch the live bar. The path should only change when a new pivot is confirmed, never from tick to tick. Third, step through the history one bar at a time and watch when each leg appears. Each should appear rightBars bars after the turning point, and never before. If a leg ever shows up at the turning point itself, something in the code is reading the pivot at the wrong offset.
The third check is the one most people skip, and it is the most convincing. Seeing a leg arrive late is what makes the delay concrete. PineScripter has a bar-by-bar replay for exactly this: it steps a chart run one bar at a time so you can see when a script reacts. It is also the quickest way to tell whether a zigzag you pasted from somewhere else has the problem described above.
Mark it on the chart with the agent
Sometimes you want the swings on a chart before you write a line of code, to decide whether a pivot window of five or ten bars matches what you see. The PineScripter chart agent does that with a request in plain English. On PineScripter's own chart, you might type:
"Mark the swing highs and lows on BTCUSDT 4h and draw the levels they cluster into as zones."
The agent starts by reading the chart: the swing levels it can find, with a touch count for each, and any drawings already on the chart. It then draws with the drawing tools from the toolbar while you watch its cursor move and click the points, and it can switch the market or timeframe if you ask it to. The whole batch of drawings can be undone in one step, so a mark you do not like costs nothing to remove. It works on PineScripter's own chart of crypto spot markets, not on your TradingView chart, and it marks what you ask for rather than choosing anything for you.
The result is a starting point for your own reading, not an answer. Check the touch counts against what you can see, switch the timeframe and see whether the same swings survive on the next one up, and step through the chart in replay to see whether the swings you marked were visible when they would have mattered. If the agent marked something you disagree with, that disagreement is useful, because it tells you what your own definition of a swing is, and that definition is what the pivot inputs encode.
Once the marks look right, the next request is the bridge to code: "Turn this into an indicator that finds these swings on every chart." The result is a script of the kind built above, with pivot windows chosen to match what you checked by eye. You then have Pine Script you own, which you can read, edit, and paste into TradingView. You can try it in PineScripter, and the overview of the chart agent explains what it can and cannot do. If you prefer to start from your own lines, turning hand-drawn chart lines into an indicator covers that route.
Common mistakes
The most frequent mistake is drawing at the current bar instead of the pivot bar, which puts every label rightBars bars too far right and makes swings look like they arrive on time. The second is the opposite: back-drawing every pivot at its turning point and then using those drawings inside a backtested strategy, where a rule that reads the swing at the turning point has information it could not have had. Keep the logic that trades or alerts keyed to the confirmation bar, not to the pivot bar.
A third mistake is treating the zigzag as a statement about significance. A swing is only as meaningful as the window that produced it. Two traders can look at the same chart with a window of three and a window of fifteen and see different structure, and neither is wrong. Write down the window you used when you share a chart.
The last is forgetting the object limits and wondering why old legs vanish, or leaving max_lines_count at its default and hitting it. The fix is the argument shown in the first script.
Where to go from here
You now have a zigzag whose legs stay where they were drawn, a labelling layer that names the structure, and a way to check both without trusting anyone. From here the natural extensions are measuring the size of each leg, drawing retracement levels from the last two pivots, or turning clusters of pivots into zones. Each of those is a layer on the same confirmed foundation, and each is easier to get right when the foundation is honest about when a swing becomes known.
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.
Frequently asked questions
Does a zigzag in Pine Script repaint?
A threshold zigzag that extends its last leg to the current bar repaints, because that leg keeps moving until a reversal is confirmed. A zigzag built on ta.pivothigh and ta.pivotlow draws a leg only after the pivot is confirmed, so confirmed legs do not move.
Why does my zigzag appear several bars after the swing?
A pivot needs bars on its right side to show nothing higher or lower followed it. With five right bars, the swing is known five bars after it formed. That delay is the cost of not repainting.
What pivot length should I use for a zigzag?
Small values follow price closely and confirm quickly but include minor wiggles. Larger values give a calmer path with a longer delay. Choose one for the timeframe you read and keep it fixed when comparing charts.
Can the zigzag predict the next swing?
No. A zigzag describes swings that already happened. It makes no statement about where price goes next.
Can the PineScripter chart agent draw swings for me?
On PineScripter's own chart of crypto spot markets, you can ask the agent to mark swing highs and lows. It reads swing levels with touch counts, draws with toolbar tools, and the batch can be undone. You check the result yourself.
Ask the agent to mark it on the chart, then turn it into Pine Script →
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.