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
- 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
VerifiedSame 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, ⋯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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Strategy Direction | 0 | int (written input.integer) · min -1 · max 1 | line 19 line 20 |
| -----------------Strategy Inputs------------------- | true | bool | unused |
| RSI Length | 21 | int | rsi |
| Overbought | 60 | int | isOB band1 OBP hline plot |
| Oversold | 40 | int | isOS band0 OSP hline plot |
| Entry Delay (# of Bars) | 15 | int | BUY SELL |
| Use Strategy Close | false | bool | close_all line 143 |
| -----------------General Inputs------------------- | true | bool | unused |
| Use Stop Loss and Take Profit | true | bool | exit TP & SL exit TP & SL line 139 |
| Use Trailing Stop | false | bool | exit TP & SL |
| Type Of Stop | ATR Stop | string · options ["Strategy Stop", "Swing Lo/Hi", "ATR Stop"] | SL SSL TP STP |
| Swing Point Lookback | 10 | int | LL HH |
| Swing Point SL Perc Increment | 3 | int · step .1 | LL HH |
| ATR Length | 14 | int | ATR |
| ATR Multiple | 3 | int · step .1 | ATR |
| Take Profit Risk Reward Ratio | 2 | int · step .1 | tp stp ATRtp ATRstp |
| Allow Direct Position Reverse | false | bool | entry long entry short entry long entry short entry long entry short entry long entry short line 125 line 132 |
| Reverse Trades | true | bool | line 124 |
What it calculates
- Lowest (
lowest,ta.lowestin v5)Swing Point Lookback (10)LL · line 46 - Highest (
highest,ta.highestin v5)Swing Point Lookback (10)HH · line 47 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, LL, 0LL_price · line 48 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, HH, 0HH_price · line 49 - ATR (
atr,ta.atrin v5)ATR Length (14)ATR · line 57 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, ATRLong, 0ATRLongStop · line 60 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, ATRShort, 0ATRShortStop · line 61 - RSI (
rsi,ta.rsiin 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long long | SELL and strategy.position_size == 0 | On | 126 |
| Open short short | BUY and strategy.position_size == 0 | On | 127 |
| Open long long | SELLBarsSinceOB == i_delay | On | 129 |
| Open short short | BUYBarsSinceOS == i_delay | On | 130 |
| Open long long | BUY and strategy.position_size == 0 | On | 133 |
| Open short short | SELL and strategy.position_size == 0 | On | 134 |
| Open long long | BUYBarsSinceOS == i_delay | On | 136 |
| Open short short | SELLBarsSinceOB == i_delay | On | 137 |
| Exit TP & SL stop and limit | i_SL | On “Use Stop Loss and Take Profit” | 140 |
| Exit TP & SL stop and limit | i_SL | On “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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −40.4% | +102.5% | 7 | 14% | 0.31 | 42.2% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +29.2% | +5.5% | 3 | 100% | — | 4.3% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −30.0% | +9.8% | 7 | 29% | 0.58 | 58.7% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +28.8% | +8.4% | 4 | 75% | 4.07 | 6.8% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −31.7% | +16.7% | 4 | 25% | 0.52 | 37.7% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −12.2% | +21.5% | 4 | 25% | 0.38 | 15.1% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +30.9% | +148.3% | 5 | 60% | 1.90 | 17.4% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −9.3% | +17.1% | 3 | 33% | 0.37 | 11.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 3 | 0% | −$2,521.71 |
| Sideways market | 2 | 0% | −$1,478.94 |
| Falling market | 2 | 50% | −$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.
All 7 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 2 Mar 2024 62,387.90 | 5 Jul 2024 55,814.60 | 125 | −$1,060.77 |
| long | 21 Nov 2024 94,286.60 | 26 Feb 2025 85,727.00 | 97 | −$818.03 |
| long | 21 May 2025 106,850.00 | 22 Jun 2025 99,264.60 | 32 | −$582.57 |
| long | 25 Jul 2025 118,341.00 | 29 Aug 2025 108,335.00 | 35 | −$642.92 |
| short | 28 Nov 2025 91,333.90 | 5 Feb 2026 67,637.50 | 69 | $1,783.57 |
| short | 13 Feb 2026 66,272.20 | 4 May 2026 80,118.10 | 80 | −$1,820.27 |
| short | 2 Jul 2026 60,024.00 | 19 Aug 2026 67,820.20 | 48 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Delayed RSI Strategy this page | — | v4 strategy | −40.4% | 7 | 42.2% |
| Double Bollinger Strategy by tweakerID | lowest highest valuewhen atr rsi | v4 strategy | −29.6% | 61 | 50.1% |
| Positive Bars - Strategy by tweakerID | lowest highest valuewhen atr | v4 strategy | −40.3% | 7 | 54.7% |
| Big Bar Strategy by tweakerID | lowest highest valuewhen atr | v4 strategy | −56.6% | 13 | 57.1% |
| SuperTrend Multi Time Frame Long and Short Trading Strategy by ranga_technologies | atr highest lowest valuewhen | v5 strategy | No trades on this market | ||
| Dynamic Stop Loss Demo by Tindtily | highest lowest rsi atr | v5 strategy | does not run in Zeal Terminal | ||
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 35 ms | With a workaround 1,000 bars in 124 ms | Not measured |
| PineTS | No 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)