You drag the Fib Retracement tool onto a swing, adjust the anchors, and it looks great. Then the market prints a new swing, the old drawing is stale, and you do it all again. Do that across a few charts and a few timeframes and the tool that was supposed to save time becomes a chore. Pine Script can draw the levels for you, and it can redraw them every time the structure changes. The catch is that "automatic" hides several decisions: which swing counts, when it counts, and what happens to the old drawing.
This post builds Fibonacci levels in Pine Script v6 two ways. The first anchors levels to confirmed pivots and redraws them when a new swing forms. The second uses a rolling high and low over a fixed window, which never lags but also never settles. You will see the arithmetic behind a level, the drawing code, the limits that bite, and how to fire an alert when price reaches a level. Everything here describes how levels are computed and drawn. Nothing about a level says price will respect it.
What a Fibonacci level actually is in code
A Fibonacci retracement level is a price calculated from two anchors. You pick a start price and an end price, take the difference, and multiply it by a ratio. If a swing runs from a low of 100 to a high of 200, the 0.618 level sits 61.8 percent of the way back from the high: 200 minus (200 minus 100) times 0.618, which is 138.2.
The common ratios are 0.236, 0.382, 0.5, 0.618, and 0.786. Most of them come from the golden ratio, 1.618. Dividing 1 by 1.618 gives 0.618, one minus 0.618 gives 0.382, 0.618 cubed gives roughly 0.236, and the square root of 0.618 gives roughly 0.786. The 0.5 level is not a Fibonacci ratio at all. It is included by convention because traders watch the halfway point. Extensions such as 1.272 and 1.618 work the same way but project beyond the end anchor instead of back toward the start.
The formula is one line, which is why the whole problem is really about the anchors. Write it as a function and you never repeat it:
//@version=6
indicator("Fib Level Function", overlay = true)
fibLevel(float startPrice, float endPrice, float ratio) =>
endPrice - (endPrice - startPrice) * ratio
float swingHigh = ta.highest(high, 50)
float swingLow = ta.lowest(low, 50)
plot(fibLevel(swingLow, swingHigh, 0.618), "0.618", color = color.orange)Ratio 0 returns the end anchor, ratio 1 returns the start anchor, and everything in between is a retracement. The same function handles both up legs and down legs, because the sign of the difference flips for you. If you want to check the numbers by hand before you trust the script, the free Fibonacci retracement calculator gives the same levels for any pair of prices and shows the Pine Script that computes them.
Choosing the anchors: confirmed pivots versus a rolling range
There are two honest ways to pick anchors automatically, and they behave very differently.
The first is pivots. A pivot high is a bar whose high is the highest of the surrounding bars, and ta.pivothigh needs bars on both sides of the candidate to decide. With a right-side length of 10, the pivot is only known 10 bars after it happened. That delay is not a bug, it is the definition of a confirmed swing, and it is why pivot signals arrive late. We cover the details in why your pivot signals arrive late. The benefit is that once a pivot is confirmed it does not move. Levels built on it are stable and do not repaint.
The second is a rolling range: the highest high and lowest low of the last N bars, from ta.highest and ta.lowest. There is no delay, since the range updates on every bar. The cost is that the anchors slide. A new high extends the range and every level shifts with it, and when an old extreme drops out of the window the range can jump. That is fine for a moving reference line but poor for a structural drawing.
Neither is better in general. Pivot-anchored levels suit a drawing that represents a specific swing. A rolling range suits a plotted level you want to test conditions against on every bar. The next two sections build one of each.
Auto-drawn levels from confirmed pivots
The plan: keep the last confirmed pivot high and pivot low, remember which came last to know the direction of the current leg, and redraw the levels whenever a new pivot confirms. Lines and labels go into arrays so the previous set can be deleted before the next one is drawn.
//@version=6
indicator("Auto Fibonacci Levels", overlay = true, max_lines_count = 100, max_labels_count = 100)
pivotLen = input.int(10, "Pivot length", minval = 2)
extendRight = input.bool(true, "Extend lines to the right")
var float[] ratios = array.from(0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0)
var line[] fibLines = array.new<line>()
var label[] fibLabels = array.new<label>()
var float lastHigh = na
var int lastHighBar = na
var float lastLow = na
var int lastLowBar = na
var bool legUp = true
float ph = ta.pivothigh(high, pivotLen, pivotLen)
float pl = ta.pivotlow(low, pivotLen, pivotLen)
bool newHigh = not na(ph)
bool newLow = not na(pl)
if newHigh
lastHigh := ph
lastHighBar := bar_index - pivotLen
legUp := true
if newLow
lastLow := pl
lastLowBar := bar_index - pivotLen
legUp := false
fibLevel(float startPrice, float endPrice, float ratio) =>
endPrice - (endPrice - startPrice) * ratio
if (newHigh or newLow) and not na(lastHigh) and not na(lastLow)
for ln in fibLines
line.delete(ln)
for lb in fibLabels
label.delete(lb)
array.clear(fibLines)
array.clear(fibLabels)
float startPrice = legUp ? lastLow : lastHigh
float endPrice = legUp ? lastHigh : lastLow
int startBar = legUp ? lastLowBar : lastHighBar
for r in ratios
float lvl = fibLevel(startPrice, endPrice, r)
color c = r == 0.618 ? color.orange : color.gray
array.push(fibLines, line.new(startBar, lvl, bar_index, lvl, color = c, extend = extendRight ? extend.right : extend.none))
array.push(fibLabels, label.new(bar_index, lvl, str.tostring(r) + " " + str.tostring(lvl, format.mintick), style = label.style_none, textcolor = c))A few things in this script are worth slowing down for.
The pivot bar is bar_index - pivotLen, not the current bar. By the time ta.pivothigh returns a value, the pivot itself is pivotLen bars in the past, so the start anchor must be placed there or the lines begin in the wrong spot. Placing it on the current bar is the most common mistake in hand-written versions.
The var declarations make the anchors persist across bars. Without them, the last high and low would reset to na on every bar and the redraw condition would almost never be true. If the distinction between var and per-bar variables is hazy, var, varip and persistent state explains how each behaves.
The direction flag matters because a retracement is relative to the most recent leg. If the last confirmed pivot is a high, the leg ran up from the previous low, so level 0 sits at the high and level 1 at the low. If the last confirmed pivot is a low, the leg ran down and the anchors swap. The ternaries pick the right ends, and fibLevel does the rest. In the rare case where a high and a low confirm on the same bar, the script treats the low as the latest, which is an acceptable simplification but worth knowing.
Finally, because the old lines are deleted before the new ones are drawn, only one set exists at a time. That is a deliberate choice, and it leads straight to the next topic.
Drawing limits and cleaning up old levels
Pine Script caps how many lines and labels a script can keep. The default is 50 of each, and max_lines_count and max_labels_count raise the cap to 500. When the cap is hit, the oldest drawing is silently removed to make room. If you draw seven levels each time a pivot confirms and never delete anything, a busy chart will push the earliest levels out within a handful of pivots, and you will see Fibonacci levels vanish for no visible reason.
There are three sensible policies. Delete everything and keep one live set, which is what the script above does. Keep the last few sets by deleting only when the arrays grow past a threshold. Or keep every set and accept that old ones will be evicted. For a chart you actually read, one live set is usually the clearest, because stacked sets from older swings clutter the area where you are looking. The broader pattern of tracking and deleting drawings is covered in drawing objects that do not hit the limit, and the limit itself is explained in the max drawings limit.
If you want to keep history, one approach is to leave the previous set in place but stop extending it. Instead of deleting, set the previous lines to extend.none and fade their color, then delete only the sets older than the last two or three. That takes a nested structure, such as an array of arrays or a user-defined type holding the lines for one swing, and it is where hand-writing starts to get tedious.
A rolling Fibonacci range for plots and alerts
Drawing objects are good for reading a chart, but conditions need series values. A line drawn with line.new is not something you can feed into ta.crossover. For that you want levels as plain series, and a rolling range gives you exactly that.
//@version=6
indicator("Rolling Fib Range", overlay = true)
lookback = input.int(100, "Lookback bars", minval = 10)
fibLevel(float startPrice, float endPrice, float ratio) =>
endPrice - (endPrice - startPrice) * ratio
float rangeHigh = ta.highest(high, lookback)
float rangeLow = ta.lowest(low, lookback)
float lvl382 = fibLevel(rangeLow, rangeHigh, 0.382)
float lvl500 = fibLevel(rangeLow, rangeHigh, 0.5)
float lvl618 = fibLevel(rangeLow, rangeHigh, 0.618)
plot(rangeHigh, "Range high", color = color.gray)
plot(lvl382, "0.382", color = color.new(color.teal, 30))
plot(lvl500, "0.500", color = color.new(color.blue, 30))
plot(lvl618, "0.618", color = color.new(color.orange, 30))
plot(rangeLow, "Range low", color = color.gray)
bool touched618 = ta.crossunder(close, lvl618) or ta.crossover(close, lvl618)
plotshape(touched618, "Cross of 0.618", shape.circle, location.belowbar, color.orange, size = size.tiny)
alertcondition(touched618, "Cross of 0.618", "Close crossed the 0.618 level of the rolling range")Here the anchors are simply the extremes of the window, so the leg is treated as running from the low up to the high and the levels measure retracement back down from the high. The three plots and the two range lines update on every bar, so a crossover test against them is straightforward.
Two behaviours to keep in mind. First, the levels move. A close that crosses the 0.618 line may be crossing a level that was somewhere else a few bars earlier, because a new high or a dropped low changed the range. Second, the ta.highest and ta.lowest calls look at the current bar, so on a live bar the values can change until the bar closes. Alerts that fire on a developing bar can behave differently from what you saw on history, a problem explained in why alerts fire on the wrong bar and handled with the techniques in the Pine Script alerts guide. Choosing alert frequency of once per bar close avoids most of it.
Choosing and customizing your ratios
The ratio list is the cheapest thing to customize, and it is where most personal preference lives. Some traders only use 0.382, 0.5, and 0.618. Others add 0.236 and 0.786, and some add extensions at 1.272 and 1.618 beyond the end anchor. In the pivot script, changing the ratios array is enough. Extensions need no new code because a ratio above 1 or below 0 simply produces a price outside the swing, and the same function computes it.
You can go further and make the ratios inputs, so you can edit them from the settings panel without touching code. Inputs are covered in every input type. A string input holding a comma-separated list and str.split is a compact way to do it, though each ratio then needs str.tonumber and a check for invalid text.
Colour is the other common tweak. A single highlighted ratio, as in the script above, makes the level you care about easy to find. A gradient from the first to the last level is another option, and colour gradients in Pine Script shows how to build one.
Mistakes that make Fibonacci scripts misleading
A handful of problems cause most of the confusion.
Placing the start anchor on the confirmation bar instead of the pivot bar, as covered above, shifts every line sideways. Using the wrong direction, so level 0 sits at the start of the leg, mirrors the whole drawing. Forgetting max_lines_count and max_labels_count, and losing old drawings without warning. And not accounting for the pivot delay: the levels from a pivot script do not exist until the pivot confirms, so if you test a rule against them on history you must remember that a human drawing the same swing would have known about it sooner. A script that treats a confirmed pivot as if it were known at the time of the actual high will look better on history than it could ever have been in real time.
That last point is a form of lookahead, and it is the reason to verify drawn levels on a replay of the chart rather than only on the final picture. Stepping through bars one at a time shows exactly when each level first appeared.
Customising the levels without writing every line
The scripts above are a starting point, and the changes people ask for next are where the effort goes: keep the last three swings faded instead of deleting them, add extensions, draw a shaded zone between 0.5 and 0.618, switch the anchors from pivots to the highest high since a session start, or fire a different alert for each level. Each of those touches the drawing code, the arrays, or the conditions, and each is easy to break with a one-character slip.
This is the kind of change PineScripter is built for. You describe the change in plain English, the AI writes Pine Script v6, checks it for compile errors the same way TradingView does and fixes what it finds, and edits only the lines that change instead of regenerating the script. The Chart runs the script on real market data inside PineScripter, so you can see what the levels draw before you paste the result into TradingView, and Replay steps through the run one bar at a time to show when each set of levels first appeared. You own the code and can read every line of it. For how to phrase a request that comes back right, see how to describe a complex indicator so the AI gets it right.
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
Can Pine Script draw Fibonacci retracements automatically?
Yes. Pine Script has no built-in Fibonacci drawing, but you can compute each level with a short formula and draw it with line.new and label.new. Anchor the levels to confirmed pivots from ta.pivothigh and ta.pivotlow, or to a rolling ta.highest and ta.lowest range.
Why do my auto Fibonacci levels start in the wrong place?
ta.pivothigh and ta.pivotlow confirm a pivot only after the right-side bars have formed, so the pivot sits pivotLen bars before the bar where the value is returned. Use bar_index minus pivotLen as the anchor bar, not the current bar.
Do Fibonacci levels in Pine Script repaint?
Levels anchored to confirmed pivots do not move once drawn, though a new set appears when the next pivot confirms. Levels from a rolling highest and lowest range shift whenever the range changes, so they can look different on a live bar than they did on history.
How many Fibonacci lines can one script draw?
A script keeps up to 50 lines and 50 labels by default. The max_lines_count and max_labels_count arguments of indicator() raise that to 500. Past the limit, the oldest drawings are removed without warning.
How do I add Fibonacci extension levels?
Add ratios above 1, such as 1.272 and 1.618, to the ratios array. The same level formula returns prices beyond the end anchor, so no other code has to change.
Describe your indicator in plain English and get Pine Script that compiles →
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.