Indicator · Pine Script v6 · On the chart

Levels S/R Boxes + Gaps + SL/TP

by ognenmitev

Draws support and resistance boxes from pivot highs and lows on the price chart, with box height set as a multiple of ATR.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code236
Settings17inputs
LicenceCustom licencefile: MPL-2.0
Last update11 months ago3 Dec 2025

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

236 lines of Pine Script v6 from TV Indicators/levels_sr_boxes.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

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

//@version=6
indicator("Levels S/R Boxes + Gaps + SL/TP", overlay=true, max_boxes_count=100, max_lines_count=100)

// ============================================================================
// INPUTS
// ============================================================================

// Support/Resistance
pivotStrength = input.int(10, "Pivot Strength", minval=3, maxval=30, group="Support & Resistance")
maxLevels = input.int(3, "Number of Levels", minval=1, maxval=8, group="Support & Resistance")
boxExtend = input.int(50, "Box Extension", minval=10, maxval=100, group="Support & Resistance")
srBoxHeight = input.float(0.3, "Box Height (ATR)", minval=0.1, maxval=1.0, step=0.1, group="Support & Resistance")

// Gaps
enableGaps = input.bool(true, "Show Gap Fills", group="Gaps")
minGapPercent = input.float(0.3, "Min Gap %", minval=0.1, maxval=5.0, step=0.1, group="Gaps")
showFilledGaps = input.bool(false, "Show Filled Gaps", group="Gaps")

// Stop Loss & Take Profit
enableSLTP = input.bool(true, "Show SL/TP Lines", group="Stop Loss & Take Profit")
slAtrMult = input.float(2.0, "SL ATR Multiplier", minval=0.5, maxval=5.0, step=0.5, group="Stop Loss & Take Profit")
tpRatio1 = input.float(2.0, "TP1 Risk:Reward", minval=1.0, maxval=5.0, step=0.5, group="Stop Loss & Take Profit")
tpRatio2 = input.float(3.0, "TP2 Risk:Reward", minval=1.5, maxval=8.0, step=0.5, group="Stop Loss & Take Profit")

// Colors
supportCol = input.color(color.new(color.green, 50), "Support Color", group="Colors")
resistanceCol = input.color(color.new(color.red, 50), "Resistance Color", group="Colors")
gapCol = input.color(color.new(color.purple, 80), "Gap Color", group="Colors")
slCol = input.color(color.red, "Stop Loss Color", group="Colors")
tp1Col = input.color(color.green, "TP1 Color", group="Colors")
tp2Col = input.color(color.lime, "TP2 Color", group="Colors")

// ============================================================================
// CALCULATIONS
// ============================================================================

// ATR for box sizing
atr = ta.atr(14)

// Detect Pivots
pivotHigh = ta.pivothigh(high, pivotStrength, pivotStrength)
pivotLow = ta.pivotlow(low, pivotStrength, pivotStrength)

// Store levels
var resistanceLevels = array.new<float>()
var supportLevels = array.new<float>()
var resistanceBars = array.new<int>()
var supportBars = array.new<int>()

// Add resistance
if not na(pivotHigh)
    array.push(resistanceLevels, pivotHigh)
    array.push(resistanceBars, bar_index[pivotStrength])
    if array.size(resistanceLevels) > maxLevels
        array.shift(resistanceLevels)
        array.shift(resistanceBars)

// Add support
if not na(pivotLow)
    array.push(supportLevels, pivotLow)
    array.push(supportBars, bar_index[pivotStrength])
    if array.size(supportLevels) > maxLevels
        array.shift(supportLevels)
        array.shift(supportBars)

// Find nearest levels
var float nearSupport = na
var float nearResistance = na

if array.size(supportLevels) > 0
    for i = 0 to array.size(supportLevels) - 1
        level = array.get(supportLevels, i)
        if level < close and (na(nearSupport) or level > nearSupport)
            nearSupport := level

if array.size(resistanceLevels) > 0
    for i = 0 to array.size(resistanceLevels) - 1
        level = array.get(resistanceLevels, i)
        if level > close and (na(nearResistance) or level < nearResistance)
            nearResistance := level

// Gap Detection
prevHigh = high[1]
prevLow = low[1]
gapUp = low > prevHigh
gapDown = high < prevLow
gapPercent = 0.0

if gapUp
    gapPercent := (low - prevHigh) / prevHigh * 100
else if gapDown
    gapPercent := (prevLow - high) / prevLow * 100

significantGap = gapPercent >= minGapPercent

// Track gaps
var gapTops = array.new<float>()
var gapBottoms = array.new<float>()
var gapBars = array.new<int>()
var gapFilled = array.new<bool>()

// Add new gaps
if enableGaps and significantGap and (gapUp or gapDown)
    if gapUp
        array.push(gapTops, low)
        array.push(gapBottoms, prevHigh)
    else
        array.push(gapTops, prevLow)
        array.push(gapBottoms, high)
    array.push(gapBars, bar_index)
    array.push(gapFilled, false)

