Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-fibonacci-retracements

$ Pine Script Fibonacci Retracements

Master this powerful technical analysis tool in TradingView's Pine Script that identifies key potential support and resistance levels during price pullbacks within a trend, based on mathematical ratios.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

What are Fibonacci Retracements?

Fibonacci Retracements are horizontal lines used in technical analysis that indicate potential support and resistance levels. They are derived from the Fibonacci sequence (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...) where each number is the sum of the two preceding ones. The key ratios used in retracements are obtained by dividing a number in the sequence by the number that follows it (e.g., 34/55 ≈ 0.618 or 61.8%), or by two numbers after it (e.g., 34/89 ≈ 0.382 or 38.2%).

These levels are drawn by taking two extreme points (a swing high and a swing low) on a chart and then drawing horizontal lines at the classic Fibonacci ratios: 23.6%, 38.2%, 50% (not a Fibonacci ratio, but commonly included), 61.8%, and 78.6% (sometimes 76.4%). The idea is that after a significant price move (impulse wave), price will often retrace a portion of that move to one of these Fibonacci levels before continuing in its original direction.

Fibonacci Retracements are primarily used to:

  • Identify potential entry points: During a pullback, price might find support/resistance at a Fibonacci level, offering an entry opportunity for trend continuation.
  • Set profit targets: Traders might use these levels as areas to take partial or full profits on existing positions.
  • Place stop-loss orders: A stop-loss could be placed just beyond a critical Fibonacci level.
  • Confirm trend strength: A strong bounce from a key Fibonacci level (e.g., 50% or 61.8%) can confirm the underlying trend.
02

Components and Calculation

To calculate Fibonacci Retracement levels, you first need to identify a significant price swing, which means a distinct high and a distinct low. Once these are defined, the levels are calculated as follows:


For an Uptrend (Price retracing downwards from a high):
Retracement Level = High_Price - (High_Price - Low_Price) * Fibonacci_Ratio

For a Downtrend (Price retracing upwards from a low):
Retracement Level = Low_Price + (High_Price - Low_Price) * Fibonacci_Ratio

Common Fibonacci Ratios:
0.236 (23.6%)
0.382 (38.2%)
0.500 (50%) - Often called the "mid-point" or "half-back"
0.618 (61.8%) - Known as the "Golden Ratio"
0.786 (78.6%) - Square root of 0.618, also commonly used.

To implement this dynamically in Pine Script, we often use `ta.highest()` and `ta.lowest()` to find a significant swing within a specified lookback period.

03

Basic Fibonacci Retracements Implementation in Pine Script

pine-script@terminal
//@version=5
indicator("My Fibonacci Retracements", overlay=true, max_bars_back=500)

lookbackPeriod = input.int(50, title="Lookback Period for Swing", minval=10, maxval=500)
showLevels = input.bool(true, title="Show Fibonacci Levels")
showLabels = input.bool(true, title="Show Level Labels")

fib0 = 0.0
fib236 = 0.236
fib382 = 0.382
fib500 = 0.500
fib618 = 0.618
fib786 = 0.786
fib100 = 1.0

hh = ta.highest(high, lookbackPeriod)
ll = ta.lowest(low, lookbackPeriod)
hh_idx = ta.highestbars(high, lookbackPeriod)
ll_idx = ta.lowestbars(low, lookbackPeriod)

leftBars = 5
rightBars = 5

pivotHigh = ta.pivothigh(high, leftBars, rightBars)
pivotLow = ta.pivotlow(low, leftBars, rightBars)

var float currentSwingHigh = na
var float currentSwingLow = na
var int currentSwingHighIdx = na
var int currentSwingLowIdx = na

if not na(pivotHigh)
    currentSwingHigh := pivotHigh
    currentSwingHighIdx := bar_index[rightBars]
if not na(pivotLow)
    currentSwingLow := pivotLow
    currentSwingLowIdx := bar_index[rightBars]

if not na(currentSwingHigh) and not na(currentSwingLow)
    float range = math.abs(currentSwingHigh - currentSwingLow)
    if range > 0
        float fib236_level = na
        float fib382_level = na
        float fib500_level = na
        float fib618_level = na
        float fib786_level = na

        isUptrendSwing = currentSwingHighIdx > currentSwingLowIdx
        isDowntrendSwing = currentSwingLowIdx > currentSwingHighIdx

        if isUptrendSwing
            fib236_level := currentSwingHigh - (range * fib236)
            fib382_level := currentSwingHigh - (range * fib382)
            fib500_level := currentSwingHigh - (range * fib500)
            fib618_level := currentSwingHigh - (range * fib618)
            fib786_level := currentSwingHigh - (range * fib786)
        else if isDowntrendSwing
            fib236_level := currentSwingLow + (range * fib236)
            fib382_level := currentSwingLow + (range * fib382)
            fib500_level := currentSwingLow + (range * fib500)
            fib618_level := currentSwingLow + (range * fib618)
            fib786_level := currentSwingLow + (range * fib786)

        if showLevels
            plot(fib236_level, title="23.6%", color=color.new(color.blue, 0), style=plot.style_stepline, linewidth=1)
            plot(fib382_level, title="38.2%", color=color.new(color.green, 0), style=plot.style_stepline, linewidth=1)
            plot(fib500_level, title="50.0%", color=color.new(color.purple, 0), style=plot.style_stepline, linewidth=1)
            plot(fib618_level, title="61.8%", color=color.new(color.orange, 0), style=plot.style_stepline, linewidth=1)
            plot(fib786_level, title="78.6%", color=color.new(color.red, 0), style=plot.style_stepline, linewidth=1)
            plot(currentSwingHigh, title="0% / Swing High", color=color.gray, style=plot.style_stepline, linewidth=1)
            plot(currentSwingLow, title="100% / Swing Low", color=color.gray, style=plot.style_stepline, linewidth=1)
$ ✓ Compiled successfully
04

The Golden Ratio

The Golden Ratio

The 61.8% (and its inverse 38.2%) Fibonacci ratio is often considered the most significant for reversals. Price frequently finds strong support/resistance at or around this level.

05

Fibonacci Retracements Trading Strategies

Strategy Example: Bounce from 61.8% Retracement

This strategy demonstrates buying on a bounce from the 61.8% Fibonacci level in an uptrend, and selling on a bounce from the 61.8% level in a downtrend.

//@version=5
strategy("Fibonacci Retracement Strategy", overlay=true)

if not na(currentSwingHigh) and not na(currentSwingLow)
    isCurrentlyUptrendSwing = currentSwingHighIdx > currentSwingLowIdx
    float fib618BuyLevel = na
    float fib382ProfitTarget = na

    if isCurrentlyUptrendSwing
        range = math.abs(currentSwingHigh - currentSwingLow)
        if range > 0
            fib618BuyLevel := currentSwingHigh - (range * fib618)
            fib382ProfitTarget := currentSwingHigh - (range * fib382)

            longCondition = close > fib618BuyLevel and close[1] <= fib618BuyLevel[1] and close > currentSwingLow
            stopLossLevel = currentSwingHigh - (range * fib786)
            
            if (longCondition)
                strategy.entry("Long Fib 61.8", strategy.long)
            
            if not na(fib382ProfitTarget) and not na(stopLossLevel)
                strategy.exit("Long Fib 61.8 Exit", from_entry="Long Fib 61.8", profit=fib382ProfitTarget, stop=stopLossLevel)

    isCurrentlyDowntrendSwing = currentSwingLowIdx > currentSwingHighIdx
    float fib618SellLevel = na
    float fib382ProfitTargetSell = na

    if isCurrentlyDowntrendSwing
        range = math.abs(currentSwingHigh - currentSwingLow)
        if range > 0
            fib618SellLevel := currentSwingLow + (range * fib618)
            fib382ProfitTargetSell := currentSwingLow + (range * fib382)

            shortCondition = close < fib618SellLevel and close[1] >= fib618SellLevel[1] and close < currentSwingHigh
            stopLossLevelSell = currentSwingLow + (range * fib786)

            if (shortCondition)
                strategy.entry("Short Fib 61.8", strategy.short)

            if not na(fib382ProfitTargetSell) and not na(stopLossLevelSell)
                strategy.exit("Short Fib 61.8 Exit", from_entry="Short Fib 61.8", profit=fib382ProfitTargetSell, stop=stopLossLevelSell)
06

Optimizing Fibonacci Retracements Performance

To get the most from Fibonacci Retracements in Pine Script:

  • Accurate Swing Point Selection: The most crucial aspect is correctly identifying the significant swing high and swing low using robust pivot detection.
  • Confluence is Key: Fibonacci levels become much more powerful when they align with previous significant highs/lows, moving averages, trendlines, psychological whole numbers, or pivot points.
  • Volume Confirmation: Look for volume to confirm bounces or breaks of Fibonacci levels.
  • Candlestick Patterns: Confirm reactions at Fibonacci levels with bullish or bearish candlestick patterns for higher probability trades.
  • Trend Context: Use Fibonacci retracements primarily for trend continuation strategies.
  • Multiple Timeframes: Fibonacci levels on higher timeframes can provide stronger support/resistance than those on lower timeframes.
07

Important Note

Important Note

Fibonacci levels are potential zones, not guaranteed levels. Price can overshoot, undershoot, or ignore them completely.

08

Common Fibonacci Retracements Pitfalls

  • Subjectivity in Swing Point Selection: Manually selecting swing highs and lows can be subjective and lead to different interpretations.
  • Self-Fulfilling Prophecy: Because many traders use Fibonacci levels, they can become self-fulfilling prophecies.
  • Not Guaranteed Support/Resistance: Fibonacci levels are potential zones, not guaranteed levels.
  • Whipsaws in Choppy Markets: In ranging or consolidating markets, price might move across multiple levels without clear reaction.
  • Over-Reliance: Relying solely on Fibonacci retracements without additional confirmation can lead to poor trading decisions.
  • Too Many Levels: Plotting too many levels can clutter the chart and lead to analysis paralysis.
09

Conclusion

Conclusion

Fibonacci Retracements are a deeply ingrained and widely used technical analysis tool available in Pine Script for TradingView. By providing mathematically derived potential support and resistance levels during price pullbacks, they offer traders a valuable framework for anticipating market reactions, identifying entry/exit points, and managing risk within a trending market. While requiring careful selection of swing points and confirmation from other indicators like candlestick patterns and volume, mastering Fibonacci Retracements can significantly enhance your pine script strategies. By understanding their calculation, thoughtfully applying them to clear price swings, and integrating them strategically into your overall trading plan, you can leverage these powerful levels to improve your decision-making and better capitalize on market opportunities.

Enhance Your Trading

Get a high-performance Pine Script analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pine Script Strategy