Indicator · Pine Script v6 · On the chart

Swing Trade Analyzer - S&R Levels

by balacloud· code credited to SwingTradeAnalyzer

Swing Trade Analyzer - S&R Levels identifies key support and resistance levels directly on the price chart using pivot high and low points.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code298
Settings16inputs
LicenceNone statedfile: MPL-2.0
Last update5 weeks ago21 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

298 lines of Pine Script v6 from docs/pine_scripts/SwingTradeAnalyzer_SR.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

SwingTradeAnalyzer_SR.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SwingTradeAnalyzer

//@version=6
indicator("Swing Trade Analyzer - S&R Levels", shorttitle="STA S&R", overlay=true, max_lines_count=500, max_labels_count=500)

// ============================================
// INPUTS
// ============================================
grp_pivot = "Pivot Detection"
pivotLeft = input.int(5, "Pivot Left Bars", minval=1, maxval=20, group=grp_pivot)
pivotRight = input.int(5, "Pivot Right Bars", minval=1, maxval=20, group=grp_pivot)
maxLevels = input.int(5, "Max Levels Each Side", minval=1, maxval=10, group=grp_pivot)

grp_display = "Display Settings"
showSupport = input.bool(true, "Show Support Lines", group=grp_display)
showResistance = input.bool(true, "Show Resistance Lines", group=grp_display)
showLabels = input.bool(true, "Show Price Labels", group=grp_display)
extendLines = input.bool(true, "Extend Lines Right", group=grp_display)

grp_colors = "Colors"
supportColor = input.color(color.new(color.green, 30), "Support Color", group=grp_colors)
resistanceColor = input.color(color.new(color.red, 30), "Resistance Color", group=grp_colors)
mtfSupportColor = input.color(color.new(color.lime, 0), "MTF Support (Strong)", group=grp_colors)
mtfResistanceColor = input.color(color.new(color.fuchsia, 0), "MTF Resistance (Strong)", group=grp_colors)

grp_mtf = "Multi-Timeframe Confluence"
useMTF = input.bool(true, "Enable MTF Confluence", group=grp_mtf)
mtfTimeframe = input.timeframe("W", "Higher Timeframe", group=grp_mtf)
confluenceThreshold = input.float(1.5, "Confluence Threshold %", minval=0.5, maxval=5.0, step=0.5, group=grp_mtf)

grp_fib = "Fibonacci Extensions (ATH)"
useFibonacci = input.bool(true, "Use Fibonacci for ATH", group=grp_fib)
athThreshold = input.float(5.0, "ATH Threshold %", minval=1.0, maxval=10.0, group=grp_fib)

// ============================================
// PIVOT DETECTION
// ============================================
pivotHigh = ta.pivothigh(high, pivotLeft, pivotRight)
pivotLow = ta.pivotlow(low, pivotLeft, pivotRight)

// Store pivot levels in arrays
var float[] supportLevels = array.new_float(0)
var float[] resistanceLevels = array.new_float(0)
var int[] supportBars = array.new_int(0)
var int[] resistanceBars = array.new_int(0)

// Add new pivot low (support)
if not na(pivotLow)
    // Check if level is unique (not within 1% of existing)
    isUnique = true
    if array.size(supportLevels) > 0
        for i = 0 to array.size(supportLevels) - 1
            existingLevel = array.get(supportLevels, i)
            if math.abs(pivotLow - existingLevel) / existingLevel < 0.01
                isUnique := false
                break

    if isUnique
        array.push(supportLevels, pivotLow)
        array.push(supportBars, bar_index - pivotRight)

// Add new pivot high (resistance)
if not na(pivotHigh)
    isUnique = true
    if array.size(resistanceLevels) > 0
        for i = 0 to array.size(resistanceLevels) - 1
            existingLevel = array.get(resistanceLevels, i)
            if math.abs(pivotHigh - existingLevel) / existingLevel < 0.01
                isUnique := false
                break

    if isUnique
        array.push(resistanceLevels, pivotHigh)
        array.push(resistanceBars, bar_index - pivotRight)

// ============================================
// MULTI-TIMEFRAME S&R (WEEKLY)
// ============================================
[weeklyHigh, weeklyLow, weeklyClose] = request.security(syminfo.tickerid, mtfTimeframe, [high, low, close])