// Check gap fills
if array.size(gapTops) > 0
    for i = array.size(gapTops) - 1 to 0
        if not array.get(gapFilled, i)
            top = array.get(gapTops, i)
            bottom = array.get(gapBottoms, i)
            filled = (low <= (top + bottom) / 2)
            if filled
                array.set(gapFilled, i, true)

// Calculate SL/TP
longSL = close - (atr * slAtrMult)
shortSL = close + (atr * slAtrMult)
longRisk = close - longSL
shortRisk = shortSL - close
longTP1 = close + (longRisk * tpRatio1)
longTP2 = close + (longRisk * tpRatio2)
shortTP1 = close - (shortRisk * tpRatio1)
shortTP2 = close - (shortRisk * tpRatio2)

// ============================================================================
// DRAW SUPPORT/RESISTANCE BOXES
// ============================================================================

if barstate.islast
    // Draw Resistance Boxes
    for i = 0 to array.size(resistanceLevels) - 1
        level = array.get(resistanceLevels, i)
        startBar = array.get(resistanceBars, i)
        top = level + (atr * srBoxHeight)
        bottom = level - (atr * srBoxHeight)
        box.new(startBar, top, bar_index + boxExtend, bottom, border_color=resistanceCol, bgcolor=color.new(resistanceCol, 85), border_width=2)
        label.new(bar_index + 5, level, "R" + str.tostring(i + 1) + "\n" + str.tostring(math.round(level, 2)), style=label.style_label_left, color=color.new(color.red, 30), textcolor=color.white, size=size.small)
    
    // Draw Support Boxes
    for i = 0 to array.size(supportLevels) - 1
        level = array.get(supportLevels, i)
        startBar = array.get(supportBars, i)
        top = level + (atr * srBoxHeight)
        bottom = level - (atr * srBoxHeight)
        box.new(startBar, top, bar_index + boxExtend, bottom, border_color=supportCol, bgcolor=color.new(supportCol, 85), border_width=2)
        label.new(bar_index + 5, level, "S" + str.tostring(i + 1) + "\n" + str.tostring(math.round(level, 2)), style=label.style_label_left, color=color.new(color.green, 30), textcolor=color.white, size=size.small)

// ============================================================================
// DRAW GAP BOXES
// ============================================================================

if enableGaps and barstate.islast
    for i = 0 to array.size(gapTops) - 1
        filled = array.get(gapFilled, i)
        if not filled or showFilledGaps
            top = array.get(gapTops, i)
            bottom = array.get(gapBottoms, i)
            startBar = array.get(gapBars, i)
            boxColor = filled ? color.new(gapCol, 95) : gapCol
            borderColor = filled ? color.new(color.gray, 80) : color.new(color.purple, 50)
            box.new(startBar, top, bar_index + 10, bottom, border_color=borderColor, bgcolor=boxColor, border_width=1, border_style=line.style_dashed)
            if not filled
                label.new(startBar + 2, (top + bottom) / 2, "GAP", style=label.style_none, textcolor=color.purple, size=size.tiny)

// ============================================================================
// DRAW SL/TP LINES
// ============================================================================

if enableSLTP and barstate.islast
    // Long Position Lines
    line.new(bar_index - 5, longSL, bar_index + boxExtend, longSL, color=slCol, width=3, style=line.style_solid)
    line.new(bar_index - 5, longTP1, bar_index + boxExtend, longTP1, color=tp1Col, width=2, style=line.style_dashed)
    line.new(bar_index - 5, longTP2, bar_index + boxExtend, longTP2, color=tp2Col, width=2, style=line.style_dotted)
    
    // Short Position Lines
    line.new(bar_index - 5, shortSL, bar_index + boxExtend, shortSL, color=slCol, width=3, style=line.style_solid)
    line.new(bar_index - 5, shortTP1, bar_index + boxExtend, shortTP1, color=tp1Col, width=2, style=line.style_dashed)
    line.new(bar_index - 5, shortTP2, bar_index + boxExtend, shortTP2, color=tp2Col, width=2, style=line.style_dotted)
    
    // Labels for Long
    label.new(bar_index + boxExtend + 2, longSL, "LONG SL\n" + str.tostring(math.round(longSL, 2)), style=label.style_label_left, color=slCol, textcolor=color.white, size=size.small)
    label.new(bar_index + boxExtend + 2, longTP1, "TP1\n" + str.tostring(math.round(longTP1, 2)), style=label.style_label_left, color=tp1Col, textcolor=color.white, size=size.tiny)
    label.new(bar_index + boxExtend + 2, longTP2, "TP2\n" + str.tostring(math.round(longTP2, 2)), style=label.style_label_left, color=tp2Col, textcolor=color.white, size=size.tiny)
    
    // Labels for Short
    label.new(bar_index + boxExtend + 2, shortSL, "SHORT SL\n" + str.tostring(math.round(shortSL, 2)), style=label.style_label_left, color=slCol, textcolor=color.white, size=size.small)
    label.new(bar_index + boxExtend + 2, shortTP1, "TP1\n" + str.tostring(math.round(shortTP1, 2)), style=label.style_label_left, color=tp1Col, textcolor=color.white, size=size.tiny)
    label.new(bar_index + boxExtend + 2, shortTP2, "TP2\n" + str.tostring(math.round(shortTP2, 2)), style=label.style_label_left, color=tp2Col, textcolor=color.white, size=size.tiny)

// ============================================================================
// CURRENT PRICE LINE
// ============================================================================

if barstate.islast
    line.new(bar_index - 20, close, bar_index + boxExtend, close, color=color.new(color.white, 50), width=1, style=line.style_solid)
    label.new(bar_index, close, "PRICE: " + str.tostring(math.round(close, 2)), style=label.style_label_left, color=color.new(color.blue, 60), textcolor=color.white, size=size.normal)

// ============================================================================
// VISUAL ALERTS
// ============================================================================

// Price near S/R
nearSupp = not na(nearSupport) and low <= nearSupport * 1.005 and low >= nearSupport * 0.995
nearRes = not na(nearResistance) and high >= nearResistance * 0.995 and high <= nearResistance * 1.005

bgcolor(nearSupp ? color.new(color.green, 95) : na, title="Near Support")
bgcolor(nearRes ? color.new(color.red, 95) : na, title="Near Resistance")

// Plot signals
plotshape(nearSupp, "At Support", shape.triangleup, location.belowbar, color.green, size=size.small, text="SUP")
plotshape(nearRes, "At Resistance", shape.triangledown, location.abovebar, color.red, size=size.small, text="RES")
plotshape(significantGap and gapUp, "Gap Up", shape.circle, location.belowbar, color.purple, size=size.tiny)
plotshape(significantGap and gapDown, "Gap Down", shape.circle, location.abovebar, color.purple, size=size.tiny)

// ============================================================================
// ALERTS
// ============================================================================

alertcondition(nearSupp, "Price at Support", "Price reached support level")
alertcondition(nearRes, "Price at Resistance", "Price reached resistance level")
alertcondition(significantGap, "Gap Detected", "Significant price gap detected")
alertcondition(close <= longSL, "Long SL Hit", "Price hit long stop loss level")
alertcondition(close >= longTP1, "Long TP1 Hit", "Price hit long take profit 1")
alertcondition(close >= shortSL, "Short SL Hit", "Price hit short stop loss level")
alertcondition(close <= shortTP1, "Short TP1 Hit", "Price hit short take profit 1")

Overview

Levels S/R Boxes + Gaps + SL/TP also marks price gaps above a minimum percentage, with an option to show filled ones, and draws stop loss and two take profit lines. The stop distance is an ATR multiple and the targets use two risk-to-reward ratios. Pivot strength, number of levels, box extension and colours are adjustable. Pivots confirm only after several bars.

Details

Published by

ognenmitev on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Support & resistance, Volatility & bands

Markets

Any symbol

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
Pivot Strengthint10pivotStrength
Number of Levelsint3maxLevels
Box Extensionint50boxExtend
Box Height (ATR)float0.3srBoxHeight
Show Gap FillsbooltrueenableGaps
Min Gap %float0.3minGapPercent
Show Filled GapsboolfalseshowFilledGaps
Show SL/TP LinesbooltrueenableSLTP
SL ATR Multiplierfloat2.0slAtrMult
TP1 Risk:Rewardfloat2.0tpRatio1
TP2 Risk:Rewardfloat3.0tpRatio2
Support Colorcolorcolor.new(color.green, 50)supportCol
Show all 17 settings
SettingTypeDefaultVariable
Resistance Colorcolorcolor.new(color.red, 50)resistanceCol
Gap Colorcolorcolor.new(color.purple, 80)gapCol
Stop Loss Colorcolorcolor.redslCol
TP1 Colorcolorcolor.greentp1Col
TP2 Colorcolorcolor.limetp2Col
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

ICT Liquidity Void Fill

by ArunKBhaskar
575 stars

This overlay indicator marks ICT liquidity void fills on the price chart and can show long and short signals. It places a Fibonacci level inside a displacement candle, defaulting to the midpoint, and draws lines in a chosen style. Optional filters limit the fi

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Liquidity Void Fill

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

Lux Trailing

by dearvn
257 stars

Plots kernel-smoothed price zones on the price chart using a Rational Quadratic kernel from an imported library. It builds an inner and an outer high-low zone from 15-minute highs and lows, plus a smoothed close and a midline, and marks bullish or bearish bars

Indicator v5 Support & resistanceVolatility & bands Repaints
Updated 6 weeks ago · None stated GitHub repository of Lux Trailing

Candlestick Patterns

by harryguiacorn
219 stars

This indicator plots optional candlestick pattern signals on the price chart. It detects engulfing bars, inside bars, HOLP and LOHP, kicker patterns, body-mass extremes, higher highs and lower lows, ATR warnings, and four-bar fractals. Optional pivot marks use

Indicator v5 Candlestick patternsVolatility & bands
Updated 1 year ago · None stated GitHub repository of Candlestick Patterns

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