Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Delta-RSI Strategy (with filters)

A Pine Script v4 strategy built on RSI (close, 21), EMA (drsi, 9) and Crossover (drsi, 0.0). It has 7 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade is one contract and pays no commission. 30 settings; defaults include Polynomial Order 3, RSI Length 21 and Length ( > Order) 50.

Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.

Does Delta-RSI Strategy (with filters) repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 21 of 21 trades.
How did Delta-RSI Strategy (with filters) do on BTCUSDT 1D with default settings?
−28.82%
From 26 Jan 2024 to 21 Oct 2026, over 71 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Delta-RSI Strategy (with filters) be converted to Pine Script v5?
Yes
The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
What alerts does Delta-RSI Strategy (with filters) have?
4
"D-RSI Long " + syminfo.tickerid; "D-RSI Short " + syminfo.tickerid; "D-RSI Exit Long " + syminfo.tickerid; "D-RSI Exit Short " + syminfo.tickerid.
Does Delta-RSI Strategy (with filters) use a stop loss?
Yes
strategy.exit sets a stop on line 349, 351.

BTCUSDT · 1D · default settings

  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (30)
50,00075,000100,000125,000AprJulOct2025AprJulOct2026AprJulOct$72,237$202,527Equity from $100,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. Zeal Terminal's engine currently reads an order side written as true, false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 337, 340) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
Net profit
−28.82%
−$28,819.20
Buy and hold
+102.5%
same period
Closed trades
71
31 won · 40 lost
Profitable
43.7%
of closed trades
Profit factor
0.85
gross profit ÷ gross loss
Max drawdown
83.81%
−$98,362.10

One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A short position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.

Review

What a careful reader of this script would point out, found by checking the source and the backtest.

  • Likely bug

    rsi(close, 14) ignores the settings line 306

    Line 306 hard-codes 14 where line 290 uses “RSI Length”. Changing those settings moves one band but not this one.

    rsi(close,14)rsi(close, rsi_l)
  • Likely bug

    rsi(close, 14) ignores the settings line 306

    Line 306 hard-codes 14 where line 290 uses “RSI Length”. Changing those settings moves one band but not this one.

    rsi(close,14)rsi(close, rsi_l)
  • Check

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Note

    8 settings have no label

    In the settings dialog usevol (line 245), useatr (line 252), usersi (line 259), rsitrhs1 (line 261), fixedstart (line 276), backtest_start (line 278), fixedend (line 282), backtest_end (line 284) show an empty name. The labels on this page come from the variable names.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

  • Note

    Uses transp =, which v5 removed line 330

    transp = on line 330, 331, 332, 333, 334. v5 folds the transparency into the colour with color.new(c, transp).

Upgrade and export

Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.

  • Upgrading to v5 renames pow → math.pow, sqrt → math.sqrt, rsi → ta.rsi, ema → ta.ema, crossover → ta.crossover, crossunder → ta.crossunder, atr → ta.atr, sma → ta.sma, valuewhen → ta.valuewhen, sign → math.sign, max → math.max, min → math.min.

v4 → v5

VerifiedDownload the v5 script

Same 71 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 29: //@version=4 → //@version=5
  • Line 86: pow → math.pow
  • Line 87: sqrt → math.sqrt
  • Line 178: pow → math.pow
  • Line 180: sqrt → math.sqrt
  • Line 199: pow → math.pow
53 more edits
  • Line 210: pow → math.pow
  • Line 216: input(type = input.integer) → input.int()
  • Line 218: input(type = input.integer) → input.int()
  • Line 221: input(type = input.integer) → input.int()
  • Line 223: input(type = input.integer) → input.int()
  • Line 226: input(type = input.bool) → input.bool()
  • Line 228: input(type = input.bool) → input.bool()
  • Line 230: input(type = input.string) → input.string()
  • Line 233: input(type = input.string) → input.string()
  • Line 236: input(type = input.string) → input.string()
  • Line 239: input(type = input.bool) → input.bool()
  • Line 241: input(type = input.bool) → input.bool()
  • Line 243: input(type = input.bool) → input.bool()
  • Line 245: input(type = input.bool) → input.bool()
  • Line 247: input(type = input.integer) → input.int()
  • Line 249: input(type = input.integer) → input.int()
  • Line 252: input(type = input.bool) → input.bool()
  • Line 254: input(type = input.integer) → input.int()
  • Line 256: input(type = input.integer) → input.int()
  • Line 259: input(type = input.bool) → input.bool()
  • Line 261: input(type = input.integer) → input.int()
  • Line 263: input(type = input.integer) → input.int()
  • Line 266: input(type = input.bool) → input.bool()
  • Line 268: input(type = input.float) → input.float()
  • Line 270: input(type = input.bool) → input.bool()
  • Line 272: input(type = input.bool) → input.bool()
  • Line 274: input(type = input.float) → input.float()
  • Line 276: input(type = input.bool) → input.bool()
  • Line 278: input(type = input.time) → input.time()
  • Line 282: input(type = input.bool) → input.bool()
  • Line 284: input(type = input.time) → input.time()
  • Line 290: rsi → ta.rsi
  • Line 292: ema → ta.ema
  • Line 296: crossover → ta.crossover
  • Line 297: crossunder → ta.crossunder
  • Line 298: crossover → ta.crossover
  • Line 299: crossunder → ta.crossunder
  • Line 306: rsi → ta.rsi
  • Line 306: rsi → ta.rsi
  • Line 307: atr → ta.atr
  • Line 307: atr → ta.atr
  • Line 308: sma → ta.sma
  • Line 320: valuewhen → ta.valuewhen
  • Line 321: sign → math.sign
  • Line 327: max → math.max
  • Line 329: min → math.min
  • Line 330: transp = 100 → color.new(color.blue, 100)
  • Line 331: transp = 100 → color.new(color.red, 100)
  • Line 332: transp = 100 → color.new(color.white, 100)
  • Line 333: transp = istp?70:100 → color.new(color.green, istp?70:100)
  • Line 334: transp = issl?70:100 → color.new(color.red, issl?70:100)
  • Line 337: strategy.entry(…, true) → strategy.entry(…, strategy.long)
  • Line 340: strategy.entry(…, false) → strategy.entry(…, strategy.short)
⋯// -//@version=4+//@version=5strategy(title="Delta-RSI Strategy with Filters", shorttitle = "D-RSI with filters", overlay = true)⋯    for i = 0 to _n-1-        _norm := _norm + pow(array.get(_X,i),2)+        _norm := _norm + math.pow(array.get(_X,i),2)-    sqrt(_norm)+    math.sqrt(_norm)qr_diag(_A,_nrows,_ncolumns) => ⋯        for i = 0 to _N-1-            _mse := _mse + pow(array.get(_x,i) - array.get(_xhat,i),2)/_N+            _mse := _mse + math.pow(array.get(_x,i) - array.get(_xhat,i),2)/_N        _xmean = array.sum(_x)/_N-        _nrmse := sqrt(_mse) /_xmean+        _nrmse := math.sqrt(_mse) /_xmean    _nrmse⋯        for j = 0 to _degree-            matrix_set(_J,pow(i,j),i,j,_window)+            matrix_set(_J,math.pow(i,j),i,j,_window)    // Vector of raw datapoints:⋯    for i = 1 to _degree-        _diff := _diff + i*array.get(_a_coef,i)*pow(_window-1,i-1)+        _diff := _diff + i*array.get(_a_coef,i)*math.pow(_window-1,i-1)    // Calculates data estimate (needed for rmse)⋯/// --- main ----degree = input(title="Polynomial Order", group = "Model Parameters:",+degree = input.int(title="Polynomial Order", group = "Model Parameters:",-              inline = "linepar1", type = input.integer, defval=3, minval = 1)+              inline = "linepar1", defval=3, minval = 1)-rsi_l = input(title = "RSI Length", group = "Model Parameters:", +rsi_l = input.int(title = "RSI Length", group = "Model Parameters:", -              inline = "linepar1", type = input.integer, defval = 21, minval = 1,+              inline = "linepar1", defval = 21, minval = 1,              tooltip="The period length of RSI that is used as input.")-window = input(title="Length ( > Order)", group = "Model Parameters:",+window = input.int(title="Length ( > Order)", group = "Model Parameters:",-              inline = "linepar2", type = input.integer, defval=50, minval = 2)+              inline = "linepar2", defval=50, minval = 2)-signalLength = input(title="Signal Length", group = "Model Parameters:",+signalLength = input.int(title="Signal Length", group = "Model Parameters:",-              inline = "linepar2", type=input.integer, defval=9,+              inline = "linepar2", defval=9,              tooltip="The signal line is a EMA of the D-RSI time series.")-islong = input(title = "Long", group = "Allowed Entries:",+islong = input.bool(title = "Long", group = "Allowed Entries:",-              inline = "lineent",type = input.bool, defval = true)+              inline = "lineent", defval = true)-isshort = input(title = "Short", group = "Allowed Entries:",+isshort = input.bool(title = "Short", group = "Allowed Entries:",-              inline = "lineent", type = input.bool, defval= true)+              inline = "lineent", defval= true)-buycond = input(title="Buy", group = "Entry and Exit Conditions:", +buycond = input.string(title="Buy", group = "Entry and Exit Conditions:", -              inline = "linecond",type = input.string, defval="Signal Line Crossing", +              inline = "linecond", defval="Signal Line Crossing",               options=["Zero-Crossing", "Signal Line Crossing","Direction Change"])-sellcond = input(title="Sell", group = "Entry and Exit Conditions:", +sellcond = input.string(title="Sell", group = "Entry and Exit Conditions:", -              inline = "linecond",type = input.string, defval="Signal Line Crossing", +              inline = "linecond", defval="Signal Line Crossing",               options=["Zero-Crossing", "Signal Line Crossing","Direction Change"])-endcond = input(title="Exit", group = "Entry and Exit Conditions:", +endcond = input.string(title="Exit", group = "Entry and Exit Conditions:", -              inline = "linecond",type = input.string, defval="Signal Line Crossing", +              inline = "linecond", defval="Signal Line Crossing",               options=["Zero-Crossing", "Signal Line Crossing","Direction Change"])-filterlong =input(title = "Long Entries", inline = 'linefilt', group = 'Apply Filters to', -               type = input.bool, defval = true)+filterlong =input.bool(title = "Long Entries", inline = 'linefilt', group = 'Apply Filters to', defval = true)-filtershort =input(title = "Short Enties", inline = 'linefilt', group = 'Apply Filters to', -               type = input.bool, defval = true)+filtershort =input.bool(title = "Short Enties", inline = 'linefilt', group = 'Apply Filters to', defval = true)-filterend =input(title = "Exits", inline = 'linefilt', group = 'Apply Filters to', -               type = input.bool, defval = true)+filterend =input.bool(title = "Exits", inline = 'linefilt', group = 'Apply Filters to', defval = true)-usevol =input(title = "", inline = 'linefiltvol', group = 'Relative Volume Filter:', -               type = input.bool, defval = false)+usevol =input.bool(title = "", inline = 'linefiltvol', group = 'Relative Volume Filter:', defval = false)-rvol = input(title = "Volume >", inline = 'linefiltvol', group = 'Relative Volume Filter:', -               type = input.integer, defval = 1)+rvol = input.int(title = "Volume >", inline = 'linefiltvol', group = 'Relative Volume Filter:', defval = 1)-len_vol = input(title = "Avg. Volume Over Period", inline = 'linefiltvol', group = 'Relative Volume Filter:', -               type = input.integer, defval = 30, minval = 1,+len_vol = input.int(title = "Avg. Volume Over Period", inline = 'linefiltvol', group = 'Relative Volume Filter:', defval = 30, minval = 1,               tooltip="The current volume must be greater than N times the M-period average volume.")-useatr =input(title = "", inline = 'linefiltatr', group = 'Volatility Filter:', -               type = input.bool, defval = false)+useatr =input.bool(title = "", inline = 'linefiltatr', group = 'Volatility Filter:', defval = false)-len_atr1 = input(title = "ATR", inline = 'linefiltatr', group = 'Volatility Filter:', -               type = input.integer, defval = 5, minval = 1)+len_atr1 = input.int(title = "ATR", inline = 'linefiltatr', group = 'Volatility Filter:', defval = 5, minval = 1)-len_atr2 = input(title = "> ATR", inline = 'linefiltatr', group = 'Volatility Filter:', -               type = input.integer, defval = 30, minval = 1,+len_atr2 = input.int(title = "> ATR", inline = 'linefiltatr', group = 'Volatility Filter:', defval = 30, minval = 1,               tooltip="The N-period ATR must be greater than the M-period ATR.")-usersi =input(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:', -               type = input.bool, defval = false)+usersi =input.bool(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:', defval = false)-rsitrhs1 = input(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:', -               type = input.integer, defval = 0, minval=0, maxval=100)+rsitrhs1 = input.int(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:', defval = 0, minval=0, maxval=100)-rsitrhs2 = input(title = "< RSI (14) <", inline = 'linersi', group = 'Overbought/Oversold Filter:', -               type = input.integer, defval = 100, minval=0, maxval=100,+rsitrhs2 = input.int(title = "< RSI (14) <", inline = 'linersi', group = 'Overbought/Oversold Filter:', defval = 100, minval=0, maxval=100,               tooltip="RSI(14) must be in the range between N and M.")-issl =  input(title = "SL", inline = 'linesl1', group = 'Stop Loss / Take Profit:', -               type = input.bool, defval = false)+issl =  input.bool(title = "SL", inline = 'linesl1', group = 'Stop Loss / Take Profit:', defval = false)-slpercent =  input(title = ", %", inline = 'linesl1', group = 'Stop Loss / Take Profit:', -               type = input.float, defval = 10, minval=0.0)+slpercent =  input.float(title = ", %", inline = 'linesl1', group = 'Stop Loss / Take Profit:', defval = 10, minval=0.0)-istrailing =  input(title = "Trailing", inline = 'linesl1', group = 'Stop Loss / Take Profit:', -               type = input.bool, defval = false)+istrailing =  input.bool(title = "Trailing", inline = 'linesl1', group = 'Stop Loss / Take Profit:', defval = false)-istp =  input(title = "TP", inline = 'linetp1', group = 'Stop Loss / Take Profit:', -               type = input.bool, defval = false)+istp =  input.bool(title = "TP", inline = 'linetp1', group = 'Stop Loss / Take Profit:', defval = false)-tppercent =  input(title = ", %", inline = 'linetp1', group = 'Stop Loss / Take Profit:', -               type = input.float, defval = 20)+tppercent =  input.float(title = ", %", inline = 'linetp1', group = 'Stop Loss / Take Profit:', defval = 20)-fixedstart =input(title="", group = "Fixed Backtest Period Start/End Dates:",+fixedstart =input.bool(title="", group = "Fixed Backtest Period Start/End Dates:",-              inline = "linebac1", type = input.bool, defval = true)+              inline = "linebac1", defval = true)-backtest_start=input(title = "", type = input.time, inline = "linebac1", +backtest_start=input.time(title = "", inline = "linebac1",               group = "Fixed Backtest Period Start/End Dates:",⋯              tooltip="If deactivated, backtest staring from the first available price bar.")-fixedend =  input(title="", group = "Fixed Backtest Period Start/End Dates:",+fixedend =  input.bool(title="", group = "Fixed Backtest Period Start/End Dates:",-              inline = "linebac2", type = input.bool, defval = false)+              inline = "linebac2", defval = false)-backtest_end =input(title = "", type = input.time, inline = "linebac2", +backtest_end =input.time(title = "", inline = "linebac2",               group = "Fixed Backtest Period Start/End Dates:",⋯    window := degree+1-src = rsi(close,rsi_l)+src = ta.rsi(close,rsi_l)[drsi,nrmse] = diff(src,window,degree)-signalline = ema(drsi, signalLength)+signalline = ta.ema(drsi, signalLength)// Conditions for D-RSI⋯dirchangedw = (drsi<drsi[1]) and (drsi[1]>drsi[2]) and drsi[1]>0.0-crossup = crossover(drsi,0.0)+crossup = ta.crossover(drsi,0.0)-crossdw = crossunder(drsi,0.0)+crossdw = ta.crossunder(drsi,0.0)-crosssignalup = crossover(drsi,signalline)+crosssignalup = ta.crossover(drsi,signalline)-crosssignaldw = crossunder(drsi,signalline)+crosssignaldw = ta.crossunder(drsi,signalline)// D-RSI signals⋯// Filters-rsifilter = usersi?(rsi(close,14) > rsitrhs1 and rsi(close,14) < rsitrhs2):true+rsifilter = usersi?(ta.rsi(close,14) > rsitrhs1 and ta.rsi(close,14) < rsitrhs2):true-volatilityfilter = useatr?(atr(len_atr1) > atr(len_atr2)):true+volatilityfilter = useatr?(ta.atr(len_atr1) > ta.atr(len_atr2)):true-volumefilter = usevol?(volume > rvol*sma(volume,len_vol)):true+volumefilter = usevol?(volume > rvol*ta.sma(volume,len_vol)):truetotalfilter = volatilityfilter and volumefilter and rsifilter⋯// Entry price / Take profit / Stop Loss-startprice = valuewhen(condition=golong or goshort, source=close, occurrence=0)+startprice = ta.valuewhen(condition=golong or goshort, source=close, occurrence=0)-pm = golong?1:goshort?-1:1/sign(strategy.position_size)+pm = golong?1:goshort?-1:1/math.sign(strategy.position_size)takeprofit = startprice*(1+pm*tppercent*0.01)⋯if istrailing and strategy.position_size>0-    stoploss := max(close*(1 - slpercent*0.01),stoploss[1])+    stoploss := math.max(close*(1 - slpercent*0.01),stoploss[1])else if istrailing and strategy.position_size<0-    stoploss := min(close*(1 + slpercent*0.01),stoploss[1])+    stoploss := math.min(close*(1 + slpercent*0.01),stoploss[1])-tpline = plot(takeprofit,color=color.blue,transp=100, title="TP")+tpline = plot(takeprofit,color=color.new(color.blue, 100), title="TP")-slline = plot(stoploss,  color=color.red, transp=100, title="SL")+slline = plot(stoploss,  color=color.new(color.red, 100), title="SL")-p1 = plot(close,transp=100,color=color.white, title="Dummy Close")+p1 = plot(close,color=color.new(color.white, 100), title="Dummy Close")-fill(p1, tpline, color=color.green, transp=istp?70:100, title="TP")+fill(p1, tpline, color=color.new(color.green, istp?70:100), title="TP")-fill(p1, slline, color=color.red,   transp=issl?70:100, title="SL")+fill(p1, slline, color=color.new(color.red, issl?70:100), title="SL")// Backtest: Basic Entry and Exit Conditionsif golong and isinrange and islong-    strategy.entry("long",   true )+    strategy.entry("long",   strategy.long )    alert("D-RSI Long " + syminfo.tickerid, alert.freq_once_per_bar_close) if goshort and isinrange and isshort-    strategy.entry("short",  false)+    strategy.entry("short",  strategy.short)    alert("D-RSI Short " + syminfo.tickerid, alert.freq_once_per_bar_close) ⋯

Clean v5

Verified

Nothing to change.

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 71 before, 58 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// -//@version=5+//@version=6strategy(title="Delta-RSI Strategy with Filters", shorttitle = "D-RSI with filters", overlay = true)⋯

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Model Parameters:
Polynomial Order3int (written input.integer) · min 1window drsi nrmse line 288
RSI LengthThe period length of RSI that is used as input.21int (written input.integer) · min 1src
Length ( > Order)50int (written input.integer) · min 2drsi nrmse line 288
Signal LengthThe signal line is a EMA of the D-RSI time series.9int (written input.integer)signalline
Allowed Entries:
Longtrueboolgolong entry long line 336
Shorttrueboolgoshort entry short line 339
Entry and Exit Conditions:
BuySignal Line Crossingstring · options ["Zero-Crossing", "Signal Line Crossing","Direction Change"]drsilong
SellSignal Line Crossingstring · options ["Zero-Crossing", "Signal Line Crossing","Direction Change"]drsishort
ExitSignal Line Crossingstring · options ["Zero-Crossing", "Signal Line Crossing","Direction Change"]drisendlong drisendshort
Apply Filters to
Long Entriestrueboolgolong
Short Entiestrueboolgoshort
Exitstrueboolendlong endshort
Relative Volume Filter:
Usevol (no label in the script)falseboolvolumefilter
Volume >1int (written input.integer)volumefilter
Avg. Volume Over PeriodThe current volume must be greater than N times the M-period average volume.30int (written input.integer) · min 1volumefilter
Volatility Filter:
Useatr (no label in the script)falseboolvolatilityfilter
ATR5int (written input.integer) · min 1volatilityfilter
> ATRThe N-period ATR must be greater than the M-period ATR.30int (written input.integer) · min 1volatilityfilter
Overbought/Oversold Filter:
Usersi (no label in the script)falseboolrsifilter
Rsitrhs1 (no label in the script)0int (written input.integer) · min 0 · max 100rsifilter
< RSI (14) <RSI(14) must be in the range between N and M.100int (written input.integer) · min 0 · max 100rsifilter
Stop Loss / Take Profit:
SLfalseboolSL exit sl/tp long exit sl/tp short
, %10float · min 0.0stoploss
Trailingfalseboolline 326 line 328
TPfalseboolTP exit sl/tp long exit sl/tp short
, %20floattakeprofit
Fixed Backtest Period Start/End Dates:
Fixedstart (no label in the script)trueboolisinrange
Backtest start (no label in the script)If deactivated, backtest staring from the first available price bar.timestamp("01 Jan 2017 13:30 +0000")timeisinrange
Fixedend (no label in the script)falseboolisinrange
Backtest end (no label in the script)If deactivated, backtesting ends at the last available price bar.timestamp("30 Dec 2080 23:30 +0000")timeisinrange

What it calculates

  • RSI (rsi, ta.rsi in v5)close, RSI Length (21)src · line 290
  • EMA (ema, ta.ema in v5)drsi, Signal Length (9)signalline · line 292
  • Crossover (crossover, ta.crossover in v5)drsi, 0.0crossup · line 296
  • Crossunder (crossunder, ta.crossunder in v5)drsi, 0.0crossdw · line 297
  • Crossover (crossover, ta.crossover in v5)drsi, signallinecrosssignalup · line 298
  • Crossunder (crossunder, ta.crossunder in v5)drsi, signallinecrosssignaldw · line 299
  • RSI (rsi, ta.rsi in v5)close, 14rsifilter · line 306
  • ATR (atr, ta.atr in v5)ATR (5)volatilityfilter · line 307
  • SMA (sma, ta.sma in v5)volume, Avg. Volume Over Period (30)volumefilter · line 308

Signal flow

How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.

The script has 75 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open long longgolong and isinrange and islongOn337
Open short shortgoshort and isinrange and isshortOn340
Close longendlongOn343
Close shortendshortOn346
Exit sl/tp long stop and limitevery barOn349
Exit sl/tp short stop and limitevery barOn351
Close (not isinrange)On355

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Alerts

AlertCallMessageLine
(no title)alert"D-RSI Long " + syminfo.tickerid338
(no title)alert"D-RSI Short " + syminfo.tickerid341
(no title)alert"D-RSI Exit Long " + syminfo.tickerid344
(no title)alert"D-RSI Exit Short " + syminfo.tickerid347

Does it repaint?

No

No repainting patterns in the source, and the live replay matched history.

21/21trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Other markets

The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D−28.8%+102.5%7144%0.8583.8%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−2.3%+5.5%7342%0.9614.1%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−1.7%+9.8%7738%0.844.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+0.4%+8.4%5947%1.270.7%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−0.2%+16.7%7747%0.750.3%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.0%+21.5%7139%1.090.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−0.4%+148.3%7547%0.790.9%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+0.1%+17.1%6740%1.220.2%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market2148%$9,745.74
Sideways market3732%−$92,487.20
Falling market1369%$53,922.20

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

81.8%

The 95th percentile of the worst drawdown when the same 71 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 55.0% to 81.8%; the tick is what actually happened, 81.9%. Order luck alone moves it this much.

0%94%
All 71 trades
SideEntryExitBarsP&L
long24 Apr 2024 66,414.0025 Apr 2024 64,289.601−$2,124.42
short25 Apr 2024 64,289.604 May 2024 62,882.009$1,407.57
long4 May 2024 62,882.0015 May 2024 61,577.5011−$1,304.52
short15 May 2024 61,577.5016 May 2024 66,206.501−$4,629.02
long16 May 2024 66,206.5025 May 2024 68,550.009$2,343.48
short25 May 2024 68,550.0026 Jun 2024 61,806.0032$6,743.98
long26 Jun 2024 61,806.0025 Jul 2024 65,376.0029$3,570.00
short25 Jul 2024 65,376.0012 Aug 2024 58,712.6018$6,663.42
long12 Aug 2024 58,712.6031 Aug 2024 59,124.0019$411.40
short31 Aug 2024 59,124.0014 Sep 2024 60,498.0014−$1,374.00
long14 Sep 2024 60,498.001 Oct 2024 63,327.6017$2,829.61
short1 Oct 2024 63,327.6015 Oct 2024 66,084.0014−$2,756.40
long15 Oct 2024 66,084.0028 Oct 2024 68,021.7013$1,937.69
short28 Oct 2024 68,021.7030 Oct 2024 72,736.402−$4,714.72
long30 Oct 2024 72,736.401 Nov 2024 70,292.002−$2,444.40
short1 Nov 2024 70,292.0011 Nov 2024 80,370.0010−$10,078.00
long11 Nov 2024 80,370.0025 Nov 2024 97,900.1014$17,530.00
short25 Nov 2024 97,900.109 Dec 2024 101,110.0014−$3,209.55
long9 Dec 2024 101,110.0024 Dec 2024 94,881.5015−$6,228.13
short24 Dec 2024 94,881.503 Jan 2025 96,984.8010−$2,103.32
long3 Jan 2025 96,984.8025 Jan 2025 104,871.0022$7,885.72
short25 Jan 2025 104,871.0013 Feb 2025 97,870.0019$7,000.51
long13 Feb 2025 97,870.0028 Feb 2025 84,708.6015−$13,161.40
short28 Feb 2025 84,708.603 Mar 2025 94,270.003−$9,561.42
long3 Mar 2025 94,270.0011 Mar 2025 78,595.908−$15,674.10
short11 Mar 2025 78,595.9015 Mar 2025 83,983.204−$5,387.33
long15 Mar 2025 83,983.2029 Mar 2025 84,424.4014$441.19
short29 Mar 2025 84,424.4012 Apr 2025 83,423.8014$1,000.55
long12 Apr 2025 83,423.802 May 2025 96,489.9020$13,066.10
short2 May 2025 96,489.9022 May 2025 109,644.0020−$13,154.10
long22 May 2025 109,644.0028 May 2025 108,938.006−$705.82
short28 May 2025 108,938.0010 Jun 2025 110,263.0013−$1,324.85
long10 Jun 2025 110,263.0023 Jun 2025 100,964.0013−$9,299.15
short23 Jun 2025 100,964.0024 Jun 2025 105,334.001−$4,370.07
long24 Jun 2025 105,334.006 Jul 2025 108,198.0012$2,864.18
short6 Jul 2025 108,198.0011 Jul 2025 116,010.005−$7,811.89
long11 Jul 2025 116,010.0020 Jul 2025 117,840.009$1,830.00
short20 Jul 2025 117,840.008 Aug 2025 117,472.0019$367.99
long8 Aug 2025 117,472.0022 Aug 2025 112,500.0014−$4,972.02
short22 Aug 2025 112,500.0023 Aug 2025 116,936.001−$4,436.00
long23 Aug 2025 116,936.0025 Aug 2025 113,494.002−$3,442.41
short25 Aug 2025 113,494.004 Sep 2025 111,706.0010$1,787.87
long4 Sep 2025 111,706.0022 Sep 2025 115,232.0018$3,526.57
short22 Sep 2025 115,232.003 Oct 2025 120,529.0011−$5,297.06
long3 Oct 2025 120,529.0011 Oct 2025 112,774.008−$7,754.86
short11 Oct 2025 112,774.0025 Oct 2025 111,005.0014$1,769.59
long25 Oct 2025 111,005.0015 Nov 2025 94,594.0021−$16,410.90
short15 Nov 2025 94,594.0026 Nov 2025 87,370.0011$7,224.03
long26 Nov 2025 87,370.0012 Dec 2025 92,513.4016$5,143.41
short12 Dec 2025 92,513.4031 Dec 2025 88,485.5019$4,027.88
long31 Dec 2025 88,485.5013 Jan 2026 91,296.2013$2,810.70
short13 Jan 2026 91,296.2014 Jan 2026 95,414.001−$4,117.79
long14 Jan 2026 95,414.0018 Jan 2026 95,147.804−$266.22
short18 Jan 2026 95,147.808 Feb 2026 69,289.4021$25,858.40
long8 Feb 2026 69,289.4028 Feb 2026 65,872.1020−$3,417.28
short28 Feb 2026 65,872.106 Apr 2026 69,034.2037−$3,162.09
long6 Apr 2026 69,034.2021 Apr 2026 75,841.0015$6,806.79
short21 Apr 2026 75,841.007 May 2026 81,447.0016−$5,606.04
long7 May 2026 81,447.0017 May 2026 78,148.1010−$3,298.96
short17 May 2026 78,148.101 Jun 2026 73,674.4015$4,473.66
long1 Jun 2026 73,674.402 Jun 2026 71,408.901−$2,265.49
short2 Jun 2026 71,408.909 Jun 2026 63,086.007$8,322.90
long9 Jun 2026 63,086.0025 Jun 2026 61,078.0016−$2,008.00
short25 Jun 2026 61,078.006 Jul 2026 63,650.0011−$2,572.01
long6 Jul 2026 63,650.009 Jul 2026 62,290.003−$1,360.00
short9 Jul 2026 62,290.0016 Jul 2026 64,756.307−$2,466.27
long16 Jul 2026 64,756.3026 Jul 2026 64,375.0010−$381.27
short26 Jul 2026 64,375.007 Aug 2026 64,323.6012$51.40
long7 Aug 2026 64,323.6030 Aug 2026 78,230.0023$13,906.40
short30 Aug 2026 78,230.0019 Sep 2026 80,883.9020−$2,653.86
long19 Sep 2026 80,883.906 Oct 2026 85,766.9017$4,883.01

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
Delta-RSI Strategy (with filters) this page—v4 strategy−28.8%7183.8%
3 x EMA + Stochastic RSI + ATR by tomimarsonema rsi sma atrv4 strategy−42.3%1844.8%
Atrend by OTS by prim722ema rsi sma atrv4 strategy+12.1%7634.4%
EMA crossover (daily TF) by tradeswithashishema sma rsi atrv5 strategy+11.0%1211.6%
[KL] Bollinger bands + RSI Strategy by DojiEmojisma atr ema rsiv4 strategy+28.2%3014.7%
3x Supertrend and Stoch RSI by M3RZIrsi sma ema atrv4 strategy−128.7%24207.6%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 56 msWith a workaround 1,000 bars in 8,412 msNot measured
PineTSNo v5 and v6 only—Not measured

Zeal Terminal's engine currently reads an order side written as true, false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 337, 340) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © tbiktag//// Delta-RSI Oscillator Strategy With Filters//// This is a version of the Delta-RSI Oscillator Strategy compatible with // the Strategy Tester.//// This version also allows filtering the trade signals generated by Delts-RSI// by means of volatility (defined by ATR), relative volume and RSI(14).//// Delta-RSI (© tbiktag) is a smoothed time derivative of the RSI designed// as a momentum indicator. For the original publication, see link below:// https://www.tradingview.com/script/OXQVFTQD-Delta-RSI-Oscillator/// // D-RSI model parameters:// RSI Length: The timeframe of the RSI that serves as an input to D-RSI.// Frame Length: The length of the lookback frame used for local regression.// Polynomial Order: The order of the local polynomial function used to interpolate // the RSI.// Trade signals are generated based on three optional conditions:// - Zero-crossing: bullish when D-RSI crosses zero from negative to positive // values (bearish otherwise)// - Signal Line Crossing: bullish when D-RSI crosses from below to above the signal // line (bearish otherwise)// - Direction Change: bullish when D-RSI was negative and starts ascending // (bearish otherwise)// //@version=4strategy(title="Delta-RSI Strategy with Filters", shorttitle = "D-RSI with filters", overlay = true)// ---Subroutines---matrix_get(_A,_i,_j,_nrows) =>    // Get the value of the element of an implied 2d matrix    //input:     // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]]    // _i :: integer: row number    // _j :: integer: column number    // _nrows :: integer: number of rows in the implied 2d matrix    array.get(_A,_i+_nrows*_j)matrix_set(_A,_value,_i,_j,_nrows) =>    // Set a value to the element of an implied 2d matrix    //input:     // _A :: array, changed on output: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]]    // _value :: float: the new value to be set    // _i :: integer: row number    // _j :: integer: column number    // _nrows :: integer: number of rows in the implied 2d matrix    array.set(_A,_i+_nrows*_j,_value)transpose(_A,_nrows,_ncolumns) =>    // Transpose an implied 2d matrix    // input:    // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]]    // _nrows :: integer: number of rows in _A    // _ncolumns :: integer: number of columns in _A    // output:    // _AT :: array: pseudo 2d matrix with implied dimensions: _ncolums x _nrows    var _AT = array.new_float(_nrows*_ncolumns,0)    for i = 0 to _nrows-1        for j = 0 to _ncolumns-1            matrix_set(_AT, matrix_get(_A,i,j,_nrows),j,i,_ncolumns)    _ATmultiply(_A,_B,_nrowsA,_ncolumnsA,_ncolumnsB) =>     // Calculate scalar product of two matrices    // input:     // _A :: array: pseudo 2d matrix    // _B :: array: pseudo 2d matrix    // _nrowsA :: integer: number of rows in _A    // _ncolumnsA :: integer: number of columns in _A    // _ncolumnsB :: integer: number of columns in _B    // output:    // _C:: array: pseudo 2d matrix with implied dimensions _nrowsA x _ncolumnsB    var _C = array.new_float(_nrowsA*_ncolumnsB,0)    int _nrowsB = _ncolumnsA    float elementC= 0.0    for i = 0 to _nrowsA-1        for j = 0 to _ncolumnsB-1            elementC := 0            for k = 0 to _ncolumnsA-1                elementC := elementC + matrix_get(_A,i,k,_nrowsA)*matrix_get(_B,k,j,_nrowsB)            matrix_set(_C,elementC,i,j,_nrowsA)    _Cvnorm(_X,_n) =>    //Square norm of vector _X with size _n    float _norm = 0.0    for i = 0 to _n-1        _norm := _norm + pow(array.get(_X,i),2)    sqrt(_norm)qr_diag(_A,_nrows,_ncolumns) =>     //QR Decomposition with Modified Gram-Schmidt Algorithm (Column-Oriented)    // input:    // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]]    // _nrows :: integer: number of rows in _A    // _ncolumns :: integer: number of columns in _A    // output:    // _Q: unitary matrix, implied dimenstions _nrows x _ncolumns    // _R: upper triangular matrix, implied dimansions _ncolumns x _ncolumns    var _Q = array.new_float(_nrows*_ncolumns,0)    var _R = array.new_float(_ncolumns*_ncolumns,0)    var _a = array.new_float(_nrows,0)    var _q = array.new_float(_nrows,0)    float _r = 0.0    float _aux = 0.0    //get first column of _A and its norm:    for i = 0 to _nrows-1        array.set(_a,i,matrix_get(_A,i,0,_nrows))    _r := vnorm(_a,_nrows)    //assign first diagonal element of R and first column of Q    matrix_set(_R,_r,0,0,_ncolumns)    for i = 0 to _nrows-1        matrix_set(_Q,array.get(_a,i)/_r,i,0,_nrows)    if _ncolumns != 1        //repeat for the rest of the columns        for k = 1 to _ncolumns-1            for i = 0 to _nrows-1                array.set(_a,i,matrix_get(_A,i,k,_nrows))            for j = 0 to k-1                //get R_jk as scalar product of Q_j column and A_k column:                _r := 0                for i = 0 to _nrows-1                    _r := _r + matrix_get(_Q,i,j,_nrows)*array.get(_a,i)                matrix_set(_R,_r,j,k,_ncolumns)                //update vector _a                for i = 0 to _nrows-1                    _aux := array.get(_a,i) - _r*matrix_get(_Q,i,j,_nrows)                    array.set(_a,i,_aux)            //get diagonal R_kk and Q_k column            _r := vnorm(_a,_nrows)            matrix_set(_R,_r,k,k,_ncolumns)            for i = 0 to _nrows-1                matrix_set(_Q,array.get(_a,i)/_r,i,k,_nrows)    [_Q,_R]    pinv(_A,_nrows,_ncolumns) =>    //Pseudoinverse of matrix _A calculated using QR decomposition    // Input:     // _A:: array: implied as a (_nrows x _ncolumns) matrix     //.             _A = [[column_0],[column_1],...,[column_(_ncolumns-1)]]    // Output:     // _Ainv:: array implied as a (_ncolumns x _nrows) matrix     //              _A = [[row_0],[row_1],...,[row_(_nrows-1)]]    // ----    // First find the QR factorization of A: A = QR,    // where R is upper triangular matrix.    // Then _Ainv = R^-1*Q^T.    // ----    [_Q,_R] = qr_diag(_A,_nrows,_ncolumns)    _QT = transpose(_Q,_nrows,_ncolumns)    // Calculate Rinv:    var _Rinv = array.new_float(_ncolumns*_ncolumns,0)    float _r = 0.0    matrix_set(_Rinv,1/matrix_get(_R,0,0,_ncolumns),0,0,_ncolumns)    if _ncolumns != 1        for j = 1 to _ncolumns-1            for i = 0 to j-1                _r := 0.0                for k = i to j-1                    _r := _r + matrix_get(_Rinv,i,k,_ncolumns)*matrix_get(_R,k,j,_ncolumns)                matrix_set(_Rinv,_r,i,j,_ncolumns)            for k = 0 to j-1                matrix_set(_Rinv,-matrix_get(_Rinv,k,j,_ncolumns)/matrix_get(_R,j,j,_ncolumns),k,j,_ncolumns)            matrix_set(_Rinv,1/matrix_get(_R,j,j,_ncolumns),j,j,_ncolumns)    //    _Ainv = multiply(_Rinv,_QT,_ncolumns,_ncolumns,_nrows)    _Ainvnorm_rmse(_x, _xhat) =>    // Root Mean Square Error normalized to the sample mean    // _x.   :: array float, original data    // _xhat :: array float, model estimate    // output    // _nrmse:: float    float _nrmse = 0.0    if array.size(_x) != array.size(_xhat)        _nrmse := na    else        int _N = array.size(_x)        float _mse = 0.0        for i = 0 to _N-1            _mse := _mse + pow(array.get(_x,i) - array.get(_xhat,i),2)/_N        _xmean = array.sum(_x)/_N        _nrmse := sqrt(_mse) /_xmean    _nrmse    diff(_src,_window,_degree) =>    // Polynomial differentiator    // input:    // _src:: input series    // _window:: integer: wigth of the moving lookback window    // _degree:: integer: degree of fitting polynomial    // output:    // _diff :: series: time derivative    // _nrmse:: float: normalized root mean square error    //    // Vandermonde matrix with implied dimensions (window x degree+1)    // Linear form: J = [ [z]^0, [z]^1, ... [z]^degree],     //              with z = [ (1-window)/2 to (window-1)/2 ]     var _J = array.new_float(_window*(_degree+1),0)    for i = 0 to _window-1         for j = 0 to _degree            matrix_set(_J,pow(i,j),i,j,_window)    // Vector of raw datapoints:    var _Y_raw = array.new_float(_window,na)    for j = 0 to _window-1        array.set(_Y_raw,j,_src[_window-1-j])     // Calculate polynomial coefficients which minimize the loss function    _C = pinv(_J,_window,_degree+1)    _a_coef = multiply(_C,_Y_raw,_degree+1,_window,1)    // For first derivative, approximate the last point (i.e. z=window-1) by     float _diff = 0.0    for i = 1 to _degree        _diff := _diff + i*array.get(_a_coef,i)*pow(_window-1,i-1)    // Calculates data estimate (needed for rmse)    _Y_hat = multiply(_J,_a_coef,_window,_degree+1,1)    float _nrmse = norm_rmse(_Y_raw,_Y_hat)    [_diff,_nrmse]/// --- main ---degree = input(title="Polynomial Order", group = "Model Parameters:",              inline = "linepar1", type = input.integer, defval=3, minval = 1)rsi_l = input(title = "RSI Length", group = "Model Parameters:",               inline = "linepar1", type = input.integer, defval = 21, minval = 1,              tooltip="The period length of RSI that is used as input.")window = input(title="Length ( > Order)", group = "Model Parameters:",              inline = "linepar2", type = input.integer, defval=50, minval = 2)signalLength = input(title="Signal Length", group = "Model Parameters:",              inline = "linepar2", type=input.integer, defval=9,              tooltip="The signal line is a EMA of the D-RSI time series.")islong = input(title = "Long", group = "Allowed Entries:",              inline = "lineent",type = input.bool, defval = true)isshort = input(title = "Short", group = "Allowed Entries:",              inline = "lineent", type = input.bool, defval= true)buycond = input(title="Buy", group = "Entry and Exit Conditions:",               inline = "linecond",type = input.string, defval="Signal Line Crossing",               options=["Zero-Crossing", "Signal Line Crossing","Direction Change"])sellcond = input(title="Sell", group = "Entry and Exit Conditions:",               inline = "linecond",type = input.string, defval="Signal Line Crossing",               options=["Zero-Crossing", "Signal Line Crossing","Direction Change"])endcond = input(title="Exit", group = "Entry and Exit Conditions:",               inline = "linecond",type = input.string, defval="Signal Line Crossing",               options=["Zero-Crossing", "Signal Line Crossing","Direction Change"])filterlong =input(title = "Long Entries", inline = 'linefilt', group = 'Apply Filters to',                type = input.bool, defval = true)filtershort =input(title = "Short Enties", inline = 'linefilt', group = 'Apply Filters to',                type = input.bool, defval = true)filterend =input(title = "Exits", inline = 'linefilt', group = 'Apply Filters to',                type = input.bool, defval = true)usevol =input(title = "", inline = 'linefiltvol', group = 'Relative Volume Filter:',                type = input.bool, defval = false)rvol = input(title = "Volume >", inline = 'linefiltvol', group = 'Relative Volume Filter:',                type = input.integer, defval = 1)len_vol = input(title = "Avg. Volume Over Period", inline = 'linefiltvol', group = 'Relative Volume Filter:',                type = input.integer, defval = 30, minval = 1,               tooltip="The current volume must be greater than N times the M-period average volume.")useatr =input(title = "", inline = 'linefiltatr', group = 'Volatility Filter:',                type = input.bool, defval = false)len_atr1 = input(title = "ATR", inline = 'linefiltatr', group = 'Volatility Filter:',                type = input.integer, defval = 5, minval = 1)len_atr2 = input(title = "> ATR", inline = 'linefiltatr', group = 'Volatility Filter:',                type = input.integer, defval = 30, minval = 1,               tooltip="The N-period ATR must be greater than the M-period ATR.")usersi =input(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:',                type = input.bool, defval = false)rsitrhs1 = input(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:',                type = input.integer, defval = 0, minval=0, maxval=100)rsitrhs2 = input(title = "< RSI (14) <", inline = 'linersi', group = 'Overbought/Oversold Filter:',                type = input.integer, defval = 100, minval=0, maxval=100,               tooltip="RSI(14) must be in the range between N and M.")issl =  input(title = "SL", inline = 'linesl1', group = 'Stop Loss / Take Profit:',                type = input.bool, defval = false)slpercent =  input(title = ", %", inline = 'linesl1', group = 'Stop Loss / Take Profit:',                type = input.float, defval = 10, minval=0.0)istrailing =  input(title = "Trailing", inline = 'linesl1', group = 'Stop Loss / Take Profit:',                type = input.bool, defval = false)istp =  input(title = "TP", inline = 'linetp1', group = 'Stop Loss / Take Profit:',                type = input.bool, defval = false)tppercent =  input(title = ", %", inline = 'linetp1', group = 'Stop Loss / Take Profit:',                type = input.float, defval = 20)fixedstart =input(title="", group = "Fixed Backtest Period Start/End Dates:",              inline = "linebac1", type = input.bool, defval = true)backtest_start=input(title = "", type = input.time, inline = "linebac1",               group = "Fixed Backtest Period Start/End Dates:",              defval = timestamp("01 Jan 2017 13:30 +0000"),              tooltip="If deactivated, backtest staring from the first available price bar.")fixedend =  input(title="", group = "Fixed Backtest Period Start/End Dates:",              inline = "linebac2", type = input.bool, defval = false)backtest_end =input(title = "", type = input.time, inline = "linebac2",               group = "Fixed Backtest Period Start/End Dates:",              defval = timestamp("30 Dec 2080 23:30 +0000"),              tooltip="If deactivated, backtesting ends at the last available price bar.")if window < degree    window := degree+1src = rsi(close,rsi_l)[drsi,nrmse] = diff(src,window,degree)signalline = ema(drsi, signalLength)// Conditions for D-RSIdirchangeup = (drsi>drsi[1]) and (drsi[1]<drsi[2]) and drsi[1]<0.0dirchangedw = (drsi<drsi[1]) and (drsi[1]>drsi[2]) and drsi[1]>0.0crossup = crossover(drsi,0.0)crossdw = crossunder(drsi,0.0)crosssignalup = crossover(drsi,signalline)crosssignaldw = crossunder(drsi,signalline)// D-RSI signalsdrsilong = (buycond=="Direction Change"?dirchangeup:(buycond=="Zero-Crossing"?crossup:crosssignalup)) drsishort= (sellcond=="Direction Change"?dirchangedw:(sellcond=="Zero-Crossing"?crossdw:crosssignaldw)) drisendlong = (endcond=="Direction Change"?dirchangedw:(endcond=="Zero-Crossing"?crossdw:crosssignaldw)) drisendshort= (endcond=="Direction Change"?dirchangeup:(endcond=="Zero-Crossing"?crossup:crosssignalup)) // Filtersrsifilter = usersi?(rsi(close,14) > rsitrhs1 and rsi(close,14) < rsitrhs2):truevolatilityfilter = useatr?(atr(len_atr1) > atr(len_atr2)):truevolumefilter = usevol?(volume > rvol*sma(volume,len_vol)):truetotalfilter = volatilityfilter and volumefilter and rsifilter//Filtered signalsgolong  = drsilong  and islong  and (filterlong?totalfilter:true) goshort = drsishort and isshort and (filtershort?totalfilter:true)endlong  = drisendlong and (filterend?totalfilter:true)endshort = drisendlong and (filterend?totalfilter:true)// Backtest period//backtest_start = timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)//backtest_end = timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0)isinrange = (fixedstart?time>=backtest_start:true) and (fixedend?time<=backtest_end:true)// Entry price / Take profit / Stop Lossstartprice = valuewhen(condition=golong or goshort, source=close, occurrence=0)pm = golong?1:goshort?-1:1/sign(strategy.position_size)takeprofit = startprice*(1+pm*tppercent*0.01)// fixed stop lossstoploss = startprice * (1-pm*slpercent*0.01)// trailing stop lossif istrailing and strategy.position_size>0    stoploss := max(close*(1 - slpercent*0.01),stoploss[1])else if istrailing and strategy.position_size<0    stoploss := min(close*(1 + slpercent*0.01),stoploss[1])tpline = plot(takeprofit,color=color.blue,transp=100, title="TP")slline = plot(stoploss,  color=color.red, transp=100, title="SL")p1 = plot(close,transp=100,color=color.white, title="Dummy Close")fill(p1, tpline, color=color.green, transp=istp?70:100, title="TP")fill(p1, slline, color=color.red,   transp=issl?70:100, title="SL")// Backtest: Basic Entry and Exit Conditionsif golong and isinrange and islong    strategy.entry("long",   true )    alert("D-RSI Long " + syminfo.tickerid, alert.freq_once_per_bar_close) if goshort and isinrange and isshort    strategy.entry("short",  false)    alert("D-RSI Short " + syminfo.tickerid, alert.freq_once_per_bar_close) if endlong    strategy.close("long",  alert_message="Close Long")    alert("D-RSI Exit Long " + syminfo.tickerid, alert.freq_once_per_bar_close) if endshort    strategy.close("short", alert_message="Close Short")    alert("D-RSI Exit Short " + syminfo.tickerid, alert.freq_once_per_bar_close) // Exit via SL or TPstrategy.exit(id="sl/tp long", from_entry="long", stop=issl?stoploss:na,               limit=istp?takeprofit:na, alert_message="Close Long")strategy.exit(id="sl/tp short",from_entry="short",stop=issl?stoploss:na,               limit=istp?takeprofit:na, alert_message="Stop Loss Short")// Close if outside the rangeif (not isinrange)    strategy.close_all()