Strategy · Pine Script v5 · On the chart

TD RSI Strategy

by zhuzp98· code credited to rhapsodyz

This strategy combines a TD Sequential close comparison, RSI with a moving-average Bollinger envelope, MACD, and the Stochastic Momentum Index.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code201
Settings24inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago17 Jan 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

201 lines of Pine Script v5 from PineScript/Stg_TD_RSI_SMI.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

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

//@version=5


// #########################
// === Strategy Settings ===
// #########################

strategy(title = "TD RSI Strategy", 
     overlay            = true, 
     pyramiding         = 1, 
     initial_capital    = 10000, 
     default_qty_type   = strategy.percent_of_equity, 
     default_qty_value  = 100, 
     commission_type    = strategy.commission.percent, 
     commission_value   = 0.04, 
     slippage           = 2)

strat_dir_input = 
     input.string(title ="Strategy Direction", 
         defval         ="long", 
         options        =["long", "short", "all"])

strat_dir_value = 
     strat_dir_input == "long" ? strategy.direction.long : 
     strat_dir_input == "short" ? strategy.direction.short : 
     strategy.direction.all

strategy.risk.allow_entry_in(strat_dir_value)

// #######################
// === General Numbers ===
// #######################

// === Equity Usage ===
equityUsage = input(0.9, title="Equity Usage Percentage")
_qty = (strategy.equity * equityUsage) / close

// === Input A TD Sequential ===
tdSetup() =>
    var int setupCount = 0
    var int setupDirection = 0
    if close > close[4]
        if setupDirection != 1
            setupCount := 1
            setupDirection := 1
        else
            setupCount += 1
    else if close < close[4]
        if setupDirection != -1
            setupCount := -1
            setupDirection := -1
        else
            setupCount -= 1
    else
        setupCount := 0
    [setupCount, setupDirection]

// === Input B RSI ===
rsiLength       = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSource       = input.source(hlc3, "RSI Source", group="RSI Settings")
rsiMALength     = input.int(14, title="MA Length", group="Boll Settings")
rsiBollMult     = input.float(2.0, minval=0.001, maxval=50, title="Boll StdDev", group="Boll Settings")
showBreakout    = input.bool(true, title="Show Breakout", group="RSI Settings")
rsiDivBreakLow  = input.float(1.0, minval=0.001, maxval=3, title="Breakout Value Low", group="RSI Settings")
rsiDivBreakHigh = input.float(1.3, minval=0.001, maxval=3, title="Breakout Value High", group="RSI Settings")
rsiRawBreak     = input.int(25, minval = 1, title = "RSI Raw Breakout Value", group = "RSI Settings")

// === Input C MACD ===
macdFastLength      = input(12, title="Fast Length", group="MACD Settings")
macdSlowLength      = input(26, title="Slow Length", group="MACD Settings")
macdSignalLength    = input(9, title="Signal Length", group="MACD Settings")

// === Input D SMI ===
smiLengthK     = input.int(10, "%K Length",  minval = 1, maxval = 150)
smiLengthD     = input.int(3,  "%D Length",  minval = 1, maxval = 50)
smiLengthEMA   = input.int(8,  "EMA Length", minval = 1, maxval = 50)
smiOversold    = - 40
smiOverbought  =   40

// ##################
// === Indicators ===
// ##################

// === Indicator A TD Sequential ===
[setup, direction] = tdSetup()
td9_down = setup == 9
td9_up = setup == -9
tdSignal = td9_down or td9_up

// === Indicator B RSI ===
up          = ta.rma(math.max(ta.change(rsiSource), 0), rsiLength)
down        = ta.rma(-math.min(ta.change(rsiSource), 0), rsiLength)
rsi         = down == 0 ? 50 : up == 0 ? -50 : 50 - (100 / (1 + up / down))
rsiMA       = ta.sma(rsi, rsiMALength)
rsiDiv      = (rsi - rsiMA) / (ta.stdev(rsi, rsiMALength) * rsiBollMult)
rsiBreak_up    = false
rsiBreak_down  = false

if rsiDiv <= -rsiDivBreakLow and rsiDiv >= -rsiDivBreakHigh and rsi <= -rsiRawBreak and showBreakout
    rsiBreak_down := true

if rsiDiv >= rsiDivBreakLow and rsiDiv <= rsiDivBreakHigh and rsi >= rsiRawBreak and showBreakout
    rsiBreak_up := true

rsiSignal = rsiBreak_down or rsiBreak_up

// === Indicator C MACD ===
[macdLine, signalLine, histLine] = ta.macd(close, fastLength, slowLength, signalLength)
diffHist = histLine - histLine[1]

macdCross_up = ta.crossover(macdLine, signalLine)
macdCross_down = ta.crossunder(macdLine, signalLine)
macdSignal = macdCross_down or macdCross_up

// === Indicator D SMI ===
highestHigh         = ta.highest(lengthK)
lowestLow           = ta.lowest(lengthK)
highestLowestRange  = highestHigh - lowestLow
relativeRange       = close - (highestHigh + lowestLow) / 2
smi                 = 200 * (emaEma(relativeRange, lengthD) / emaEma(highestLowestRange, lengthD))
smiEMA              = ta.ema(smi, lengthEMA)
smiDiff             = smi - smiEMA
smiDiv              = smiDiff - smiDiff[1]

smiBreak_up = ta.crossover(smi, smiEMA)
smiBreak_down = ta.crossunder(smi, smiEMA)
smiSignal = smiBreak_down or smiBreak_up

// ##########################
// === Observation Window ===
// ##########################
// Observation window
var int observationWindow = 0

if tdSignal
    observationWindow := 8
else if observationWindow > 0
    observationWindow := observationWindow - 1

// ##################
// === Conditions ===
// ##################

var bool LongEntry = false
var bool ShortEntry = false

if observationWindow > 0
    if (macdCross_up or smiBreak_up or rsiBreak_up) and td9_up
        LongEntry := true
        observationWindow := 0
    else if (macdCross_down or smiBreak_down or rsiBreak_down) and td9_down
        ShortEntry := true
        observationWindow := 0


// #######################
// === Risk Management ===
// #######################

per(pcnt) =>
    strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)

q1=input.int(title=" qty_percent1", defval=25, minval=1)
q2=input.int(title=" qty_percent2", defval=25, minval=1)
q3=input.int(title=" qty_percent3", defval=25, minval=1)



// === Stop-loss ===
stoploss = input.float(title="Stop Loss", defval = 0.02, minval = 0.01)
los = per(stoploss)

// === Take-profit ===
tp1=input.float(title=" Take profit1", defval=3, minval=0.01)
tp2=input.float(title=" Take profit2", defval=5, minval=0.01)
tp3=input.float(title=" Take profit3", defval=7, minval=0.01)
tp4=input.float(title=" Take profit4", defval=10, minval=0.01)



// #######################
// === Order Execution ===
// #######################

// === Execute long entry ===
if LongEntry 
    strategy.order(id = "Long", strategy.long, qty = _qty)
    strategy.exit("LongStop", "Long", loss = los)

if ShortEntry 
    strategy.order(id = "Short", strategy.short, qty = _qty)
    strategy.exit("ShortStop", "Short", loss = los)

if direction != direction[1]
    strategy.order(id = "Long", strategy.short, qty_percent = 100)

if direction != direction[1]
    strategy.order(id = "Short", strategy.long, qty_percent = 100)

Overview

TD RSI Strategy allows long, short, or both directions and sizes orders from a percentage of equity. Inputs set RSI and MACD lengths, SMI smoothing, breakout thresholds, a stop loss, and four take-profit levels with partial quantities. It draws on the price chart. The provided code ends before the entry and exit conditions, so those rules are not fully visible.

Details

Published by

zhuzp98 on GitHub

Code credit

rhapsodyz, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Oscillators & momentum, Breakout

Markets

Crypto

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
Strategy DirectionstringlongStrategy Direction
Equity Usage Percentagefloat0.9equityUsage
RSI Lengthint14rsiLength
RSI Sourcesourcehlc3rsiSource
MA Lengthint14rsiMALength
Boll StdDevfloat2.0rsiBollMult
Show BreakoutbooltrueshowBreakout
Breakout Value Lowfloat1.0rsiDivBreakLow
Breakout Value Highfloat1.3rsiDivBreakHigh
RSI Raw Breakout Valueint25rsiRawBreak
Fast Lengthint12macdFastLength
Slow Lengthint26macdSlowLength
Show all 24 settings
SettingTypeDefaultVariable
Signal Lengthint9macdSignalLength
%K Lengthint10smiLengthK
%D Lengthint3smiLengthD
EMA Lengthint8smiLengthEMA
qty_percent1int25q1
qty_percent2int25q2
qty_percent3int25q3
Stop Lossfloat0.02stoploss
Take profit1float3tp1
Take profit2float5tp2
Take profit3float7tp3
Take profit4float10tp4
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

257 stars

The ESH2023 5M strategy is a Pine Script v5 indicator for E-mini S&P 500 futures trading on the 5-minute chart. It calculates a Stochastic oscillator from Ichimoku cloud high/low averages using inputs for K period, D period, and smoothing. The script signals l

Strategy v5 Oscillators & momentumBreakout Repaints
Updated 6 weeks ago · None stated GitHub repository of ESH2023 5M - No repaint V1.1
106 stars

Calculates a momentum squeeze using Bollinger Bands and Keltner Channels alongside a trend-filtering moving average. It generates long and short entries based on squeeze momentum bar conditions and an optional pre-squeeze dot count filter. Exits can trigger on

Strategy v5 Oscillators & momentumVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of Athena Momentum Squeeze - Autoview

Bollinger bands examples

by tradingstrategy-ai
53 stars

This strategy plots exponential-moving-average Bollinger bands on the price chart and calculates RSI. It opens a long position when close crosses above the upper band while RSI is at or above a threshold, the date filter allows trading, and no position is open

Strategy v5 Volatility & bandsOscillators & momentum
Updated 3 years ago · None stated GitHub repository of Bollinger bands examples
53 stars

This strategy enters long or short on the price chart when price is on the correct side of a 200-period EMA, MACD agrees, RSI is not at the opposing extreme, ADX exceeds a threshold, volume beats a 20-bar average, and close breaks the recent high or low. A tim

Strategy v6 TrendOscillators & momentum
Updated 2 months ago · MPL-2.0 GitHub repository of BTCUSD 5M Optimized Strategy

ADA4H Optuna Strategy

by skywalker0803r
42 stars

This strategy trades longs and shorts on the price chart. Long entries require a close above the prior Donchian high, a close above a long-term SMA, and RSI above a threshold, with size set as a percentage of equity. Long exits use a stop at the prior Donchian

Strategy v5 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of ADA4H Optuna Strategy

Morning Scalp

by benso87
24 stars

This strategy tracks an opening session time range to establish directional bias and triggers pullback trades using Stochastic RSI. Once price breaks out of the initial range, it establishes a directional bias and enters when the Stochastic RSI crosses over in

Strategy v5 Sessions & timeBreakout
Updated 4 years ago · MPL-2.0 GitHub repository of Morning Scalp

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