Strategy · Pine Script v5 · On the chart

Support and Resistance with RSI and Trend Filter

by wynnforthework· code credited to alescha73

This strategy plots support and resistance from the highest high and lowest low over a lookback window, and can overlay Bollinger Bands on the price chart.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code268
Settings40inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 Oct 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 strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

268 lines of Pine Script v5 from 策略/DCA、RSI 和趋势过滤器的支撑位和阻力位.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

DCA、RSI 和趋势过滤器的支撑位和阻力位.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © alescha73
// this script is bases on script from Kieranj https://www.tradingview.com/v/8avMvSbe/

//@version=5
strategy("Support and Resistance with RSI and Trend Filter", overlay=true, default_qty_type = strategy.cash, default_qty_value = 100, initial_capital = 10000, pyramiding = 100)

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>//

testStartYear = input.int(2023, 'Backtest Start Year', minval=1980)
testStartMonth = input.int(1, 'Backtest Start Month', minval=1, maxval=12)
testStartDay = input.int(1, 'Backtest Start Day', minval=1, maxval=31)
testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0)

testStopYear = input.int(9999, 'Backtest Stop Year', minval=1980)
testStopMonth = input.int(12, 'Backtest Stop Month', minval=1, maxval=12)
testStopDay = input.int(31, 'Backtest Stop Day', minval=1, maxval=31)
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)

testPeriod() =>
    time >= testPeriodStart and time <= testPeriodStop ? true : false

//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<//

// === STRATEGY ===
tradeType = input.string('LONG', title='What trades should be taken : ', options=['LONG', 'SHORT', 'BOTH', 'NONE'])


uha = input(false, title='Use Heikin Ashi Candles', group = "RSI")
o_rsi = "RSI"
o_mfi = "MFI"
i_osc = input.string(o_rsi, title = "Oscillator Type", options = [o_rsi, o_mfi])
f_osc(_src, _len) => i_osc == o_mfi ? ta.mfi(_src, _len) : ta.rsi(_src, _len)

// Use only Heikinashi Candles for all calculations or use Standard Candles for calculations.
srcClose = uha ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close) : request.security(syminfo.tickerid, timeframe.period, close)
//
// BB
useBB = input(false, group = "BB")
bblength = input(50, group = "BB")
bbupmult =input(1.5,title="Multiplier for BB Upper Band", group = "BB")
bblowmult = input(1.5,title="Multiplier for BB Lower Band", group = "BB")

basis =  ta.sma(srcClose,bblength)

devup = bbupmult * ta.stdev(srcClose, bblength)
devlow = bblowmult * ta.stdev(srcClose, bblength)

upper = basis + devup
lower = basis - devlow
plot(basis, color=color.red)
p1 = plot(upper, color=color.blue)
p2 = plot(lower, color=color.blue)
fill(p1, p2)

// Support and Resistance Calculation
lookbackBars = input(50, title="Lookback Bars", group = "S&P")

highs = ta.highest(high, lookbackBars)
lows = ta.lowest(low, lookbackBars)

supportLevel = ta.valuewhen(low == lows, low, 0)
resistanceLevel = ta.valuewhen(high == highs, high, 0)

plot(supportLevel, color=color.green, linewidth=1, title="Support")
plot(resistanceLevel, color=color.red, linewidth=1, title="Resistance")

// RSI Conditions
rsiLength = input(14, title="RSI Length", group = "RSI")
overboughtThreshold = input(62, title="Overbought Threshold", group = "RSI")
oversoldThreshold = input(38, title="Oversold Threshold", group = "RSI")

rsi = f_osc(srcClose, rsiLength)

// Wave trend