weeklyPivotHigh = ta.pivothigh(weeklyHigh, 2, 2)
weeklyPivotLow = ta.pivotlow(weeklyLow, 2, 2)

var float[] weeklySupportLevels = array.new_float(0)
var float[] weeklyResistanceLevels = array.new_float(0)

if not na(weeklyPivotLow) and useMTF
    isUnique = true
    if array.size(weeklySupportLevels) > 0
        for i = 0 to array.size(weeklySupportLevels) - 1
            existingLevel = array.get(weeklySupportLevels, i)
            if math.abs(weeklyPivotLow - existingLevel) / existingLevel < 0.02
                isUnique := false
                break
    if isUnique
        array.push(weeklySupportLevels, weeklyPivotLow)

if not na(weeklyPivotHigh) and useMTF
    isUnique = true
    if array.size(weeklyResistanceLevels) > 0
        for i = 0 to array.size(weeklyResistanceLevels) - 1
            existingLevel = array.get(weeklyResistanceLevels, i)
            if math.abs(weeklyPivotHigh - existingLevel) / existingLevel < 0.02
                isUnique := false
                break
    if isUnique
        array.push(weeklyResistanceLevels, weeklyPivotHigh)

// ============================================
// CHECK MTF CONFLUENCE
// ============================================
isConfluent(float level, bool isSupport) =>
    result = false
    if useMTF
        checkArray = isSupport ? weeklySupportLevels : weeklyResistanceLevels
        if array.size(checkArray) > 0
            for i = 0 to array.size(checkArray) - 1
                weeklyLevel = array.get(checkArray, i)
                if math.abs(level - weeklyLevel) / level * 100 < confluenceThreshold
                    result := true
                    break
    result

// ============================================
// FIBONACCI EXTENSIONS FOR ATH
// ============================================
high52Week = ta.highest(high, 252)
low52Week = ta.lowest(low, 252)
isNearATH = (high52Week - close) / high52Week * 100 < athThreshold

// Find recent swing low for Fibonacci
recentSwingLow = ta.lowest(low, 60)

// Calculate Fibonacci extensions
fib127 = high52Week + (high52Week - recentSwingLow) * 0.272
fib161 = high52Week + (high52Week - recentSwingLow) * 0.618
fib200 = high52Week + (high52Week - recentSwingLow) * 1.0

// ============================================
// DRAW SUPPORT & RESISTANCE LINES
// ============================================
// Clean up old lines on each bar
var line[] supportLines = array.new_line(0)
var line[] resistanceLines = array.new_line(0)
var label[] supportLabels = array.new_label(0)
var label[] resistanceLabels = array.new_label(0)

// Delete all existing lines and labels
if barstate.islast
    // Clear old drawings (check size > 0 before looping)
    if array.size(supportLines) > 0
        for i = 0 to array.size(supportLines) - 1
            line.delete(array.get(supportLines, i))
    if array.size(resistanceLines) > 0
        for i = 0 to array.size(resistanceLines) - 1
            line.delete(array.get(resistanceLines, i))
    if array.size(supportLabels) > 0
        for i = 0 to array.size(supportLabels) - 1
            label.delete(array.get(supportLabels, i))
    if array.size(resistanceLabels) > 0
        for i = 0 to array.size(resistanceLabels) - 1
            label.delete(array.get(resistanceLabels, i))

    array.clear(supportLines)
    array.clear(resistanceLines)
    array.clear(supportLabels)
    array.clear(resistanceLabels)

    // Get current price for filtering
    currentPrice = close

    // Draw Support Lines (below current price)
    drawnSupport = 0
    if showSupport and array.size(supportLevels) > 0
        // Sort by proximity to current price (descending - nearest first)
        for i = array.size(supportLevels) - 1 to 0
            if drawnSupport >= maxLevels
                break
            level = array.get(supportLevels, i)
            if level < currentPrice
                isMTF = isConfluent(level, true)
                lineColor = isMTF ? mtfSupportColor : supportColor
                lineWidth = isMTF ? 2 : 1
                lineStyle = isMTF ? line.style_solid : line.style_dashed

                startBar = array.size(supportBars) > i ? array.get(supportBars, i) : bar_index - 100
                endBar = extendLines ? bar_index + 20 : bar_index

                newLine = line.new(startBar, level, endBar, level,
                     color=lineColor, width=lineWidth, style=lineStyle,
                     extend=extendLines ? extend.right : extend.none)
                array.push(supportLines, newLine)

                if showLabels
                    labelText = isMTF ? "S " + str.tostring(level, "#.##") + " [MTF]" : "S " + str.tostring(level, "#.##")
                    newLabel = label.new(bar_index + 5, level, labelText,
                         color=color.new(lineColor, 80), textcolor=lineColor,
                         style=label.style_label_left, size=size.small)
                    array.push(supportLabels, newLabel)

                drawnSupport += 1

    // Draw Resistance Lines (above current price)
    drawnResistance = 0
    if showResistance and array.size(resistanceLevels) > 0
        for i = array.size(resistanceLevels) - 1 to 0
            if drawnResistance >= maxLevels
                break
            level = array.get(resistanceLevels, i)
            if level > currentPrice
                isMTF = isConfluent(level, false)
                lineColor = isMTF ? mtfResistanceColor : resistanceColor
                lineWidth = isMTF ? 2 : 1
                lineStyle = isMTF ? line.style_solid : line.style_dashed

                startBar = array.size(resistanceBars) > i ? array.get(resistanceBars, i) : bar_index - 100
                endBar = extendLines ? bar_index + 20 : bar_index

                newLine = line.new(startBar, level, endBar, level,
                     color=lineColor, width=lineWidth, style=lineStyle,
                     extend=extendLines ? extend.right : extend.none)
                array.push(resistanceLines, newLine)

                if showLabels
                    labelText = isMTF ? "R " + str.tostring(level, "#.##") + " [MTF]" : "R " + str.tostring(level, "#.##")
                    newLabel = label.new(bar_index + 5, level, labelText,
                         color=color.new(lineColor, 80), textcolor=lineColor,
                         style=label.style_label_left, size=size.small)
                    array.push(resistanceLabels, newLabel)

                drawnResistance += 1

    // Draw Fibonacci Extensions if near ATH
    if useFibonacci and isNearATH and drawnResistance < maxLevels
        // Only draw if no natural resistance above
        if drawnResistance == 0 or (drawnResistance > 0 and array.size(resistanceLines) > 0)
            // Fib 127.2%
            fibLine1 = line.new(bar_index - 50, fib127, bar_index + 20, fib127,
                 color=color.new(color.orange, 30), width=1, style=line.style_dotted,
                 extend=extendLines ? extend.right : extend.none)
            array.push(resistanceLines, fibLine1)
            if showLabels
                fibLabel1 = label.new(bar_index + 5, fib127, "Fib 127.2% " + str.tostring(fib127, "#.##"),
                     color=color.new(color.orange, 80), textcolor=color.orange,
                     style=label.style_label_left, size=size.small)
                array.push(resistanceLabels, fibLabel1)

            // Fib 161.8%
            fibLine2 = line.new(bar_index - 50, fib161, bar_index + 20, fib161,
                 color=color.new(color.orange, 30), width=1, style=line.style_dotted,
                 extend=extendLines ? extend.right : extend.none)
            array.push(resistanceLines, fibLine2)
            if showLabels
                fibLabel2 = label.new(bar_index + 5, fib161, "Fib 161.8% " + str.tostring(fib161, "#.##"),
                     color=color.new(color.orange, 80), textcolor=color.orange,
                     style=label.style_label_left, size=size.small)
                array.push(resistanceLabels, fibLabel2)

// ============================================
// INFO TABLE
// ============================================
var table infoTable = table.new(position.top_right, 2, 6, bgcolor=color.new(color.black, 80), border_width=1)

if barstate.islast
    // Count confluent levels
    mtfSupportCount = 0
    mtfResistanceCount = 0

    if array.size(supportLevels) > 0
        for i = 0 to array.size(supportLevels) - 1
            if isConfluent(array.get(supportLevels, i), true)
                mtfSupportCount += 1

    if array.size(resistanceLevels) > 0
        for i = 0 to array.size(resistanceLevels) - 1
            if isConfluent(array.get(resistanceLevels, i), false)
                mtfResistanceCount += 1

    table.cell(infoTable, 0, 0, "STA S&R", text_color=color.white, text_size=size.small)
    table.cell(infoTable, 1, 0, "v1.0", text_color=color.gray, text_size=size.small)

    table.cell(infoTable, 0, 1, "Support Levels", text_color=supportColor, text_size=size.tiny)
    table.cell(infoTable, 1, 1, str.tostring(array.size(supportLevels)), text_color=color.white, text_size=size.tiny)

    table.cell(infoTable, 0, 2, "Resistance Levels", text_color=resistanceColor, text_size=size.tiny)
    table.cell(infoTable, 1, 2, str.tostring(array.size(resistanceLevels)), text_color=color.white, text_size=size.tiny)

    table.cell(infoTable, 0, 3, "MTF Confluent (S)", text_color=mtfSupportColor, text_size=size.tiny)
    table.cell(infoTable, 1, 3, str.tostring(mtfSupportCount), text_color=color.white, text_size=size.tiny)

    table.cell(infoTable, 0, 4, "MTF Confluent (R)", text_color=mtfResistanceColor, text_size=size.tiny)
    table.cell(infoTable, 1, 4, str.tostring(mtfResistanceCount), text_color=color.white, text_size=size.tiny)

    athStatus = isNearATH ? "YES" : "NO"
    athColor = isNearATH ? color.yellow : color.gray
    table.cell(infoTable, 0, 5, "Near ATH", text_color=athColor, text_size=size.tiny)
    table.cell(infoTable, 1, 5, athStatus, text_color=athColor, text_size=size.tiny)

Overview

Swing Trade Analyzer - S&R Levels filters duplicate price levels and offers optional multi-timeframe confluence analysis against higher timeframes like weekly data to highlight strong zones. Additionally, it supports Fibonacci extensions near all-time highs. Users can adjust pivot lookback settings, line styling, price labels, and confluence percentage thresholds.

Details

Published by

balacloud on GitHub

Code credit

SwingTradeAnalyzer, as written in the script's header

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Support & resistance, Trend

Markets

Stocks

Timeframes

H4 and above, M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Pivot Left Barsint5pivotLeft
Pivot Right Barsint5pivotRight
Max Levels Each Sideint5maxLevels
Show Support LinesbooltrueshowSupport
Show Resistance LinesbooltrueshowResistance
Show Price LabelsbooltrueshowLabels
Extend Lines RightbooltrueextendLines
Support Colorcolorcolor.new(color.green, 30)supportColor
Resistance Colorcolorcolor.new(color.red, 30)resistanceColor
MTF Support (Strong)colorcolor.new(color.lime, 0)mtfSupportColor
MTF Resistance (Strong)colorcolor.new(color.fuchsia, 0)mtfResistanceColor
Enable MTF ConfluencebooltrueuseMTF
Show all 16 settings
SettingTypeDefaultVariable
Higher TimeframetimeframeWmtfTimeframe
Confluence Threshold %float1.5confluenceThreshold
Use Fibonacci for ATHbooltrueuseFibonacci
ATH Threshold %float5.0athThreshold
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener

Function - Linear Regression

by ricardosantos79
261 stars

This indicator fits a linear regression through stored pivot highs and lows and draws the resulting channel on the price chart. A function returns predicted values, maximum and minimum deviations, and the average absolute deviation. Confirmed two-bar pivots up

Indicator v5 TrendSupport & resistance
Updated 4 years ago · None stated GitHub repository of Function - Linear Regression

AI Trend

by dearvn
257 stars

AI Trend is an indicator that plots pivot points, trend lines, and support and resistance levels directly on the price chart. It marks high and low pivots based on user-defined length, draws trend lines that check for violations at specified points, and identi

Indicator v5 TrendSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of AI Trend

Ichimoku Cloud

by harryguiacorn
219 stars

This indicator plots Ichimoku Cloud elements on the price chart, including Tenkan-sen, Kijun-sen, Senkou Span A and B lines with optional Chikou Span. It signals trend changes via Tenkan-sen and Kijun-sen crosses and places arrows at Kijun-sen direction shifts

Indicator v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ichimoku Cloud
219 stars

This indicator identifies local swing highs and swing lows to construct a Zig Zag pattern on the main price chart. It evaluates pivot points based on a customizable number of surrounding left and right bars. Using persistent variables, the script tracks previo

Indicator v4 Support & resistanceTrend Repaints
Updated 5 years ago · None stated GitHub repository of Teaching: Finding Highs and Lows 6

Dynamic Linear Regression

by TradersPost
218 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 3 months ago · None stated GitHub repository of Dynamic Linear Regression

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers