Strategy · Pine Script v5 · On the chart

Support and Resistance with RSI and Trend Filter

by wynnforthework· code credited to alescha73

The strategy combines support and resistance levels with RSI or MFI momentum oscillators, optional WaveTrend indicators, and Bollinger Bands filters.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code305
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

305 lines of Pine Script v5 from 策略/DCA, Support and Resistance with RSI and Trend Filter.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

DCA, Support and Resistance with RSI and Trend Filter.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(2019, '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', group = "General", title='What trades should be taken : ', options=['LONG', 'SHORT', 'BOTH', 'NONE'])

uha = input(true, title='Use Heikin Ashi Candles', group = "General")
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)

delayInBars = input.int(12, title="Cooldown(bars)", group = "General")
profitPerc = input.float(0.9, title="Profit %", group = "General")
profitPerc2 = input.float(0.6, title="Profit outside trend %", group = "General")
partSellPerc = input.int(50, title="Part. sell %", group = "General")
ATRTresholdPartSellPerc = input.int(50, "ATR Threshold partial sell (percentrank)", group = "General")



// 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
useSupportResistence = input(false, title="use S&R?", group = "S&P")
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(70, title="Overbought Threshold", group = "RSI")
oversoldThreshold = input(40, 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
srcWT = input.source(title="Source", group = "Wave trend", defval=hlcc4)
obLevel = input(48, "Overbought Level", group = "Wave trend")
osLevel = input(-48, "Oversold Level", group = "Wave trend")

ap = uha ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, srcWT) : srcWT

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

WTBull = ta.crossover(wt1, wt2) and (wt1<osLevel)
WTBear = ta.crossunder(wt1, wt2) and (wt1>obLevel) 

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

len = input.int(title="RSI Period", minval=1, defval=14)
src = input(title="RSI Source", defval=close)
lbR = input(title="Pivot Lookback Right", defval=5, display = display.data_window)
lbL = input(title="Pivot Lookback Left", defval=5, display = display.data_window)
rangeUpper = input(title="Max of Lookback Range", defval=60, display = display.data_window)
rangeLower = input(title="Min of Lookback Range", defval=5, display = display.data_window)
osc = ta.rsi(src, len)

plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
    bars = ta.barssince(cond == true)
    rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------
// 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)
bullCondAlert = priceLL and oscHL and plFound
bullCond = bullCondAlert

//------------------------------------------------------------------------------
// 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)
hiddenBullCondAlert = priceHL and oscLL and plFound
hiddenBullCond = hiddenBullCondAlert


//------------------------------------------------------------------------------
// 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)

bearCondAlert = priceHH and oscLH and phFound
bearCond = bearCondAlert

//------------------------------------------------------------------------------
// 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)

hiddenBearCondAlert = priceLH and oscHH and phFound
hiddenBearCond = hiddenBearCondAlert
 
// Trend Filter
useTrendFilter = input.bool(true, "Use fast trend filter?", group = "Fast trend filter")
fast_trendtimeframe = input.string("15", "Fast trend filter timeframe", group = "Fast trend filter")
fast_rsiLength = input(14, title="RSI Length", group = "Fast trend filter")
fast_overboughtThreshold = input(65, title="Overbought Threshold", group = "Fast trend filter")
fast_oversoldThreshold = input(35, title="Oversold Threshold", group = "Fast trend filter")

useTrendFilter2 = input.bool(true, "Use slow  trend filter?", group = "Slow trend filter")
slow_trendtimeframe = input.string("240", "Slow trend filter timeframe", group = "Slow trend filter")
slow_rsiLength = input(14, title="RSI Length", group = "Slow trend filter")
slow_overboughtThreshold = input(70, title="Overbought Threshold", group = "Slow trend filter")
slow_oversoldThreshold = input(30, title="Oversold Threshold", group = "Slow trend filter")

//MACD 
useMACD = input(title='use MACD as trend indicator', group = "MACD",  defval=true)
fast_length = input(title = "Fast Length", group = "MACD", defval = 12)
slow_length = input(title = "Slow Length", group = "MACD", defval = 26)
MACDsrc = input(title = "Source", group = "MACD", defval = hlcc4)
signal_length = input.int(title = "Signal Smoothing",  minval = 1, maxval = 50, defval = 9, group = "MACD", display = display.data_window)
sma_source = input.string(title = "Oscillator MA Type",  defval = "SMA", options = ["SMA", "EMA"], group = "MACD", display = display.data_window)
sma_signal = input.string(title = "Signal Line MA Type", defval = "SMA", options = ["SMA", "EMA"], group = "MACD", display = display.data_window)
// Calculating

f_MACD(MACDsrc, fast_length, slow_length, signal_length, sma_source, sma_signal) => 
    fast_ma = sma_source == "SMA" ? ta.sma(MACDsrc, fast_length) : ta.ema(MACDsrc, fast_length)
    slow_ma = sma_source == "SMA" ? ta.sma(MACDsrc, slow_length) : ta.ema(MACDsrc, slow_length)
    macd = fast_ma - slow_ma
    macd
    signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
    MACDhist = macd - signal
    MACDhist

//g trend

useGtrend = input(title='use G Trend as trend indicator', group = "g Trend",  defval=false)
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] : srcClose[1]) > longStopPrev ? math.max(longStop, longStopPrev) : longStop

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

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


//isUptrend = useTrendFilter and request.security(syminfo.tickerid, trendtimeframe, ta.sma(srcClose, 50) > ta.sma(srcClose, 200)) 
CalcTrend(useMACD, useGtrend) => 
    result = 0.
    if useMACD
        result := f_MACD(MACDsrc, fast_length, slow_length, signal_length, sma_source, sma_signal)
    else
        if useGtrend
            result := f_gtrend(length, mult, wicks)
        else 
            result := ta.sma(srcClose, 50) - ta.sma(srcClose, 200)
    result

ATRPeriods = input.int(22, "ATR Periods", step=5,  group = "Fast trend filter")
lookback = input.int(2000, minval=1, title="ATR Percent Rank Lookback", group = "Fast trend filter")
atrp = request.security(syminfo.tickerid, fast_trendtimeframe, ta.percentrank(ta.atr(ATRPeriods), lookback))

isUptrend = useTrendFilter and (request.security(syminfo.tickerid, fast_trendtimeframe, CalcTrend(useMACD, useGtrend)>0 or f_osc(srcClose, fast_rsiLength) < fast_oversoldThreshold))
isUptrendSlow = useTrendFilter2 and (request.security(syminfo.tickerid, slow_trendtimeframe, CalcTrend(useMACD, useGtrend)>0 or f_osc(srcClose, slow_rsiLength) < slow_oversoldThreshold))
isDowntrend = useTrendFilter and (request.security(syminfo.tickerid, fast_trendtimeframe, CalcTrend(useMACD, useGtrend)<0 or f_osc(srcClose, fast_rsiLength) > fast_overboughtThreshold))
isDowntrendSlow = useTrendFilter2 and (request.security(syminfo.tickerid, slow_trendtimeframe, CalcTrend(useMACD, useGtrend)<0 or f_osc(srcClose, slow_rsiLength) > slow_overboughtThreshold))

//macd = request.security(syminfo.tickerid, trendtimeframe, f_MACD(MACDsrc, fast_length, slow_length, signal_length, sma_source, sma_signal)) 
//macd = f_MACD(MACDsrc, fast_length, slow_length, signal_length, sma_source, sma_signal) 

plotshape(isUptrend or isDowntrend, title='Trend Indicator blocking', location=location.top, color= tradeType == "SHORT" ? (isDowntrend ? color.red : color.black) : isUptrend ? color.green : color.red, style=shape.circle, offset=-1, transp=0)
plotshape(isUptrendSlow or isDowntrendSlow, title='Trend Indicator blocking', location=location.bottom, color= tradeType == "SHORT" ? (isDowntrendSlow? color.red : color.black) : isUptrendSlow ? color.green : color.red, style=shape.circle, offset=-1, transp=0)

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

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

// Buy Condition
buyCondition = oversold and (srcClose >= supportLevel or not useSupportResistence) and (not useBB or srcClose < lower) and (isUptrend or not useTrendFilter) and (isUptrendSlow or not useTrendFilter2) and insidePeriod 

overbought = not useWT and not useDivergences and ta.crossunder(rsi, overboughtThreshold) or (useWT or useDivergences) and rsi > overboughtThreshold and (not useWT or useWT and WTBear) and (not useDivergences  or useDivergences and bearCond)

// Sell Condition
sellCondition = overbought and (srcClose <= resistanceLevel or not useSupportResistence) and (not useBB or srcClose > upper) and (isDowntrend or not useTrendFilter) and (isDowntrendSlow or not useTrendFilter2) and insidePeriod


var int lastEntryBar = 0
var bool canEnterNewTrade = true

if strategy.position_size > 0 
    if overbought and srcClose > strategy.position_avg_price * (1 + ((isUptrend or not useTrendFilter) and (isUptrendSlow or not useTrendFilter) ? profitPerc : profitPerc2) /100.) and (bar_index - lastEntryBar) >= delayInBars 
        if not isUptrend and useTrendFilter or not isUptrendSlow and useTrendFilter2 or atrp > ATRTresholdPartSellPerc
            strategy.close_all(comment = "Full sell long")
        else 
            if partSellPerc > 0
                strategy.close("long", comment = "part. sell", qty_percent = partSellPerc)
        lastEntryBar := bar_index

if strategy.position_size < 0 
    if oversold and srcClose < strategy.position_avg_price * (1 - ((isDowntrend or not useTrendFilter) and (isDowntrendSlow  or not useTrendFilter2) ? profitPerc : profitPerc2)/100.) and (bar_index - lastEntryBar) >= delayInBars 
        if not isDowntrend and useTrendFilter or not isDowntrendSlow and useTrendFilter2
            strategy.close_all(comment = "Full sell short")
        else 
            if partSellPerc > 0
                strategy.close("short", comment = "Part. sell 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

Strategy logic evaluates trade signals on either Heikin Ashi or standard candle data to execute DCA entries with a configurable cooldown period between trades. Entries scale across multiple positions and exit through partial profit targets or ATR thresholds. It plots Bollinger Bands and support or resistance lines directly on the main price chart. Default settings allow extensive pyramiding and operate without a built-in 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

Trend, Support & resistance, Oscillators & momentum

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 Yearint2019testStartYear
Backtest Start Monthint1testStartMonth
Backtest Start Dayint1testStartDay
Backtest Stop Yearint9999testStopYear
Backtest Stop Monthint12testStopMonth
Backtest Stop Dayint31testStopDay
What trades should be taken : stringLONGtradeType
Use Heikin Ashi Candlesbooltrueuha
Oscillator Typestringo_rsii_osc
Cooldown(bars)int12delayInBars
Profit %float0.9profitPerc
Profit outside trend %float0.6profitPerc2
Show all 40 settings
SettingTypeDefaultVariable
Part. sell %int50partSellPerc
ATR Threshold partial sell (percentrank)int50ATRTresholdPartSellPerc
useBBboolfalseuseBB
bblengthint50bblength
Multiplier for BB Upper Bandfloat1.5bbupmult
Multiplier for BB Lower Bandfloat1.5bblowmult
use S&R?boolfalseuseSupportResistence
Lookback Barsint50lookbackBars
RSI Lengthint14rsiLength
Overbought Thresholdint70overboughtThreshold
Oversold Thresholdint40oversoldThreshold
Use wave trend?booltrueuseWT
Channel Lengthint12n1
Average Lengthint20n2
Sourcesourcehlcc4srcWT
Overbought Levelint48obLevel
Oversold Levelint-48osLevel
Use divergences?boolfalseuseDivergences
RSI Periodint14len
RSI Sourcesourceclosesrc
Pivot Lookback Rightint5lbR
Pivot Lookback Leftint5lbL
Max of Lookback Rangeint60rangeUpper
Min of Lookback Rangeint5rangeLower
Use fast trend filter?booltrueuseTrendFilter
Fast trend filter timeframestring15fast_trendtimeframe
RSI Lengthint14fast_rsiLength
Overbought Thresholdint65fast_overboughtThreshold
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

This strategy overlays the price chart and looks for VWAP pullbacks. It goes long when a short SMA crosses above VWAP after RSI has been oversold within ten bars, and short on the opposite cross after RSI has been overbought. Optional Minervini-style moving-av

Strategy v5 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of Advanced VWAP-Momentum Pullback Trend Qualifier

This strategy trades 1-minute futures contracts on Binance. It plots pivot high and low resistance and support levels on the price chart, along with an EMA and a custom Cto indicator. Long and short entries trigger on EMA and Cto crossovers combined with price

Strategy v5 TrendMoving averages Repaints
Updated 2 years ago · None stated GitHub repository of Binancash Futures Strategy 1M Candles

This strategy identifies reversal opportunities based on liquidity sweeps and multi-gate confluence scoring. It evaluates setups using mandatory conditions such as swing sweeps, body and ATR filters, and dual EMA higher-timeframe trend alignment, alongside opt

Strategy v6 SMC / ICT / price actionTrend
Updated yesterday · MIT GitHub repository of Reversal Engine Score [WavesUnchained] Strategy
7 stars

This strategy plots dynamic pivot-based support and resistance trendlines on the price chart and trades breakouts beyond those lines. By default it allows longs only when EMA 50 is above EMA 200 and an RSI-SMA momentum filter is met, with an ATR entry buffer.

Strategy v6 TrendBreakout
Updated 12 months ago · None stated GitHub repository of Easy Trendline - XAUUSD 30m

Optimizer v1

by QuantGeekDev
7 stars

This strategy generates long signals on the price chart using multiple technical indicators. It computes EMA 70 and 100, SMA 70, ADX with DMI, CCI, and MACD values. A long entry occurs when EMA crossover condition, SMA condition, ADX above 15, CCI above 30, an

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · None stated GitHub repository of Optimizer v1

This strategy combines MACD momentum signals with support and resistance levels from pivot points and an EMA100 trend filter for long positions. It plots the 100-period EMA on the price chart and signals when price breaks above the EMA or forms bullish pivot p

Strategy v4 TrendOscillators & momentum
Updated 3 years ago · Apache-2.0 GitHub repository of MACD + Support / Resistance Long 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