useWT = input.bool(title="Use wave trend?", group = "Wave trend", defval=true) 
n1 = input.int(title="Channel Length", group = "Wave trend", defval=12) //Channel Length
n2 = input.int(title="Average Length", group = "Wave trend", defval=20) //Average Length
obLevel1 = input.int(title="Over Bought Level 1", group = "Wave trend", defval=60) //Over Bought Level 1
obLevel2 = input.int(title="Over Bought Level 2", group = "Wave trend", defval=53) //Over Bought Level 2
osLevel1 = input.int(title="Over Sold Level 1", group = "Wave trend", defval=-60) //Over Sold Level 1
osLevel2 = input.int(title="Over Sold Level 2", group = "Wave trend", defval=-53) //Over Sold Level 2
ap = input.source(title="Source", group = "Wave trend", defval=hlcc4)

useLag = input.bool(title="Apply Laguerre Smoothing", defval=true)
gamma = input.float(title="Laguerre Gamma", defval=0.03)

lag(g, p) => // Laguerre PPO Code from TheLark
    L0=0.0, L0 := (1 - g)*p+g*nz(L0[1])
    L1=0.0, L1 := -g*L0+nz(L0[1])+g*nz(L1[1])
    L2=0.0, L2 := -g*L1+nz(L1[1])+g*nz(L2[1])
    L3=0.0, L3 := -g*L2+nz(L2[1])+g*nz(L3[1])
    (L0 + 2*L1 + 2*L2 + L3)/6

esa = ta.ema(ap, n1) 
apesa = math.abs(ap - esa)
d = ta.ema(apesa, n1)
ci = (ap - esa) / (0.015 * d)
tci = ta.ema(ci, n2)

output = lag(gamma, tci)
wt1 = useLag ? output : tci
wt2 = ta.sma(wt1, 4)
wt3 = (wt1 - wt2)

WTBull = ta.crossover(wt1, wt2) and wt1 < osLevel2 
WTBear = ta.crossunder(wt1, wt2) and wt1 > obLevel2 

// Divergences //
useDivergences = input.bool(title="Use divergences?", group = "Divergences", defval=false) 

len = input.int(title="RSI Period", group = "Divergences", minval=1, defval=14)
src = input.source(title="RSI Source", group = "Divergences", defval=close)
lbR = input.int(title="Pivot Lookback Right", group = "Divergences", defval=5)
lbL = input.int(title="Pivot Lookback Left", group = "Divergences", defval=5)

rangeUpper = input.int(title="Max of Lookback Range", group = "Divergences", defval=60)
rangeLower = input.int(title="Min of Lookback Range", group = "Divergences", defval=5)

osc = f_osc(src, len)

_inRange(cond) =>
    bars = ta.barssince(cond == true)
    rangeLower <= bars and bars <= rangeUpper

plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true

f_DivergenceBullish(osc, plFound) =>   
    //------------------------------------------------------------------------------
    // Regular Bullish

    // Osc: Higher Low
    oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

    // Price: Lower Low
    priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)

    bullCond = priceLL and oscHL and plFound

    //------------------------------------------------------------------------------
    // Hidden Bullish

    // Osc: Lower Low
    oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

    // Price: Higher Low
    priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
    hiddenBullCond = priceHL and oscLL and plFound
    bullCond or hiddenBullCond

divergenceLongCondition = f_DivergenceBullish(osc, plFound)

f_DivergenceBearish(osc, phFound) => 
    //------------------------------------------------------------------------------
    // Regular Bearish

    // Osc: Lower High
    oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

    // Price: Higher High
    priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)

    bearCond = priceHH and oscLH and phFound

    //------------------------------------------------------------------------------
    // Hidden Bearish

    // Osc: Higher High
    oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

    // Price: Lower High
    priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)

    hiddenBearCond = priceLH and oscHH and phFound

    hiddenBearCond or bearCond

divergenceCloseCondition = f_DivergenceBearish(osc, phFound) 
// Trend Filter
useTrendFilter = input.bool(true, "Use trend filter?", group = "Trend filter")
trendtimeframe = input.string("240", "Trend filter timeframe", group = "Trend filter")

//g trend

useGtrend = input(title='use G Trend as trend indicator', group = "g Trend",  defval=true)
length = input(title='ATR Period', group = "g Trend", defval=99)
mult = input.float(title='ATR Multiplier', step=0.1, group = "g Trend", defval=1)
wicks = input(title='Take Wicks into Account ?', group = "g Trend", defval=false)


f_gtrend(length, mult, wicks) => 
    atr = mult * ta.atr(length)

    longStop = hl2 - atr
    longStopPrev = nz(longStop[1], longStop)
    longStop := (wicks ? low[1] : close[1]) > longStopPrev ? math.max(longStop, longStopPrev) : longStop

    shortStop = hl2 + atr
    shortStopPrev = nz(shortStop[1], shortStop)
    shortStop := (wicks ? high[1] : close[1]) < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop

    dir = 1
    dir := nz(dir[1], dir)
    dir := dir == -1 and (wicks ? high : close) > shortStopPrev ? 1 : dir == 1 and (wicks ? low : close) < longStopPrev ? -1 : dir
    dir


//isUptrend = useTrendFilter and request.security(syminfo.tickerid, trendtimeframe, ta.sma(srcClose, 50) > ta.sma(srcClose, 200)) 
isUptrend = useTrendFilter and useGtrend ? request.security(syminfo.tickerid, trendtimeframe, f_gtrend(length, mult, wicks) == 1) : request.security(syminfo.tickerid, trendtimeframe, ta.sma(srcClose, 50) > ta.sma(srcClose, 200)) 


plotshape(true, title='Trend Indicator', location=location.bottom, color= isUptrend ? color.green : color.red, style=shape.circle, offset=-1, transp=0)

oversold = ta.crossover(rsi, oversoldThreshold) and not useWT and not useDivergences  or rsi < oversoldThreshold and (WTBull and useWT or divergenceLongCondition and useDivergences)

profitPerc = input.float(0.9, title="Profit %", group = "Profit")
profitPerc2 = input.float(0.3, title="Profit outside trend %", group = "Profit")
partSellPerc = input.int(75, title="Part. sell %", group = "Profit")

insidePeriod = time >= testPeriodStart and time <= testPeriodStop ? true : false

// Buy Condition
buyCondition = oversold and srcClose >= supportLevel and (not useBB or srcClose < lower) and insidePeriod

overbought = ta.crossunder(rsi, overboughtThreshold) and not useWT or rsi > overboughtThreshold and WTBear and useWT
// Sell Condition
sellCondition = overbought and srcClose <= resistanceLevel and (not useBB or srcClose > upper) and insidePeriod


var int lastEntryBar = 0
var bool canEnterNewTrade = true
delayInBars = 12

if strategy.position_size > 0 
    if overbought  and srcClose > strategy.position_avg_price * (1 + (isUptrend and useTrendFilter ? profitPerc : profitPerc2) /100.) and (bar_index - lastEntryBar) >= delayInBars 
        if not isUptrend and useTrendFilter
            strategy.close("long", qty_percent = 100)
        else 
            if partSellPerc > 0
                strategy.close("long", qty_percent = partSellPerc)
        lastEntryBar := bar_index

if strategy.position_size < 0 
    if oversold  and srcClose < strategy.position_avg_price * (1 - (not isUptrend and useTrendFilter ? profitPerc : profitPerc2)/100.) and (bar_index - lastEntryBar) >= delayInBars 
        if isUptrend and useTrendFilter
            strategy.close("short", qty_percent = 100)
        else 
            if partSellPerc > 0
                strategy.close("short", qty_percent = partSellPerc)
        lastEntryBar := bar_index

if buyCondition and (bar_index - lastEntryBar) >= delayInBars and strategy.position_size >= 0 and (tradeType == "BOTH" or tradeType == "LONG")
    strategy.entry("long", strategy.long) 
    lastEntryBar := bar_index
if sellCondition and (bar_index - lastEntryBar) >= delayInBars and strategy.position_size <= 0 and (tradeType == "BOTH" or tradeType == "SHORT")
    strategy.entry("short", strategy.short) 
    lastEntryBar := bar_index

// Plotting Buy/Sell Signals
//plotshape(buyCondition, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
//plotshape(sellCondition, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")

// Plotting RSI
//hline(overboughtThreshold, "Overbought", color=color.red)
//hline(oversoldThreshold, "Oversold", color=color.green)
//plot(rsi, title="RSI", color=color.orange, linewidth=2)

Overview

Support and Resistance with RSI and Trend Filter calculates RSI or MFI, optionally from Heikin Ashi prices, and exposes WaveTrend, Laguerre smoothing and divergence settings. Orders are restricted to a chosen direction, long, short, both or none, inside a backtest date window. Pyramiding allows many stacked positions, and the visible code sets no stop loss.

Details

Published by

wynnforthework on GitHub

Code credit

alescha73, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Support & resistance, Oscillators & momentum, Volatility & bands, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy can add several entries in the same direction
  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
Backtest Start Yearint2023testStartYear
Backtest Start Monthint1testStartMonth
Backtest Start Dayint1testStartDay
Backtest Stop Yearint9999testStopYear
Backtest Stop Monthint12testStopMonth
Backtest Stop Dayint31testStopDay
What trades should be taken : stringLONGtradeType
Use Heikin Ashi Candlesboolfalseuha
Oscillator Typestringo_rsii_osc
useBBboolfalseuseBB
bblengthint50bblength
Multiplier for BB Upper Bandfloat1.5bbupmult
Show all 40 settings
SettingTypeDefaultVariable
Multiplier for BB Lower Bandfloat1.5bblowmult
Lookback Barsint50lookbackBars
RSI Lengthint14rsiLength
Overbought Thresholdint62overboughtThreshold
Oversold Thresholdint38oversoldThreshold
Use wave trend?booltrueuseWT
Channel Lengthint12n1
Average Lengthint20n2
Over Bought Level 1int60obLevel1
Over Bought Level 2int53obLevel2
Over Sold Level 1int-60osLevel1
Over Sold Level 2int-53osLevel2
Sourcesourcehlcc4ap
Apply Laguerre SmoothingbooltrueuseLag
Laguerre Gammafloat0.03gamma
Use divergences?boolfalseuseDivergences
RSI Periodint14len
RSI Sourcesourceclosesrc
Pivot Lookback Rightint5lbR
Pivot Lookback Leftint5lbL
Max of Lookback Rangeint60rangeUpper
Min of Lookback Rangeint5rangeLower
Use trend filter?booltrueuseTrendFilter
Trend filter timeframestring240trendtimeframe
use G Trend as trend indicatorbooltrueuseGtrend
ATR Periodint99length
ATR Multiplierfloat1mult
Take Wicks into Account ?boolfalsewicks
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

Liquidity Sweep Scalper v2

by godlesscherry
2 stars

Liquidity Sweep Scalper v2 is a scalping strategy that detects liquidity sweeps using Supertrend trend filters, Bollinger Bands for volatility, Williams Fractals for pivots, and MACD momentum. It enters on rejection candle breaks after sweeps and exits via sto

Strategy v6 TrendOscillators & momentum
Updated 7 months ago · None stated GitHub repository of Liquidity Sweep Scalper v2

This strategy trades S50 TFEX USDTHB contracts on the price chart. It detects swing highs and swing lows with pivot points to generate long entries on swing highs and short entries on swing lows. The ATR indicator calculates dynamic stop-loss distances while t

Strategy v6 Volatility & bandsOscillators & momentum Repaints
Updated 1 year ago · None stated GitHub repository of S50 TFEX Strategy With ATR and Stoploss
257 stars

This strategy plots VWMA-based Bollinger bands on the 1-minute ES futures price chart for volatility analysis and potential breakout identification. It calculates dynamic long and short stop loss and take profit levels using percentage inputs relative to entry

Strategy v6 Volatility & bandsSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of V1.6 ES - Futures 1M No Repaint

Nasdaq Prop Firm Strategy

by TradersPost
218 stars

This strategy uses multiple VWAP anchors and a custom Lull indicator to generate buy and sell signals on the Nasdaq price chart. It plots the VWAP trend line and three VWAP anchors with customizable colors and mitigation methods. The Lull indicator produces si

Strategy v6 TrendSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Nasdaq Prop Firm Strategy

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers