Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Delayed RSI Strategy

A Pine Script v4 strategy built on Lowest (10), Highest (10) and Valuewhen (bought, LL). It has 11 order rules, 8 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 100% of equity and pays 0.04 commission. 18 settings; defaults include Strategy Direction 0, RSI Length 21 and Overbought 60.

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 Delayed RSI Strategy repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 2 of 2 trades.
How did Delayed RSI Strategy do on BTCUSDT 1D with default settings?
−40.40%
From 26 Jan 2024 to 21 Oct 2026, over 7 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Delayed RSI Strategy 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.
Does Delayed RSI Strategy use a stop loss?
Yes
strategy.exit sets a stop on line 140, 141.
Does Delayed RSI Strategy run in Zeal Terminal?
Yes
It compiles in 35 ms and runs 1,000 bars in 124 ms, in the browser.

BTCUSDT · 1D · default settings

  • RSI
  • Upper Band
  • Middle Band
  • Lower Band
  • RSI
  • Plot
  • Plot
  • Plot
  • Plot
  • 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 (18)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOctRSI$6,528$20,253Equity from $10,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. 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
−40.40%
−$4,039.73
Buy and hold
+102.5%
same period
Closed trades
7
1 won · 6 lost
Profitable
14.3%
of closed trades
Profit factor
0.31
gross profit ÷ gross loss
Max drawdown
42.23%
−$4,222.53

One run with the author's default settings, $10,000 starting capital, commission as the script sets it. A long 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.

  • Check

    2 settings do nothing

    “-----------------Strategy Inputs-------------------”, “-----------------General Inputs-------------------” are declared but never read.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    Uses an argument v6 removed

    when = on line 126, 127, 129, 130, 133, 134, 136, 137, 144. The upgraded version below moves each call inside an if block.

  • Note

    Uses transp =, which v5 removed line 153

    transp = on line 153, 156, 158. 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 lowest → ta.lowest, highest → ta.highest, valuewhen → ta.valuewhen, atr → ta.atr, rsi → ta.rsi, barssince → ta.barssince, cross → ta.cross.
  • 9 strategy calls use the when = argument (line 126, 127, 129, 130, 133, 134, 136, 137, 144). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Verified

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

  • Line 8: //@version=4 → //@version=5
  • Line 18: input(type = input.integer) → input.int()
  • Line 46: lowest → ta.lowest
  • Line 47: highest → ta.highest
  • Line 48: valuewhen → ta.valuewhen
  • Line 49: valuewhen → ta.valuewhen
12 more edits
  • Line 57: atr → ta.atr
  • Line 60: valuewhen → ta.valuewhen
  • Line 61: valuewhen → ta.valuewhen
  • Line 77: valuewhen → ta.valuewhen
  • Line 89: valuewhen → ta.valuewhen
  • Line 108: rsi → ta.rsi
  • Line 111: barssince → ta.barssince
  • Line 112: barssince → ta.barssince
  • Line 144: cross → ta.cross
  • Line 153: transp = 100 removed: the call sets no colour to fold it into, so its default colour loses the transparency
  • Line 156: transp = 0 → color.new(OSOBColor, 0)
  • Line 158: transp = 0 → color.new(OSOBColor, 0)
⋯// the amount of bars determined by the user. The trading logic can be reversed, which seems to work better.-//@version=4+//@version=5strategy("Delayed RSI Strategy", ⋯     -direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)+direction = input.int(0, title = "Strategy Direction", minval=-1, maxval=1)strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : ⋯SwingStopProfit() =>-    LL=(lowest(i_SPL))*(1-i_PercIncrement)+    LL=(ta.lowest(i_SPL))*(1-i_PercIncrement)-    HH=(highest(i_SPL))*(1+i_PercIncrement)+    HH=(ta.highest(i_SPL))*(1+i_PercIncrement)-    LL_price = valuewhen(bought, LL, 0)+    LL_price = ta.valuewhen(bought, LL, 0)-    HH_price = valuewhen(bought, HH, 0)+    HH_price = ta.valuewhen(bought, HH, 0)    entry_LL_price = strategy.position_size > 0 ? LL_price : na ⋯ATRStop() =>-    ATR=atr(i_ATR)*i_ATRMult+    ATR=ta.atr(i_ATR)*i_ATRMult    ATRLong = ohlc4 - ATR    ATRShort = ohlc4 + ATR-    ATRLongStop = valuewhen(bought, ATRLong, 0)+    ATRLongStop = ta.valuewhen(bought, ATRLong, 0)-    ATRShortStop = valuewhen(bought, ATRShort, 0)+    ATRShortStop = ta.valuewhen(bought, ATRShort, 0)    LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ⋯TrailingStop(SL,SSL) =>-    dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))+    dif=(ta.valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))     -strategy.position_avg_price⋯    var Ststop = float(na)-    Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 +    Sdif=strategy.position_avg_price-(ta.valuewhen(strategy.position_size<0      and strategy.position_size[1]>=0, low,0))⋯/////////////////////// STRATEGY LOGIC /////////////////////////////////////////-rsi = rsi(close, rsiLen)+rsi = ta.rsi(close, rsiLen)isOB= rsi > i_OBisOS= rsi < i_OS-BarsSinceOB = barssince(not isOB)+BarsSinceOB = ta.barssince(not isOB)-BarsSinceOS = barssince(not isOS)+BarsSinceOS = ta.barssince(not isOS)BUY = BarsSinceOS == i_delay⋯if i_Close-    strategy.close_all(when=cross(rsi, 50))+    strategy.close_all(when=ta.cross(rsi, 50))/////////////////////// PLOTS //////////////////////////////////////////////////⋯plot(rsi, "RSI", color=#7E57C2)-OSOBCount = plot(isOB ? BarsSinceOB : isOS ? BarsSinceOS : na, transp=100)+OSOBCount = plot(isOB ? BarsSinceOB : isOS ? BarsSinceOS : na)OSOBColor = color.from_gradient(isOB ? BarsSinceOB : BarsSinceOS, 0, 20, color.black, isOB ? color.red : isOS ? color.green : na)OBP = plot(rsi > i_OB ? rsi : na, color=color.white, display=display.none)-fill(plot(i_OB, display=display.none), OBP, color=OSOBColor, transp=0, fillgaps=false)+fill(plot(i_OB, display=display.none), OBP, color=color.new(OSOBColor, 0), fillgaps=false)OSP = plot(rsi < i_OS ? rsi : na, color=color.white, display=display.none)-fill(plot(i_OS, display=display.none), OSP, color=OSOBColor, transp=0, fillgaps=false)+fill(plot(i_OS, display=display.none), OSP, color=color.new(OSOBColor, 0), fillgaps=false)plotshape(BUY ? 1 : na, style=shape.arrowdown, location=location.bottom, ⋯

Clean v5

VerifiedDownload the v5 script

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

  • Line 25: input() → input.bool()
  • Line 26: input() → input.int()
  • Line 27: input() → input.int()
  • Line 28: input() → input.int()
  • Line 29: input() → input.int()
  • Line 30: input() → input.bool()
20 more edits
  • Line 32: input() → input.bool()
  • Line 34: input() → input.bool()
  • Line 35: input() → input.bool()
  • Line 36: input() → input.string()
  • Line 37: input() → input.int()
  • Line 38: input() → input.int()
  • Line 39: input() → input.int()
  • Line 40: input() → input.int()
  • Line 41: input() → input.int()
  • Line 42: input() → input.bool()
  • Line 43: input() → input.bool()
  • Line 126: when = SELL and strategy.position_size == 0 → if block
  • Line 127: when = BUY and strategy.position_size == 0 → if block
  • Line 129: when = SELL → if block
  • Line 130: when = BUY → if block
  • Line 133: when = BUY and strategy.position_size == 0 → if block
  • Line 134: when = SELL and strategy.position_size == 0 → if block
  • Line 136: when = BUY → if block
  • Line 137: when = SELL → if block
  • Line 144: when = ta.cross(rsi, 50) → if block
⋯/////////////////////// STRATEGY INPUTS ////////////////////////////////////////-title1=input(true, "-----------------Strategy Inputs-------------------")  +title1=input.bool(true, "-----------------Strategy Inputs-------------------")  -rsiLen=input(21, title="RSI Length")+rsiLen=input.int(21, title="RSI Length")-i_OB = input(60, title="Overbought")+i_OB = input.int(60, title="Overbought")-i_OS = input(40, title="Oversold")+i_OS = input.int(40, title="Oversold")-i_delay = input(15, title="Entry Delay (# of Bars)")+i_delay = input.int(15, title="Entry Delay (# of Bars)")-i_Close= input(false, title="Use Strategy Close")+i_Close= input.bool(false, title="Use Strategy Close")/////////////////////// BACKTESTER /////////////////////////////////////////////-title2=input(true, "-----------------General Inputs-------------------")  +title2=input.bool(true, "-----------------General Inputs-------------------")  // Backtester General Inputs-i_SL=input(true, title="Use Stop Loss and Take Profit")+i_SL=input.bool(true, title="Use Stop Loss and Take Profit")-TS=input(false, title="Use Trailing Stop")+TS=input.bool(false, title="Use Trailing Stop")-i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])+i_SLType=input.string(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])-i_SPL=input(defval=10, title="Swing Point Lookback")+i_SPL=input.int(defval=10, title="Swing Point Lookback")-i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01+i_PercIncrement=input.int(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01-i_ATR = input(14, title="ATR Length")+i_ATR = input.int(14, title="ATR Length")-i_ATRMult = input(3, step=.1, title="ATR Multiple")+i_ATRMult = input.int(3, step=.1, title="ATR Multiple")-i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio")+i_TPRRR = input.int(2, step=.1, title="Take Profit Risk Reward Ratio")-DPR=input(false, "Allow Direct Position Reverse")+DPR=input.bool(false, "Allow Direct Position Reverse")-reverse=input(true, "Reverse Trades")+reverse=input.bool(true, "Reverse Trades")// Swing Points Stop and Take Profit⋯    if not DPR-        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)+        if SELL and strategy.position_size == 0+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)+        if BUY and strategy.position_size == 0+            strategy.entry("short", strategy.short)    else     -        strategy.entry("long", strategy.long, when=SELL)+        if SELL+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=BUY)+        if BUY+            strategy.entry("short", strategy.short)else    if not DPR -        strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)+        if BUY and strategy.position_size == 0+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)+        if SELL and strategy.position_size == 0+            strategy.entry("short", strategy.short)    else-        strategy.entry("long", strategy.long, when=BUY)+        if BUY+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=SELL)+        if SELL+            strategy.entry("short", strategy.short)// Exits⋯if i_Close-    strategy.close_all(when=ta.cross(rsi, 50))+    if ta.cross(rsi, 50)+        strategy.close_all()/////////////////////// PLOTS //////////////////////////////////////////////////⋯

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: 7 before, 7 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.

⋯// the amount of bars determined by the user. The trading logic can be reversed, which seems to work better.-//@version=5+//@version=6strategy("Delayed RSI Strategy", ⋯

Settings

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

SettingDefaultType and rangeFeeds
Strategy Direction0int (written input.integer) · min -1 · max 1line 19 line 20
-----------------Strategy Inputs-------------------trueboolunused
RSI Length21intrsi
Overbought60intisOB band1 OBP hline plot
Oversold40intisOS band0 OSP hline plot
Entry Delay (# of Bars)15intBUY SELL
Use Strategy Closefalseboolclose_all line 143
-----------------General Inputs-------------------trueboolunused
Use Stop Loss and Take Profittrueboolexit TP & SL exit TP & SL line 139
Use Trailing Stopfalseboolexit TP & SL
Type Of StopATR Stopstring · options ["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]SL SSL TP STP
Swing Point Lookback10intLL HH
Swing Point SL Perc Increment3int · step .1LL HH
ATR Length14intATR
ATR Multiple3int · step .1ATR
Take Profit Risk Reward Ratio2int · step .1tp stp ATRtp ATRstp
Allow Direct Position Reversefalseboolentry long entry short entry long entry short entry long entry short entry long entry short line 125 line 132
Reverse Tradestrueboolline 124

What it calculates

  • Lowest (lowest, ta.lowest in v5)Swing Point Lookback (10)LL · line 46
  • Highest (highest, ta.highest in v5)Swing Point Lookback (10)HH · line 47
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, LL, 0LL_price · line 48
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, HH, 0HH_price · line 49
  • ATR (atr, ta.atr in v5)ATR Length (14)ATR · line 57
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, ATRLong, 0ATRLongStop · line 60
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, ATRShort, 0ATRShortStop · line 61
  • RSI (rsi, ta.rsi in v5)close, RSI Length (21)rsi · line 108

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.

i_SPLSwing Point Lookbacksetting · 10i_PercIncrementSwing Point SL Perc Inc…setting · 3high · low · closehigh · low · closeprice datai_ATRATR Lengthsetting · 14i_ATRMultATR Multiplesetting · 3closecloseprice datarsiLenRSI Lengthsetting · 21ohlc4ohlc4price datai_delayEntry Delay (# of Bars)setting · 15highhighprice datalowlowprice datai_OBOverboughtsetting · 60i_OSOversoldsetting · 40LLLowest→ LLHHHighest→ HHLL_priceValuewhen→ LL_priceHH_priceValuewhen→ HH_priceATRATR→ ATRATRLongStopValuewhen→ ATRLongStopATRShortStopValuewhen→ ATRShortStoprsiRSI→ rsiATRLong, ATRShortATRLong · ATRShort2 valuesLongStop, ShortStop, StratTP, StratSTPLongStop · ShortStop +24 valuestrailOffsettrailOffsetvaluetstop, Ststoptstop · Ststop2 valuesStrailOffsetStrailOffsetvalueSL, SSL, TP, STPSL · SSL +24 valuesBUYBUYconditionSELLSELLconditionboughtboughtconditiondifdifconditionSdifSdifconditionisOB, BarsSinceOBisOB · BarsSinceOB2 conditionsisOS, BarsSinceOSisOS · BarsSinceOS2 conditionsOSOBColorColourOSOBColorentry:longOpen longstrategy.entryentry:shortOpen shortstrategy.entryexit:TP & SLexit TP & SLstrategy.exitclose_all:close_all strategy.close_allplot:147RSIplothline:148hlinehlinehline:149hlinehlinehline:150hlinehlinefill:BackgroundBackgroundfillplot:152RSIplotplot:153plotplotplot:155plotplotfill:156Fillfill × 2plot:156plotplotplot:157plotplotfill:158Fillfill × 2plot:158plotplotplotshape:159Bullish Setupplotshapeplotshape:161Bearish Setupplotshape

Order rules

OrderFires whenBy defaultLine
Open long longSELL and strategy.position_size == 0On126
Open short shortBUY and strategy.position_size == 0On127
Open long longSELLBarsSinceOB == i_delayOn129
Open short shortBUYBarsSinceOS == i_delayOn130
Open long longBUY and strategy.position_size == 0On133
Open short shortSELL and strategy.position_size == 0On134
Open long longBUYBarsSinceOS == i_delayOn136
Open short shortSELLBarsSinceOB == i_delayOn137
Exit TP & SL stop and limiti_SLOn “Use Stop Loss and Take Profit”140
Exit TP & SL stop and limiti_SLOn “Use Stop Loss and Take Profit”141
Close cross(rsi, 50)Off “Use Strategy Close”144

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

Does it repaint?

No

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

2/2trades 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−40.4%+102.5%714%0.3142.2%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+29.2%+5.5%3100%—4.3%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−30.0%+9.8%729%0.5858.7%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+28.8%+8.4%475%4.076.8%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−31.7%+16.7%425%0.5237.7%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−12.2%+21.5%425%0.3815.1%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+30.9%+148.3%560%1.9017.4%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−9.3%+17.1%333%0.3711.8%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 market30%−$2,521.71
Sideways market20%−$1,478.94
Falling market250%−$36.69

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

How bad could the drawdown be?

52.6%

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

0%61%
All 7 trades
SideEntryExitBarsP&L
long2 Mar 2024 62,387.905 Jul 2024 55,814.60125−$1,060.77
long21 Nov 2024 94,286.6026 Feb 2025 85,727.0097−$818.03
long21 May 2025 106,850.0022 Jun 2025 99,264.6032−$582.57
long25 Jul 2025 118,341.0029 Aug 2025 108,335.0035−$642.92
short28 Nov 2025 91,333.905 Feb 2026 67,637.5069$1,783.57
short13 Feb 2026 66,272.204 May 2026 80,118.1080−$1,820.27
short2 Jul 2026 60,024.0019 Aug 2026 67,820.2048−$896.37

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
Delayed RSI Strategy this page—v4 strategy−40.4%742.2%
Double Bollinger Strategy by tweakerIDlowest highest valuewhen atr rsiv4 strategy−29.6%6150.1%
Positive Bars - Strategy by tweakerIDlowest highest valuewhen atrv4 strategy−40.3%754.7%
Big Bar Strategy by tweakerIDlowest highest valuewhen atrv4 strategy−56.6%1357.1%
SuperTrend Multi Time Frame Long and Short Trading Strategy by ranga_technologiesatr highest lowest valuewhenv5 strategyNo trades on this market
Dynamic Stop Loss Demo by Tindtilyhighest lowest rsi atrv5 strategydoes not run in Zeal Terminal

Where it runs

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

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/// © tweakerID and © BacktestRookies// This strategy uses a 21 period RSI with an overbought (RSI indicator // is greater than) level of 60 (user defined) to determines long entries and an oversold // (RSI indicator is less than) level of 40 (user defined) for shorts. It introduces a bar delay that starts// counting when the RSI < Oversold or RSI > Overbought conditions are true, delaying the entry with // the amount of bars determined by the user. The trading logic can be reversed, which seems to work better.//@version=4strategy("Delayed RSI Strategy",      overlay=false,      default_qty_type=strategy.percent_of_equity,      default_qty_value=100,      initial_capital=10000,      commission_value=0.04,      calc_on_every_tick=false,      slippage=0)     direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all :  (direction < 0 ? strategy.direction.short : strategy.direction.long))// Bought and Sold Boolean Signalbought = strategy.position_size > strategy.position_size[1]  or strategy.position_size < strategy.position_size[1]/////////////////////// STRATEGY INPUTS ////////////////////////////////////////title1=input(true, "-----------------Strategy Inputs-------------------")  rsiLen=input(21, title="RSI Length")i_OB = input(60, title="Overbought")i_OS = input(40, title="Oversold")i_delay = input(15, title="Entry Delay (# of Bars)")i_Close= input(false, title="Use Strategy Close")/////////////////////// BACKTESTER /////////////////////////////////////////////title2=input(true, "-----------------General Inputs-------------------")  // Backtester General Inputsi_SL=input(true, title="Use Stop Loss and Take Profit")TS=input(false, title="Use Trailing Stop")i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])i_SPL=input(defval=10, title="Swing Point Lookback")i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01i_ATR = input(14, title="ATR Length")i_ATRMult = input(3, step=.1, title="ATR Multiple")i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio")DPR=input(false, "Allow Direct Position Reverse")reverse=input(true, "Reverse Trades")// Swing Points Stop and Take ProfitSwingStopProfit() =>    LL=(lowest(i_SPL))*(1-i_PercIncrement)    HH=(highest(i_SPL))*(1+i_PercIncrement)    LL_price = valuewhen(bought, LL, 0)    HH_price = valuewhen(bought, HH, 0)    entry_LL_price = strategy.position_size > 0 ? LL_price : na     entry_HH_price = strategy.position_size < 0 ? HH_price : na     tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR    stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR    [entry_LL_price, entry_HH_price, tp, stp]// ATR StopATRStop() =>    ATR=atr(i_ATR)*i_ATRMult    ATRLong = ohlc4 - ATR    ATRShort = ohlc4 + ATR    ATRLongStop = valuewhen(bought, ATRLong, 0)    ATRShortStop = valuewhen(bought, ATRShort, 0)    LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na     ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na     ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR    ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR    [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp]    // Strategy StopStrategyStop(bought) =>    float LongStop = na    float ShortStop = na    float StratTP = na    float StratSTP = na    [LongStop, ShortStop, StratTP, StratSTP]//TrailingStopTrailingStop(SL,SSL) =>    dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))     -strategy.position_avg_price    trailOffset     = strategy.position_avg_price - SL    var tstop = float(na)    if strategy.position_size > 0        tstop := high- trailOffset - dif        if tstop<tstop[1]            tstop:=tstop[1]    else        tstop := na    StrailOffset     = SSL - strategy.position_avg_price    var Ststop = float(na)    Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0      and strategy.position_size[1]>=0, low,0))    if strategy.position_size < 0        Ststop := low+ StrailOffset + Sdif        if Ststop>Ststop[1]            Ststop:=Ststop[1]    else        Ststop := na    [tstop, Ststop]  //Stop Loss & Take Profit Switches  SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) =>    SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop    SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop    TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP    STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP    [SL, SSL, TP, STP]/////////////////////// STRATEGY LOGIC /////////////////////////////////////////rsi = rsi(close, rsiLen)isOB= rsi > i_OBisOS= rsi < i_OSBarsSinceOB = barssince(not isOB)BarsSinceOS = barssince(not isOS)BUY = BarsSinceOS == i_delaySELL = BarsSinceOB == i_delay/////////////////////// FUNCTION CALLS /////////////////////////////////////////// Stops and Profits[entry_LL_price, entry_HH_price, tp, stp] = SwingStopProfit()[LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] = ATRStop()[LongStop, ShortStop, StratTP, StratSTP] = StrategyStop(bought)[SL, SSL, TP, STP] = SLTPLogic(LongStop, ShortStop, StratTP, StratSTP,  LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp)[tstop, Ststop] = TrailingStop(SL,SSL)// Entriesif reverse    if not DPR        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)    else             strategy.entry("long", strategy.long, when=SELL)        strategy.entry("short", strategy.short, when=BUY)else    if not DPR         strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)    else        strategy.entry("long", strategy.long, when=BUY)        strategy.entry("short", strategy.short, when=SELL)// Exitsif i_SL    strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL)    strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL)    if i_Close    strategy.close_all(when=cross(rsi, 50))/////////////////////// PLOTS ////////////////////////////////////////////////////Plotsrsiplot = plot(rsi, "RSI", color=#7E57C2)band1 = hline(i_OB, "Upper Band", color=#787B86)bandm = hline(50, "Middle Band", color=color.new(#787B86, 50))band0 = hline(i_OS, "Lower Band", color=#787B86)fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background")plot(rsi, "RSI", color=#7E57C2)OSOBCount = plot(isOB ? BarsSinceOB : isOS ? BarsSinceOS : na, transp=100)OSOBColor = color.from_gradient(isOB ? BarsSinceOB : BarsSinceOS, 0, 20, color.black, isOB ? color.red : isOS ? color.green : na)OBP = plot(rsi > i_OB ? rsi : na, color=color.white, display=display.none)fill(plot(i_OB, display=display.none), OBP, color=OSOBColor, transp=0, fillgaps=false)OSP = plot(rsi < i_OS ? rsi : na, color=color.white, display=display.none)fill(plot(i_OS, display=display.none), OSP, color=OSOBColor, transp=0, fillgaps=false)plotshape(BUY ? 1 : na, style=shape.arrowdown, location=location.bottom,  color=color.green, title="Bullish Setup", size=size.normal)plotshape(SELL ? 1 : na, style=shape.arrowup, location=location.top,  color=color.red, title="Bearish Setup", size=size.normal)