Indicator TutorialPine Script v6

How to Create Fibonacci Retracements on TradingView

Choose anchor order and account for when the pivot becomes known.

Retracement ratios describe a position inside a chosen price move. They do not prove that price will pause or reverse there. This example stores confirmed pivot highs and lows, uses their chronological order to select rising or falling arithmetic, and displays new levels only from the confirmation bar.

What is a Fibonacci retracement?

Retracement levels are measured from the end of a move back toward its start. Common displayed ratios include 23.6%, 38.2%, 50%, 61.8% and 78.6%; 50% is a midpoint convention, not a Fibonacci sequence ratio.

TradingView’s Fib Retracement drawing tool lets you choose anchors, reverse the levels and change the calculation to log scale. This Pine example uses linear arithmetic only. Match anchor prices, direction, level labels and scale before comparing them.

Why Traders Use This Indicator

  • Describe a pullback as a fraction of a specified anchor range.
  • Make anchor order and update timing explicit.
  • Compare a fixed hypothesis across several historical periods without presenting the levels as predictive proof.
ParameterDefaultDescription
Pivot left/right bars5 / 5A candidate requires neighboring bars on both sides. With right=5, it becomes available five bars later, at that confirmation bar’s close.
Anchor pairLatest confirmed high and lowChronological order determines up/down arithmetic. This is not a Zig Zag or a complete trend model; repeated same-type pivots replace that endpoint.
Ratios23.6%, 38.2%, 50%, 61.8%, 78.6%Each display toggle changes its plot, not the alert calculation.
Proximity tolerance2% of anchor rangeA hypothetical distance around 61.8%, not 2% of price and not a trade signal.

Direction, arithmetic and information timing

For high H and low L with H > L, range R = H − L. After a low-to-high move, retracement at ratio r is H − rR. After a high-to-low move, it is L + rR. The 0% level is the latest endpoint and 100% returns to the starting endpoint.

In a hypothetical 100 → 120 move, 61.8% is 120 − 0.618 × 20 = 107.64. For 120 → 100 it is 100 + 0.618 × 20 = 112.36. With a 2% range tolerance, the distance is 0.4 price units. These are constructed arithmetic examples, not observed reactions.

The script updates anchors only on a confirmed chart bar. A high at bar 20 with right=5 can be accepted at the close of bar 25; its levels do not exist at bar 20. If both pivot types confirm together, the script keeps its previous pair. Equal or inverted high/low prices produce no valid pair.

A new pivot of the same type replaces that endpoint; this simple latest-pair rule does not enforce alternating swings or select the most economically meaningful move. Levels can jump when anchors change. TradingView explains how plotting pivots back in history can conceal their detection delay.

Signal Interpretation

Each level is a geometric reference, not evidence of support, resistance, a “last chance” entry or a likely reversal. The proximity alert requires a confirmed close within the chosen distance of 61.8%. It is suppressed on an anchor-update bar so a moving level alone does not create that alert.

The condition may remain true on successive closes. It is not a first-touch detector, does not require a wick rejection, and executes no orders. Plot toggles do not disable alerts. Create the alert in TradingView and recreate it after changing inputs or code.

Combining with Other Indicators

If combining the levels with a moving average, volume or another condition, define that rule separately and compare it with an unfiltered baseline. Extra conditions do not demonstrate greater accuracy. A strategy study also needs entries, exits, costs, position size and evaluation dates fixed before tuning.

Writing Pine Script Manually

Challenges of Manual Coding

Track pivot indices as well as prices so falling and rising legs use different formulas.

Wait for the confirmation bar to close, and show levels from that time rather than backdating them.

Specify simultaneous pivots, repeated same-type pivots and invalid pairs.

Separate proximity alerts from drawing toggles and first-touch events.

Pine Script v6
//@version=6
indicator("Confirmed pivot Fibonacci retracements", shorttitle="Pivot Fib", overlay=true)
leftBars = input.int(5, "Pivot left bars", minval=1, maxval=100)
rightBars = input.int(5, "Pivot right bars", minval=1, maxval=100)
show236 = input.bool(true, "Show 23.6%")
show382 = input.bool(true, "Show 38.2%")
show500 = input.bool(true, "Show 50%")
show618 = input.bool(true, "Show 61.8%")
show786 = input.bool(true, "Show 78.6%")
tolerance = input.float(2.0, "61.8% proximity (% of anchor range)", minval=0, maxval=100)
ph = ta.pivothigh(high, leftBars, rightBars)
pl = ta.pivotlow(low, leftBars, rightBars)
var float swingHigh = na
var float swingLow = na
var int highBar = na
var int lowBar = na
// Ambiguous bars confirming both pivot types leave the existing anchors unchanged.
singleHigh = not na(ph) and na(pl)
singleLow = not na(pl) and na(ph)
anchorChanged = barstate.isconfirmed and (singleHigh or singleLow)
if barstate.isconfirmed
    if singleHigh
        swingHigh := ph
        highBar := bar_index - rightBars
    if singleLow
        swingLow := pl
        lowBar := bar_index - rightBars
validPair = not na(highBar) and not na(lowBar) and highBar != lowBar and swingHigh > swingLow
upLeg = validPair and highBar > lowBar
span = validPair ? swingHigh - swingLow : na
level(float ratio) =>
    validPair ? (upLeg ? swingHigh - span * ratio : swingLow + span * ratio) : na
f236 = level(0.236)
f382 = level(0.382)
f500 = level(0.5)
f618 = level(0.618)
f786 = level(0.786)
// No offset or historical line extension: new levels begin at confirmation.
plot(show236 ? f236 : na, "23.6%", color.teal, style=plot.style_stepline)
plot(show382 ? f382 : na, "38.2%", color.blue, style=plot.style_stepline)
plot(show500 ? f500 : na, "50%", color.gray, style=plot.style_stepline)
plot(show618 ? f618 : na, "61.8%", color.orange, 2, style=plot.style_stepline)
plot(show786 ? f786 : na, "78.6%", color.red, style=plot.style_stepline)
plot(validPair ? swingHigh : na, "Anchor high", color.new(color.green, 65), style=plot.style_stepline)
plot(validPair ? swingLow : na, "Anchor low", color.new(color.red, 65), style=plot.style_stepline)
near618 = barstate.isconfirmed and validPair and not anchorChanged and math.abs(close - f618) <= span * tolerance / 100.0
alertcondition(near618, "Closed near 61.8%", "Close is within the configured anchor-range distance of 61.8% on {{ticker}}.")
var table info = table.new(position.top_right, 2, 4)
if barstate.islast
    table.cell(info, 0, 0, "Latest anchor order")
    table.cell(info, 1, 0, not validPair ? "Waiting for valid pair" : upLeg ? "Low then high" : "High then low")
    table.cell(info, 0, 1, "High / low")
    table.cell(info, 1, 1, validPair ? str.tostring(swingHigh, format.mintick) + " / " + str.tostring(swingLow, format.mintick) : "Unavailable")
    table.cell(info, 0, 2, "61.8%")
    table.cell(info, 1, 2, validPair ? str.tostring(f618, format.mintick) : "Unavailable")
    table.cell(info, 0, 3, "Confirmation delay")
    table.cell(info, 1, 3, str.tostring(rightBars) + " bars + closing update")

Maintenance Note: This is a linear-price, latest-pivot-pair illustration, not a Zig Zag or a strategy. New levels begin at confirmation, never at the old pivot bar. It makes no higher-timeframe requests. Changing inputs or available history, or revised market data, can change anchors. No returns are reported.

Build with Pineify Visual Editor

Pineify lets you configure supported indicators and export Pine Script. Available settings and plan requirements vary by indicator. Compare the generated rules with the example before using its signals.

FeatureManual Pine ScriptPineify Visual Editor
Existing visual moduleThe example uses confirmed pivots and chronological anchor order.Fibonacci Zone is a separate paid module using a rolling Length input; it is not this pivot algorithm.
Custom pivot rulesWrite confirmation, direction and ambiguous-pivot handling explicitly.Provide these requirements to the AI Coding Agent and inspect its generated source.
VerificationCompare a fixed pair of anchors with matching linear drawings.Review generated code and perform the same arithmetic and timing checks.

Use the existing Fibonacci Zone module when rolling-range zones fit the task.

Ask AI Coding Agent to draft custom pivot-based rules with explicit timing.

Inspect the source and compare it with known anchor examples before use.

Step-by-Step Tutorial

1

Choose rolling zones or custom pivots

Fibonacci Zone has a Length input and a different rolling-range calculation. Use AI Coding Agent for the exact pivot example here.

2

Specify the anchor rules

State left/right bars, closing confirmation, same-type replacement and simultaneous-pivot handling.

3

Review arithmetic and timing

Check rising and falling formulas, first availability of each pair and the proximity condition.

4

Compile and compare

Add the script to TradingView and compare a selected pair with the drawing tool using matching linear scale and labels.

Trading Strategies & Pro Tips

Anchor timing check

Choose a pivot and count the right-side bars before its level appears. Verify that no earlier bar is treated as having known the new level.

Direction and scale comparison

Use the same high and low in both chronological orders, then match a manual linear drawing. Do not compare against log-calculated levels.

Separate strategy experiment

If studying a pullback entry, define its confirmation, exit, sizing and costs first. Keep a later sample untouched. The indicator supplies references, not test results.

Common Mistakes to Avoid

  • Using H − rR for both rising and falling moves.
  • Drawing newly confirmed levels backward and treating them as previously known.
  • Calling a latest-pivot pair a complete Zig Zag or trend algorithm.
  • Confusing 2% of anchor range with 2% of market price.
  • Assuming hidden plots disable a running TradingView alert.

Frequently Asked Questions

No. It is a midpoint convention often displayed alongside Fibonacci-derived ratios.

The anchor prices or order may differ. Pivot confirmation is delayed, and this example uses linear prices only. Match anchors, direction, level labels and calculation scale before comparing.

With right=5, a pivot candidate is evaluated five chart bars later. This script waits until that confirmation bar closes and starts the new levels there, without a negative plot offset.

No. A ratio describes a location within an anchor range. Neither a nearby close nor a band of levels establishes a profitable entry or a reliable support level.

That requires an explicitly named convention. A two-point projection beyond the impulse endpoint differs from a three-point projection measured from a pullback anchor. This script implements retracements only.

No. The existing paid module uses a rolling Length input and its own ratios. For this latest-pivot-pair algorithm, request custom code from AI Coding Agent and review the result.

Specify Fibonacci anchors you can verify

  • Choose rolling-range zones or a custom pivot rule.
  • Review direction, confirmation delay and alert behavior.
  • Compare the generated source against explicit anchor examples.

Disclaimer: Trading involves significant risk. The indicators, code, and strategies provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.