Pine Script v4 · Strategy
RSI Mean Reversion Bot Strategy
A Pine Script v4 strategy built on RSI (0, 14), EMA (rsi_ema, 14) and VWAP (close). It has 6 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 commits 100% of equity and pays 0.18% commission. 21 settings; defaults include Trade Types Long/Short, Stop Loss % 10.0 and Target Profit % 20.0.
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 RSI Mean Reversion Bot Strategy repaint?
- Yes
- At least one pattern in the source can repaint: intrabar recalculation.
- How did RSI Mean Reversion Bot Strategy do on BTCUSDT 1D with default settings?
- Not measured
- It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its code limits trading to a date window, which can leave this period out. It closed no trades on the other markets either. A backtest, not investment advice.
- Can RSI Mean Reversion Bot Strategy be converted to Pine Script v5?
- Not tested
- The steps are shown below, but neither version placed a trade on any market tested, so there was nothing to compare and no download is offered.
- Does RSI Mean Reversion Bot Strategy use a stop loss?
- Yes
- strategy.exit sets a stop on line 124, 127.
- Does RSI Mean Reversion Bot Strategy run in Zeal Terminal?
- Yes
- It compiles in 38 ms and runs 1,000 bars in 95 ms, in the browser.
BTCUSDT · 1D · default settings
- K
- D
- Signal Up
- Signal Down
- Oversold
- Overbought
- RSI
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- 0.00%
- $0.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 0
- 0 won · 0 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- —
- gross profit ÷ gross loss
- Max drawdown
- 0.00%
- $0.00
One run with the author's default settings, $1,000 starting capital, commission as the script sets it. 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
4 settings do nothing
“Long/Short for Mixed Market, Long for Bull, Short for Bear”, “RSI Strategy Inputs”, “Stochastic Overlay Inputs”, “EMA Fast and Slow Length Inputs” are declared but never read.
-
Check
Every trade uses all the equity
default_qty_value is 100% of equity.
-
Note
1 setting has no label
In the settings dialog length (line 36) shows 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.
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 rsi → ta.rsi, ema → ta.ema, vwap → ta.vwap, stoch → ta.stoch, wma → ta.wma, sma → ta.sma, change → ta.change, crossover → ta.crossover, crossunder → ta.crossunder.
v4 → v5
Not verifiedNeither version placed a trade on any of the 8 markets, so there was nothing to compare.
- Line 2: //@version=4 → //@version=5
- Line 22: input(type = input.time) → input.time()
- Line 23: input(type = input.time) → input.time()
- Line 37: input(type = input.source) → input.source()
- Line 49: input(type = input.source) → input.source()
- Line 55: rsi → ta.rsi
19 more edits
- Line 56: ema → ta.ema
- Line 57: ema → ta.ema
- Line 58: ema → ta.ema
- Line 59: ema → ta.ema
- Line 60: ema → ta.ema
- Line 61: ema → ta.ema
- Line 62: vwap → ta.vwap
- Line 74: rsi → ta.rsi
- Line 75: stoch → ta.stoch
- Line 77: ema → ta.ema
- Line 78: wma → ta.wma
- Line 79: sma → ta.sma
- Line 80: sma → ta.sma
- Line 81: change → ta.change
- Line 82: change → ta.change
- Line 104: crossover → ta.crossover
- Line 105: crossunder → ta.crossunder
- Line 111: crossover → ta.crossover
- Line 112: crossunder → ta.crossunder
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/-//@version=4+//@version=5// ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗██████╗ ██████╗ ██╗ ██╗ ⋯//Backtest dates with auto finish date of today-start = input(defval = timestamp("01 April 2021 00:00 -0500"), title = "Start Time", type = input.time)+start = input.time(defval = timestamp("01 April 2021 00:00 -0500"), title = "Start Time")-finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", type = input.time)+finish = input.time(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time")window() => time >= start and time <= finish ? true : false // create function "within window of time"⋯length = input(14, minval=1)-source = input(title="Source", type=input.source, defval=close)+source = input.source(title="Source", defval=close)overbought = input(60, "Overbought")⋯slowLength = input(10, minval=1, title="EMA Slow Length")-VWAPSource = input(title="VWAP Source", type=input.source, defval=close)+VWAPSource = input.source(title="VWAP Source", defval=close)// Selections to show or hide the overlays⋯haClose(gap) => (open[gap] + high[gap] + low[gap] + close[gap]) / 4-rsi_ema = rsi(haClose(0), length)+rsi_ema = ta.rsi(haClose(0), length)-v2 = ema(rsi_ema, length) +v2 = ta.ema(rsi_ema, length) -v3 = 2 * v2 - ema(v2, length) +v3 = 2 * v2 - ta.ema(v2, length) -emaA = ema(rsi_ema, fastLength) +emaA = ta.ema(rsi_ema, fastLength) -emaFast = 2 * emaA - ema(emaA, fastLength)+emaFast = 2 * emaA - ta.ema(emaA, fastLength)-emaB = ema(rsi_ema, slowLength) +emaB = ta.ema(rsi_ema, slowLength) -emaSlow = 2 * emaB - ema(emaB, slowLength) +emaSlow = 2 * emaB - ta.ema(emaB, slowLength) -vwapVal = vwap(VWAPSource)+vwapVal = ta.vwap(VWAPSource)// bullish signal rule: ⋯// Calculation-rsi1 = rsi(source, length)+rsi1 = ta.rsi(source, length)-stoch = stoch(rsi1, rsi1, rsi1, length)+stoch = ta.stoch(rsi1, rsi1, rsi1, length)k =- k_mode=="EMA" ? ema(stoch, smoothK) :+ k_mode=="EMA" ? ta.ema(stoch, smoothK) :- k_mode=="WMA" ? wma(stoch, smoothK) :+ k_mode=="WMA" ? ta.wma(stoch, smoothK) :- sma(stoch, smoothK)+ ta.sma(stoch, smoothK)-d = sma(k, smoothD)+d = ta.sma(k, smoothD)-k_c = change(k)+k_c = ta.change(k)-d_c = change(d)+d_c = ta.change(d)kd = k - d⋯// Entry Logic-GoLong = strat_val>-1 and crossover(rsi1, oversold) and strategy.position_size==0 and window()+GoLong = strat_val>-1 and ta.crossover(rsi1, oversold) and strategy.position_size==0 and window()-GoShort = strat_val<1 and crossunder(rsi1, overbought) and strategy.position_size==0 and window()+GoShort = strat_val<1 and ta.crossunder(rsi1, overbought) and strategy.position_size==0 and window()// Strategy Entry and Exit with built in Risk Management⋯ strategy.entry("SHORT", strategy.short)-CloseLong = strat_val > -1 and strategy.position_size > 0 and crossover(rsi1, overbought) and window()+CloseLong = strat_val > -1 and strategy.position_size > 0 and ta.crossover(rsi1, overbought) and window()-CloseShort = strat_val < 1 and strategy.position_size < 0 and crossunder(rsi1, oversold) and window()+CloseShort = strat_val < 1 and strategy.position_size < 0 and ta.crossunder(rsi1, oversold) and window()if(CloseLong)⋯Clean v5
Not verifiedNeither version placed a trade on any of the 8 markets, so there was nothing to compare.
- Line 26: input() → input.bool()
- Line 27: input() → input.string()
- Line 30: input() → input.float()
- Line 31: input() → input.float()
- Line 35: input() → input.bool()
- Line 36: input() → input.int()
11 more edits
- Line 38: input() → input.int()
- Line 39: input() → input.int()
- Line 41: input() → input.bool()
- Line 42: input() → input.int()
- Line 43: input() → input.int()
- Line 44: input() → input.string()
- Line 46: input() → input.bool()
- Line 47: input() → input.int()
- Line 48: input() → input.int()
- Line 51: input() → input.bool()
- Line 52: input() → input.bool()
⋯// Strategy Selection - Long, Short, or Both-stratinfo = input(true, "Long/Short for Mixed Market, Long for Bull, Short for Bear")+stratinfo = input.bool(true, "Long/Short for Mixed Market, Long for Bull, Short for Bear")-strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"])+strat = input.string(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"])strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1// Risk Management Inputs-sl = input(10.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01)+sl = input.float(10.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01)-tp = input(20.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01)+tp = input.float(20.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01)stoploss = sl/100⋯// RSI Inputs-RSIinfo = input(true, "RSI Strategy Inputs")+RSIinfo = input.bool(true, "RSI Strategy Inputs")-length = input(14, minval=1)+length = input.int(14, minval=1)source = input.source(title="Source", defval=close)-overbought = input(60, "Overbought")+overbought = input.int(60, "Overbought")-oversold = input(30, "Oversold")+oversold = input.int(30, "Oversold")// Stochastic Inputs-Stochinfo = input(true, "Stochastic Overlay Inputs")+Stochinfo = input.bool(true, "Stochastic Overlay Inputs")-smoothK = input(3, "K", minval=1)+smoothK = input.int(3, "K", minval=1)-smoothD = input(3, "D", minval=1)+smoothD = input.int(3, "D", minval=1)-k_mode = input("SMA", "K Mode", options=["SMA", "EMA", "WMA"])+k_mode = input.string("SMA", "K Mode", options=["SMA", "EMA", "WMA"])//EMA Inputs-EMAInfo = input(true, "EMA Fast and Slow Length Inputs")+EMAInfo = input.bool(true, "EMA Fast and Slow Length Inputs")-fastLength = input(5, minval=1, title="EMA Fast Length")+fastLength = input.int(5, minval=1, title="EMA Fast Length")-slowLength = input(10, minval=1, title="EMA Slow Length")+slowLength = input.int(10, minval=1, title="EMA Slow Length")VWAPSource = input.source(title="VWAP Source", defval=close)// Selections to show or hide the overlays-showZones = input(true, title="Show Bullish/Bearish Zones")+showZones = input.bool(true, title="Show Bullish/Bearish Zones")-showStoch = input(true, title="Show Stochastic Overlays")+showStoch = input.bool(true, title="Show Stochastic Overlays")// ------------------ Background Colors based on EMA Indicators -----------------------------------⋯Does it run in Pine Script v6?
Not tested
Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/-//@version=5+//@version=6// ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗██████╗ ██████╗ ██╗ ██╗ ⋯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 |
|---|---|---|---|
| Start Time | timestamp("01 April 2021 00:00 -0500") | time | line 24 |
| End Time | timestamp("31 December 2021 00:00 -0600") | time | line 24 |
| Long/Short for Mixed Market, Long for Bull, Short for Bear | true | bool | unused |
| Trade Types | Long/Short | string · options ["Long Only", "Long/Short", "Short Only"] | strat_val |
| Stop Loss % | 10.0 | float · min 0 · max 100 · step 0.01 | stoploss |
| Target Profit % | 20.0 | float · min 0 · max 100 · step 0.01 | TargetProfit |
| RSI Strategy Inputs | true | bool | unused |
| Length (no label in the script) | 14 | int · min 1 | rsi_ema v2 v3 rsi1 stoch |
| Source | close | source | rsi1 |
| Overbought | 60 | int | signalColor Overbought GoShort CloseLong |
| Oversold | 30 | int | signalColor Oversold GoLong CloseShort |
| Stochastic Overlay Inputs | true | bool | unused |
| K | 3 | int · min 1 | k |
| D | 3 | int · min 1 | d |
| K Mode | SMA | string · options ["SMA", "EMA", "WMA"] | k |
| EMA Fast and Slow Length Inputs | true | bool | unused |
| EMA Fast Length | 5 | int · min 1 | emaA emaFast |
| EMA Slow Length | 10 | int · min 1 | emaB emaSlow |
| VWAP Source | close | source | vwapVal |
| Show Bullish/Bearish Zones | true | bool | Bullish/Bearish Zones |
| Show Stochastic Overlays | true | bool | K D signalUp signalDown |
What it calculates
- RSI (
rsi,ta.rsiin v5)haClose(0), Length (14)rsi_ema · line 55 - EMA (
ema,ta.emain v5)rsi_ema, Length (14)v2 · line 56 - EMA (
ema,ta.emain v5)v2, Length (14)v3 · line 57 - EMA (
ema,ta.emain v5)rsi_ema, EMA Fast Length (5)emaA · line 58 - EMA (
ema,ta.emain v5)emaA, EMA Fast Length (5)emaFast · line 59 - EMA (
ema,ta.emain v5)rsi_ema, EMA Slow Length (10)emaB · line 60 - EMA (
ema,ta.emain v5)emaB, EMA Slow Length (10)emaSlow · line 61 - VWAP (
vwap,ta.vwapin v5)VWAP Source (close)vwapVal · line 62 - RSI (
rsi,ta.rsiin v5)Source (close), Length (14)rsi1 · line 74 - Stoch (
stoch,ta.stochin v5)rsi1, rsi1, rsi1, Length (14)stoch · line 75 - EMA / WMA / SMA (
ema,ta.emain v5)stoch, K (3) · chosen by K Modek · line 76 - SMA (
sma,ta.smain v5)k, D (3)d · line 80 - Change (
change,ta.changein v5)kk_c · line 81 - Change (
change,ta.changein v5)dd_c · line 82
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 63 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open LONG long | (GoLong) | On | 108 |
| Open SHORT short | (GoShort) | On | 110 |
| Close LONG | (CloseLong) | On | 114 |
| Close SHORT | (CloseShort) | On | 116 |
| Exit Exit Long stop and limit | (strategy.position_size > 0) | On | 124 |
| Exit Exit Short stop and limit | (strategy.position_size < 0) | On | 127 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
Yes
At least one pattern in the source can repaint; it is marked Check below.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- CheckIntrabar recalculationcalc_on_every_tick = true. Live values can differ from history.
- ClearOrder timingprocess_orders_on_close = true: orders fill at the signal bar's close.
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 | 0.0% | +102.5% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | 0.0% | +5.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | 0.0% | +9.8% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | 0.0% | +8.4% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | 0.0% | +16.7% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | 0.0% | +21.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | 0.0% | +148.3% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | 0.0% | +17.1% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
Settings heatmap
Two settings that feed the entry signal, moved around their defaults. The best in-sample pair (Length 7, D 2) made 0.0% before 26 Dec 2025 and 0.0% after it, against 0.0% for the defaults. 0% of the 32 combinations made money in-sample and 0% out-of-sample.
| D ↓ · Length → | 7 | 8 | 10 | 12 | 14 | 17 | 20 | 24 |
|---|---|---|---|---|---|---|---|---|
| 2 | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% |
| 3 | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% |
| 4 | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% |
| 5 | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% |
| D ↓ · Length → | 7 | 8 | 10 | 12 | 14 | 17 | 20 | 24 |
|---|---|---|---|---|---|---|---|---|
| 2 | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% |
| 3 | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% |
| 4 | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% |
| 5 | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% |
Net P&L of trades opened in each period, as a share of starting capital. marks the defaults and the best in-sample cell. Hover a cell for its trade count. Backtests are simulations on historical data and are not investment advice.
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 |
|---|---|---|---|---|---|
| RSI Mean Reversion Bot Strategy this page | — | v4 strategy | 0.0% | 0 | 0.0% |
| DRSI DMA Scalping Strategy No Repaint by allenlk | sma wma ema rsi | v4 strategy | −99.5% | 44 | 137.7% |
| Power Zonessssss by liuen | vwap ema rsi | v5 strategy | +2.5% | 4 | 5.1% |
| MACD, RSI, & RVOL Strategy by BobBarker42069 | rsi ema sma | v4 strategy | +32.6% | 1 | 1.5% |
| ZVWAP strategy by mohanee | sma ema vwap | v4 strategy | +614.4% | 13 | 748.5% |
| IFR2 - RSI2 by jocker.soad | rsi sma ema | v4 strategy | No trades on this market | ||
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 38 ms | Yes 1,000 bars in 95 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
“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///@version=4// ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗██████╗ ██████╗ ██╗ ██╗ //██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗ ██╔══██╗╚██╗ ██╔╝ //██║ ██████╔╝█████╗ ███████║ ██║ █████╗ ██║ ██║ ██████╔╝ ╚████╔╝ //██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ ██║ ██║ ██╔══██╗ ╚██╔╝ //╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗██████╔╝ ██████╔╝ ██║ // ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═════╝ ╚═════╝ ╚═╝ //███████╗ ██████╗ ██╗ ██╗ ██╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ ██╗ █████╗ ███████╗ █████╗ //██╔════╝██╔═══██╗██║ ██║ ██║╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝███║██╔══██╗╚════██║██╔══██╗//███████╗██║ ██║██║ ██║ ██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗╚██║╚██████║ ██╔╝╚█████╔╝//╚════██║██║ ██║██║ ██║ ██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ ██║ ╚═══██║ ██╔╝ ██╔══██╗//███████║╚██████╔╝███████╗╚██████╔╝ ██║ ██║╚██████╔╝██║ ╚████║███████║ ██║ █████╔╝ ██║ ╚█████╔╝//╚══════╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚════╝ ╚═╝ ╚════╝ strategy(shorttitle='RSI Bot Strategy v3',title='Holy Grail RSI Strategy', overlay=true, scale=scale.left, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.18, calc_on_every_tick=true)kcolor = color.new(#0094FF, 60)dcolor = color.new(#FF6A00, 60)// ----------------- Strategy Inputs -------------------------------------------------------------//Backtest dates with auto finish date of todaystart = input(defval = timestamp("01 April 2021 00:00 -0500"), title = "Start Time", type = input.time)finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", type = input.time)window() => time >= start and time <= finish ? true : false // create function "within window of time"// Strategy Selection - Long, Short, or Bothstratinfo = input(true, "Long/Short for Mixed Market, Long for Bull, Short for Bear")strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"])strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1// Risk Management Inputssl = input(10.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01)tp = input(20.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01)stoploss = sl/100TargetProfit = tp/100// RSI InputsRSIinfo = input(true, "RSI Strategy Inputs")length = input(14, minval=1)source = input(title="Source", type=input.source, defval=close)overbought = input(60, "Overbought")oversold = input(30, "Oversold")// Stochastic InputsStochinfo = input(true, "Stochastic Overlay Inputs")smoothK = input(3, "K", minval=1)smoothD = input(3, "D", minval=1)k_mode = input("SMA", "K Mode", options=["SMA", "EMA", "WMA"])//EMA InputsEMAInfo = input(true, "EMA Fast and Slow Length Inputs")fastLength = input(5, minval=1, title="EMA Fast Length")slowLength = input(10, minval=1, title="EMA Slow Length")VWAPSource = input(title="VWAP Source", type=input.source, defval=close)// Selections to show or hide the overlaysshowZones = input(true, title="Show Bullish/Bearish Zones")showStoch = input(true, title="Show Stochastic Overlays")// ------------------ Background Colors based on EMA Indicators -----------------------------------haClose(gap) => (open[gap] + high[gap] + low[gap] + close[gap]) / 4rsi_ema = rsi(haClose(0), length)v2 = ema(rsi_ema, length) v3 = 2 * v2 - ema(v2, length) emaA = ema(rsi_ema, fastLength) emaFast = 2 * emaA - ema(emaA, fastLength)emaB = ema(rsi_ema, slowLength) emaSlow = 2 * emaB - ema(emaB, slowLength) vwapVal = vwap(VWAPSource)// bullish signal rule: bullishRule =emaFast > emaSlow and close>open and close>vwapVal// bearish signal rule: bearishRule =emaFast < emaSlow and close<open and close<vwapVal// current trading StateruleState = 0ruleState := bullishRule ? 1 : bearishRule ? -1 : nz(ruleState[1])ruleColor = ruleState==1 ? color.new(color.blue, 90) : ruleState == -1 ? color.new(color.red, 90) : ruleState == 0 ? color.new(color.gray, 90) : nabgcolor(showZones ? ruleColor : na, title="Bullish/Bearish Zones")// ------------------ Stochastic Indicator Overlay -----------------------------------------------// Calculationrsi1 = rsi(source, length)stoch = stoch(rsi1, rsi1, rsi1, length)k = k_mode=="EMA" ? ema(stoch, smoothK) : k_mode=="WMA" ? wma(stoch, smoothK) : sma(stoch, smoothK)d = sma(k, smoothD)k_c = change(k)d_c = change(d)kd = k - d// PlotsignalColor = k>oversold and d<overbought and k>d and k_c>0 and d_c>0 ? kcolor : k<overbought and d>oversold and k<d and k_c<0 and d_c<0 ? dcolor : nakp = plot(showStoch ? k : na, "K", color=kcolor)dp = plot(showStoch ? d : na, "D", color=dcolor)fill(kp, dp, color = signalColor, title="K-D")signalUp = showStoch ? not na(signalColor) and kd>0 : nasignalDown = showStoch ? not na(signalColor) and kd<0 : naplot(signalUp ? kd : na, "Signal Up", color=kcolor, style=plot.style_columns)plot(signalDown ? (kd+100) : na , "Signal Down", color=dcolor, style=plot.style_columns, histbase=100)// Add RSI Candle Plot to Strategy for better visualization//overlay RSIh0 = hline(oversold, title="Oversold", color=color.green)h1 = hline(overbought, title="Overbought", color=color.red)RSIFill = color.new(#9915FF, 95)fill(h0, h1, RSIFill, title="Band Background")plot(rsi1, title="RSI", color=color.yellow, linewidth=3)// End Plot Code// -------------------------------- Entry and Exit Logic ------------------------------------// Entry LogicGoLong = strat_val>-1 and crossover(rsi1, oversold) and strategy.position_size==0 and window()GoShort = strat_val<1 and crossunder(rsi1, overbought) and strategy.position_size==0 and window()// Strategy Entry and Exit with built in Risk Managementif (GoLong) strategy.entry("LONG", strategy.long)if (GoShort) strategy.entry("SHORT", strategy.short)CloseLong = strat_val > -1 and strategy.position_size > 0 and crossover(rsi1, overbought) and window()CloseShort = strat_val < 1 and strategy.position_size < 0 and crossunder(rsi1, oversold) and window()if(CloseLong) strategy.close("LONG")if(CloseShort) strategy.close("SHORT") // Determine where you've entered and in what directionlongStopPrice = strategy.position_avg_price * (1 - stoploss)longTakePrice = strategy.position_avg_price * (1 + TargetProfit)shortStopPrice = strategy.position_avg_price * (1 + stoploss)shortTakePrice = strategy.position_avg_price * (1 - TargetProfit)if (strategy.position_size > 0) strategy.exit(id="Exit Long", from_entry = "LONG", stop = longStopPrice, limit = longTakePrice) if (strategy.position_size < 0) strategy.exit(id="Exit Short", from_entry = "SHORT", stop = shortStopPrice, limit = shortTakePrice)//PLOT FIXED SLTP LINEplot(strategy.position_size > 0 ? longStopPrice : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Fixed SL")plot(strategy.position_size < 0 ? shortStopPrice : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Fixed SL")plot(strategy.position_size > 0 ? longTakePrice : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit")plot(strategy.position_size < 0 ? shortTakePrice : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")