Indicator · Pine Script v6 · On the chart

STA S&R v2

by balacloud· code credited to SwingTradeAnalyzer

This indicator plots support and resistance levels on the price chart based on pivot detection.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code310
Settings14inputs
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

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

SwingTradeAnalyzer_SR_v2.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
// v2.0 - Enhanced with swing trading rules:
//   - Lookback limit (recent levels only, default 18 months)
//   - Multiple rejection requirement (min 2 touches)
//   - Role reversal detection (support↔resistance)
//   - Avoid outlier extremes
//   - Multi-timeframe color coding

//@version=6
indicator("STA S&R v2.0", shorttitle="STA S&R v2", overlay=true, max_lines_count=100, max_labels_count=100)

// ============================================
// INPUTS
// ============================================
grp_lookback = "Lookback Settings"
lookbackBars = input.int(378, "Lookback Bars (378 = 18mo)", minval=50, maxval=1000, group=grp_lookback, tooltip="Only consider pivots within this many bars. 252=1yr, 378=18mo")
minTouches = input.int(2, "Min Touches Required", minval=1, maxval=5, group=grp_lookback, tooltip="Level must have this many rejections to be valid")
touchZonePct = input.float(1.0, "Touch Zone %", minval=0.5, maxval=3.0, step=0.5, group=grp_lookback, tooltip="How close price must come to count as a touch")

grp_pivot = "Pivot Detection"
pivotStrength = input.int(5, "Pivot Strength", minval=2, maxval=20, group=grp_pivot, tooltip="Bars left/right to confirm pivot")
maxLevels = input.int(5, "Max Levels Per Side", minval=1, maxval=10, group=grp_pivot)
avoidExtremes = input.bool(true, "Avoid Extreme Outliers", group=grp_pivot, tooltip="Skip absolute 52w high/low as levels")

grp_display = "Display"
showSupport = input.bool(true, "Show Support", group=grp_display)
showResistance = input.bool(true, "Show Resistance", group=grp_display)
showLabels = input.bool(true, "Show Labels", group=grp_display)
showTouchCount = input.bool(true, "Show Touch Count", group=grp_display)

grp_colors = "Colors (by Strength)"
weakColor = input.color(color.new(color.gray, 50), "Weak (2 touches)", group=grp_colors)
mediumColor = input.color(color.new(color.yellow, 30), "Medium (3-4 touches)", group=grp_colors)
strongColor = input.color(color.new(color.lime, 0), "Strong (5+ touches)", group=grp_colors)
resistanceHue = input.color(color.new(color.red, 30), "Resistance Tint", group=grp_colors)

// ============================================
// HELPER: Count touches at a level
// ============================================
countTouches(float level, int startBar, float zonePct) =>
    touches = 0
    zoneSize = level * zonePct / 100
    upperZone = level + zoneSize
    lowerZone = level - zoneSize

    barsToCheck = math.min(bar_index - startBar, lookbackBars)
    if barsToCheck > 0
        for i = 0 to barsToCheck - 1
            idx = bar_index - i
            if idx >= 0
                h = high[i]
                l = low[i]
                // Check if high or low touched the zone
                if (h >= lowerZone and h <= upperZone) or (l >= lowerZone and l <= upperZone)
                    touches += 1
    touches

// ============================================
// HELPER: Check if level is an extreme outlier
// ============================================
high52w = ta.highest(high, 252)
low52w = ta.lowest(low, 252)

isOutlier(float level) =>
    if not avoidExtremes
        false
    else
        // Skip if within 1% of absolute 52w high or low
        nearHigh = math.abs(level - high52w) / high52w < 0.01
        nearLow = math.abs(level - low52w) / low52w < 0.01
        nearHigh or nearLow

// ============================================
// PIVOT DETECTION (with lookback limit)
// ============================================
pivotHigh = ta.pivothigh(high, pivotStrength, pivotStrength)
pivotLow = ta.pivotlow(low, pivotStrength, pivotStrength)

// Store recent pivots only
var float[] recentPivotHighs = array.new_float(0)
var float[] recentPivotLows = array.new_float(0)
var int[] pivotHighBars = array.new_int(0)
var int[] pivotLowBars = array.new_int(0)

// Track pivot high
if not na(pivotHigh)
    pivotBar = bar_index - pivotStrength
    // Only add if within lookback and not outlier
    if bar_index - pivotBar <= lookbackBars and not isOutlier(pivotHigh)
        // Check if unique (not within 1.5% of existing)
        isUnique = true
        if array.size(recentPivotHighs) > 0
            for i = 0 to array.size(recentPivotHighs) - 1
                if math.abs(pivotHigh - array.get(recentPivotHighs, i)) / pivotHigh < 0.015
                    isUnique := false
                    break
        if isUnique
            array.push(recentPivotHighs, pivotHigh)
            array.push(pivotHighBars, pivotBar)

// Track pivot low
if not na(pivotLow)
    pivotBar = bar_index - pivotStrength
    if bar_index - pivotBar <= lookbackBars and not isOutlier(pivotLow)
        isUnique = true
        if array.size(recentPivotLows) > 0
            for i = 0 to array.size(recentPivotLows) - 1
                if math.abs(pivotLow - array.get(recentPivotLows, i)) / pivotLow < 0.015
                    isUnique := false
                    break
        if isUnique
            array.push(recentPivotLows, pivotLow)
            array.push(pivotLowBars, pivotBar)

// Cleanup old pivots outside lookback
if barstate.islast
    // Remove old pivot highs
    if array.size(recentPivotHighs) > 0
        for i = array.size(recentPivotHighs) - 1 to 0
            if array.size(pivotHighBars) > i
                if bar_index - array.get(pivotHighBars, i) > lookbackBars
                    array.remove(recentPivotHighs, i)
                    array.remove(pivotHighBars, i)

    // Remove old pivot lows
    if array.size(recentPivotLows) > 0
        for i = array.size(recentPivotLows) - 1 to 0
            if array.size(pivotLowBars) > i
                if bar_index - array.get(pivotLowBars, i) > lookbackBars
                    array.remove(recentPivotLows, i)
                    array.remove(pivotLowBars, i)

// ============================================
// GET COLOR BY TOUCH COUNT
// ============================================
getColorByTouches(int touches, bool isResistance) =>
    baseColor = touches >= 5 ? strongColor : touches >= 3 ? mediumColor : weakColor
    // Tint resistance slightly red
    isResistance ? color.new(color.red, color.t(baseColor) + 20) : baseColor

getLineWidth(int touches) =>
    touches >= 5 ? 3 : touches >= 3 ? 2 : 1

// ============================================
// DRAW LEVELS
// ============================================
var line[] drawnLines = array.new_line(0)
var label[] drawnLabels = array.new_label(0)

// Declare at global scope so INFO TABLE can access
var float[] validLevels = array.new_float(0)
var int[] levelTouches = array.new_int(0)
var bool[] levelIsResistance = array.new_bool(0)
var int[] levelStartBars = array.new_int(0)

if barstate.islast
    // Clear old drawings
    if array.size(drawnLines) > 0
        for i = 0 to array.size(drawnLines) - 1
            line.delete(array.get(drawnLines, i))
    if array.size(drawnLabels) > 0
        for i = 0 to array.size(drawnLabels) - 1
            label.delete(array.get(drawnLabels, i))
    array.clear(drawnLines)
    array.clear(drawnLabels)

    currentPrice = close

    // Clear and rebuild valid levels
    array.clear(validLevels)
    array.clear(levelTouches)
    array.clear(levelIsResistance)
    array.clear(levelStartBars)

    // Process pivot highs (potential resistance)
    if array.size(recentPivotHighs) > 0
        for i = 0 to array.size(recentPivotHighs) - 1
            level = array.get(recentPivotHighs, i)
            startBar = array.get(pivotHighBars, i)
            touches = countTouches(level, startBar, touchZonePct)

            if touches >= minTouches
                array.push(validLevels, level)
                array.push(levelTouches, touches)
                array.push(levelIsResistance, level > currentPrice)
                array.push(levelStartBars, startBar)

    // Process pivot lows (potential support)
    if array.size(recentPivotLows) > 0
        for i = 0 to array.size(recentPivotLows) - 1
            level = array.get(recentPivotLows, i)
            startBar = array.get(pivotLowBars, i)
            touches = countTouches(level, startBar, touchZonePct)

            if touches >= minTouches
                // Check if already added from highs (role reversal!)
                alreadyExists = false
                if array.size(validLevels) > 0
                    for j = 0 to array.size(validLevels) - 1
                        if math.abs(level - array.get(validLevels, j)) / level < 0.015
                            // Boost touch count for role reversal!
                            existingTouches = array.get(levelTouches, j)
                            array.set(levelTouches, j, existingTouches + touches)
                            alreadyExists := true
                            break

                if not alreadyExists
                    array.push(validLevels, level)
                    array.push(levelTouches, touches)
                    array.push(levelIsResistance, level > currentPrice)
                    array.push(levelStartBars, startBar)

    // Draw support levels
    drawnSupport = 0
    if showSupport and array.size(validLevels) > 0
        for i = 0 to array.size(validLevels) - 1
            if drawnSupport >= maxLevels
                break
            level = array.get(validLevels, i)
            isRes = array.get(levelIsResistance, i)

            if not isRes  // Support = below current price
                touches = array.get(levelTouches, i)
                startBar = array.get(levelStartBars, i)

                lineColor = getColorByTouches(touches, false)
                lineWidth = getLineWidth(touches)

                newLine = line.new(startBar, level, bar_index + 20, level,
                     color=lineColor, width=lineWidth, style=line.style_solid,
                     extend=extend.right)
                array.push(drawnLines, newLine)

                if showLabels
                    touchText = showTouchCount ? " [" + str.tostring(touches) + "x]" : ""
                    labelText = "S " + str.tostring(level, "#.##") + touchText
                    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(drawnLabels, newLabel)

                drawnSupport += 1

    // Draw resistance levels
    drawnResistance = 0
    if showResistance and array.size(validLevels) > 0
        for i = 0 to array.size(validLevels) - 1
            if drawnResistance >= maxLevels
                break
            level = array.get(validLevels, i)
            isRes = array.get(levelIsResistance, i)

            if isRes  // Resistance = above current price
                touches = array.get(levelTouches, i)
                startBar = array.get(levelStartBars, i)

                lineColor = getColorByTouches(touches, true)
                lineWidth = getLineWidth(touches)

                newLine = line.new(startBar, level, bar_index + 20, level,
                     color=lineColor, width=lineWidth, style=line.style_solid,
                     extend=extend.right)
                array.push(drawnLines, newLine)

                if showLabels
                    touchText = showTouchCount ? " [" + str.tostring(touches) + "x]" : ""
                    labelText = "R " + str.tostring(level, "#.##") + touchText
                    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(drawnLabels, newLabel)

                drawnResistance += 1

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

if barstate.islast
    // Count levels by strength
    strongCount = 0
    mediumCount = 0
    weakCount = 0

    if array.size(validLevels) > 0
        for i = 0 to array.size(levelTouches) - 1
            t = array.get(levelTouches, i)
            if t >= 5
                strongCount += 1
            else if t >= 3
                mediumCount += 1
            else
                weakCount += 1

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

    table.cell(infoTable, 0, 1, "Strong (5+)", text_color=strongColor, text_size=size.tiny)
    table.cell(infoTable, 1, 1, str.tostring(strongCount), text_color=color.white, text_size=size.tiny)

    table.cell(infoTable, 0, 2, "Medium (3-4)", text_color=mediumColor, text_size=size.tiny)
    table.cell(infoTable, 1, 2, str.tostring(mediumCount), text_color=color.white, text_size=size.tiny)

    table.cell(infoTable, 0, 3, "Weak (2)", text_color=weakColor, text_size=size.tiny)
    table.cell(infoTable, 1, 3, str.tostring(weakCount), text_color=color.white, text_size=size.tiny)

    table.cell(infoTable, 0, 4, "Lookback", text_color=color.gray, text_size=size.tiny)
    table.cell(infoTable, 1, 4, str.tostring(lookbackBars) + " bars", text_color=color.gray, text_size=size.tiny)

Overview

STA S&R v2 identifies potential reversal points by finding local highs and lows with specified strength. For each level, it counts how many times price has touched or approached within a zone percentage. Levels are colored based on touch count: weak gray, medium yellow, strong lime. Settings allow adjusting lookback period (default 18 months), minimum touches required (default 2), pivot strength, and whether to show levels or labels. It draws horizontal lines and labels for each valid S&R level on the chart. The script recalculates levels on every bar update.

Details

Published by

balacloud on GitHub

Code credit

SwingTradeAnalyzer, as written in the script's header

Draws

On the price chart

Markets

Stocks

Timeframes

Any timeframe

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
Lookback Bars (378 = 18mo)int378lookbackBars
Min Touches Requiredint2minTouches
Touch Zone %float1.0touchZonePct
Pivot Strengthint5pivotStrength
Max Levels Per Sideint5maxLevels
Avoid Extreme OutliersbooltrueavoidExtremes
Show SupportbooltrueshowSupport
Show ResistancebooltrueshowResistance
Show LabelsbooltrueshowLabels
Show Touch CountbooltrueshowTouchCount
Weak (2 touches)colorcolor.new(color.gray, 50)weakColor
Medium (3-4 touches)colorcolor.new(color.yellow, 30)mediumColor
Show all 14 settings
SettingTypeDefaultVariable
Strong (5+ touches)colorcolor.new(color.lime, 0)strongColor
Resistance Tintcolorcolor.new(color.red, 30)resistanceHue
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

947 stars

Moving Average Channel plots separate simple moving averages for upper and lower bands on the price chart. It fills the space between bands with semi-transparent color and colors bars green above the upper band, red below the lower band, or gray in between. Us

Indicator v4 Moving averagesSupport & resistance
Updated 12 days ago · GPL-3.0 GitHub repository of Moving Average Channel

ICT Equal Highs and Lows

by ArunKBhaskar
575 stars

This overlay indicator finds pivot highs and lows on the price chart and compares the last two highs and the last two lows. When the percentage difference between a pair is below the Equal HL threshold, it treats them as equal levels and draws a box. Left and

Indicator v5 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows
330 stars

This indicator monitors multiple cryptocurrency symbols for trading signals. It calculates and plots entry prices, take profit, and stop loss levels for each symbol including BTCUSDT, ETHUSDT, BNBUSDT and others. Price crossovers trigger buy, sell or close ale

Indicator v5 Support & resistanceScreeners & dashboards
Updated 2 months ago · None stated GitHub repository of Multi Alert Long/Short [Alorse]

This overlay indicator draws a fixed-range volume profile on the price chart, splitting traded activity into up and down volume at each price level. It also plots a sentiment profile, a developing point of control, and value-area high and low around a configur

Indicator v5 VolumeSupport & resistance
Updated 2 months ago · MIT GitHub repository of Volume Profile and Indicator by DGT

BZ-tracker

by Allen1212
303 stars

The BZ-tracker indicator marks ARK Invest buy and sell transactions on stock charts with labels. It plots green labels for purchases and red labels for sales, each annotated with a multiplier such as X1 or X2 to show the number of ARK ETFs trading the stock on

Indicator v4 Support & resistanceScreeners & dashboards
Updated 2 years ago · None stated GitHub repository of BZ-tracker

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

More Support & resistance scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers