Pine Script v5 · Strategy
3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders
A Pine Script v5 strategy built on RSI (close, 100), SMA or Stoch (1) and SMA (kvalue, 1). It has 12 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. 25 settings; defaults include Long/Short Both, Starting Balance 10000.0 and Risk Per Trade 1.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 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders repaint?
- Yes
- At least one pattern in the source can repaint: intrabar recalculation.
- How did 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders 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 entry conditions never all held on this data. On BTCUSDT 4h it did trade; that row of the markets table below has its figures. A backtest, not investment advice.
- Does 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders 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: 12 before, 12 after on BTCUSDT 4h, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download.
- Does 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders use a stop loss?
- Yes
- strategy.exit sets a stop on line 130, 131.
- Does 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders run in Zeal Terminal?
- Yes
- It compiles in 36 ms and runs 1,000 bars in 58 ms, in the browser.
BTCUSDT · 1D · default settings
- SMA
- SMA
- EMA
- 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,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
1 setting does nothing
“Take Profit/Stop Loss Target Percentage” is declared but never read.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses an argument v6 removed
when = on line 133, 134. The upgraded version below moves each call inside an if block.
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 |
|---|---|---|---|
| Trade Settings | |||
| Long/Short | Both | string · options ["Longs Only", "Shorts Only", "Both"] | line 73 line 79 |
| Balance/Risk Settings | |||
| Starting BalanceThe starting balance for the strategy | 10000.0 | float | current_balance |
| Risk Per TradeRisk per trade as a percentage of the equity | 1.0 | float · min 0.01 · max 100 | order_size |
| Take Profit / Stop Loss Settings | |||
| Take Profit/Stop Loss TypeThe type of TP/SL used to close the position. | Pips | string · options ["Pips", "Base Value", "Opposite Signal"] | exit Exit Long exit Exit Short close Enter Long close Enter Short line 121 line 129 line 132 |
| Risk Reward Ratio | 1.0 | float · min 0.1 · max 10.0 | line 122 |
| Min Profit/Loss to Close Trade | 10.0 | float · min 0.1 · max 1000000 | line 122 |
| Take Profit/Stop Loss Target Percentage | 1.0 | float · min 0.01 · max 100 | unused |
| Long Take Profit (mintick) | 1000 | float | exit Exit Long |
| Long Stop Loss (mintick) | 2000 | float | exit Exit Long |
| Short Take Profit (mintick) | 1000 | float | exit Exit Short |
| Short Stop Loss (mintick) | 2000 | float | exit Exit Short |
| Safety Order Settings | |||
| Safety Order PercentPercentage of price deviation to open the first safety order. | 2 | float | line 89 |
| Safety Order MultiplierMultiplies the current position size for each safety order. | 1 | float · min 1 · max 10 | order_size |
| Safety Order Max StepsMaximum number of safety orders before the trade is a loss. | 5 | int · min 1 · max 10 | order Enter Long order Enter Short line 96 line 99 line 103 line 114 line 118 |
| Strategy Settings | |||
| Source | close | source | rsi1 MFI EMA_indicator |
| Stochastic RSI Settings | |||
| K | 1 | int · min 1 | kvalue |
| D | 1 | int · min 1 | stochrsi_d |
| RSI Length | 100 | int · min 1 | rsi1 |
| Stochastic Length | 100 | int · min 1 | kvalue |
| Stochastic RSI Long Signal | 20 | float · min 0 · max 50 | stochrsi_long |
| Stochastic RSI Short Signal | 80 | float · min 50 · max 100 | stochrsi_short |
| Money Flow Index Settings | |||
| MFI Length | 30 | int · min 1 · max 2000 | MFI |
| MFI Long Signal | 20 | float · min 0 · max 50 | mfi_long |
| MFI Short Signal | 80 | float · min 50 · max 100 | mfi_short |
| EMA Settings | |||
| EMA Length | 100 | int | EMA_indicator |
What it calculates
- RSISource (close), RSI Length (100)
rsi1 · line 40 - SMA / Stochta.stoch(rsi1, rsi1, rsi1, lengthStoch), K (1)
kvalue · line 41 - SMAkvalue, D (1)
stochrsi_d · line 42 - MFISource (close), MFI Length (30)
MFI · line 47 - EMASource (close), EMA Length (100)
EMA_indicator · line 52
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 Enter Long long | long_condition and strategy.position_size == 0 | On | 77 |
| Open Enter Short short | short_condition and strategy.position_size == 0 | On | 84 |
| order Enter Long long | strategy.position_size > 0 and current_step < safety_order_steps | On | 97 |
| order Enter Short short | strategy.position_size < 0 and current_step < safety_order_steps | On | 101 |
| Close Enter Long | strategy.position_size > 0 | On | 106 |
| Close Enter Short | strategy.position_size < 0 | On | 108 |
| Close Enter Long | strategy.position_size > 0 | On | 124 |
| Close Enter Short | strategy.position_size < 0 | On | 126 |
| Exit Exit Long stop and limit | tp_sl_type == "Pips" | On | 130 |
| Exit Exit Short stop and limit | tp_sl_type == "Pips" | On | 131 |
| Close Enter Long | short_condition and strategy.position_size > 0 | On | 133 |
| Close Enter Short | long_condition and strategy.position_size < 0 | On | 134 |
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 recalculationuses varip. Live values can differ from history.
- 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 | 0.0% | +102.5% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −0.0% | +5.5% | 12 | 50% | 0.72 | 0.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −0.0% | +9.8% | 4 | 50% | 0.50 | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −0.0% | +8.4% | 15 | 60% | 0.63 | 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.6% | +21.5% | 9 | 100% | — | 0.1% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +0.0% | +148.3% | 3 | 67% | 29.88 | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +0.0% | +17.1% | 1 | 100% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
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 |
|---|---|---|---|---|---|
| 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders this page | — | v5 strategy | 0.0% | 0 | 0.0% |
| RSI Mean Reversion Bot Strategy by Solutions1978 | rsi ema stoch sma | v4 strategy | No trades on this market | ||
| MACD, RSI, & RVOL Strategy by BobBarker42069 | rsi ema sma | v4 strategy | +32.6% | 1 | 1.5% |
| CCU MFI + RSI + STOCH RSI by Bangsoul | mfi rsi sma | v4 strategy | +41.8% | 6 | 37.4% |
| IFR2 - RSI2 by jocker.soad | rsi sma ema | v4 strategy | No trades on this market | ||
| Vin's Playzone Strategy by Vvaz_ | ema rsi sma | v5 strategy | −908.1% | 21 | 3,570.5% |
Upgrade and export
Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.
- 2 strategy calls use the when = argument (line 133, 134). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
- No v6-only features. v6 is not needed to run this script.
Same 12 trades and the same P&L on BTCUSDT 4h, 1,000 bars, in Zeal Terminal's engine.
- Line 133: when = short_condition and strategy.position_size > 0 → if block
- Line 134: when = long_condition and strategy.position_size < 0 → if block
⋯if tp_sl_type == "Opposite Signal"- strategy.close(id="Enter Long", when = short_condition and strategy.position_size > 0)+ if short_condition and strategy.position_size > 0+ strategy.close(id="Enter Long")- strategy.close(id="Enter Short", when = long_condition and strategy.position_size < 0)+ if long_condition and strategy.position_size < 0+ strategy.close(id="Enter Short")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: 12 before, 12 after on BTCUSDT 4h, 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.
⋯// © ggekko21-//@version=5+//@version=6strategy("3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders", shorttitle="StochRSI MFI EMA With Safety Orders", overlay=true, max_labels_count=500)⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 36 ms | Yes 1,000 bars in 58 ms | Not measured |
| PineTS | Not tested | Not tested | 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.
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/// © ggekko21//@version=5strategy("3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders", shorttitle="StochRSI MFI EMA With Safety Orders", overlay=true, max_labels_count=500)bal_group = "Balance/Risk Settings"trade_group = "Trade Settings"long_or_shorts = input.string(defval = "Both", title = "Long/Short", options = ["Longs Only", "Shorts Only", "Both"], group=trade_group)// Balance & Risk inputsstarting_balance = input.float(defval=10000.0, title="Starting Balance", tooltip="The starting balance for the strategy", group=bal_group)risk_per_trade = input.float(defval=1.0, minval = 0.01, maxval = 100, title="Risk Per Trade", tooltip="Risk per trade as a percentage of the equity", group=bal_group)// TP/SL inputstpsl_group = "Take Profit / Stop Loss Settings"tp_sl_type = input.string(defval = "Pips", title="Take Profit/Stop Loss Type", options = ["Pips", "Base Value", "Opposite Signal"], tooltip = "The type of TP/SL used to close the position.", group=tpsl_group)rr_ratio = input.float(defval = 1.0, minval = 0.1, maxval = 10.0, title="Risk Reward Ratio", group=tpsl_group)tpsl = input.float(defval = 10.0, minval = 0.1, maxval = 1000000, title="Min Profit/Loss to Close Trade", group=tpsl_group)tpsl_percentage = input.float(defval = 1.0, minval = 0.01, maxval = 100, title = "Take Profit/Stop Loss Target Percentage", group=tpsl_group)long_tp = input.float(1000, title="Long Take Profit (mintick)", group=tpsl_group)long_sl = input.float(2000, title="Long Stop Loss (mintick)", group=tpsl_group)short_tp = input.float(1000, title="Short Take Profit (mintick)", group=tpsl_group)short_sl = input.float(2000, title="Short Stop Loss (mintick)", group=tpsl_group)// Safety Order inputssafety_group = "Safety Order Settings"// First safety order price deviation.safety_order_percent = input.float(defval = 2, title = "Safety Order Percent", group=safety_group, tooltip = "Percentage of price deviation to open the first safety order.")// What increments do you want the safety order to increase by?safety_order_mul = input.float(defval = 1, minval = 1, maxval = 10, title = "Safety Order Multiplier", group=safety_group, tooltip = "Multiplies the current position size for each safety order.")// How many safety order steps?safety_order_steps = input.int(defval = 5, minval = 1, maxval = 10, title = "Safety Order Max Steps", group=safety_group, tooltip = "Maximum number of safety orders before the trade is a loss.")src = input.source(defval = close, title = "Source", group = "Strategy Settings")// ==================================================================================================================== //// ============================================= StochRSI ============================================================= //// ==================================================================================================================== //StochRSI_group = "Stochastic RSI Settings"StochRSI_kvalue = input.int(1, "K", minval=1, group=StochRSI_group)StochRSI_dvalue = input.int(1, "D", minval=1, group=StochRSI_group)lengthRSI = input.int(100, "RSI Length", minval=1, group=StochRSI_group)lengthStoch = input.int(100, "Stochastic Length", minval=1, group=StochRSI_group)StochRSI_long = input.float(20, minval = 0, maxval = 50, title = "Stochastic RSI Long Signal", group=StochRSI_group)StochRSI_short = input.float(80, minval = 50, maxval = 100, title = "Stochastic RSI Short Signal", group=StochRSI_group)rsi1 = ta.rsi(src, lengthRSI)kvalue = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), StochRSI_kvalue)stochrsi_d = ta.sma(kvalue, StochRSI_dvalue)// ==================================================================================================================== //// =============================================== MFI ================================================================ //// ==================================================================================================================== //MFI_length = input.int(title="MFI Length", defval=30, minval=1, maxval=2000, group="Money Flow Index Settings")MFI = ta.mfi(src, MFI_length)MFI_long = input.float(20, minval = 0, maxval = 50, title = "MFI Long Signal", group="Money Flow Index Settings")MFI_short = input.float(80, minval = 50, maxval = 100, title = "MFI Short Signal", group="Money Flow Index Settings")// EMA IndicatorEMA_length = input.int(100, title="EMA Length", group = "EMA Settings")EMA_indicator = ta.ema(src, EMA_length)// ==================================================================================================================== //// ============================================ Apply Strategy ======================================================== //// ==================================================================================================================== //stochrsi_long = stochrsi_d < StochRSI_longstochrsi_short = stochrsi_d > StochRSI_shortmfi_long = MFI < MFI_longmfi_short = MFI > MFI_shortema_long = close < EMA_indicatorema_short = close > EMA_indicatorlong_condition = stochrsi_long and mfi_long and ema_longshort_condition = stochrsi_short and mfi_short and ema_short// ==================================================================================================================== //// ========================================== Apply Safety Orders ===================================================== //// ==================================================================================================================== //varip float current_balance = starting_balancevarip float order_size = ((risk_per_trade/100) * current_balance)/openvarip int current_step = 0varip float price_entry = closeupnl_percentage = (strategy.openprofit/math.abs(strategy.position_avg_price*strategy.position_size))*100// Make sure strategy doesn't duplicate ordersif long_or_shorts == "Longs Only" or long_or_shorts == "Both" if long_condition and strategy.position_size == 0 //label.new(bar_index, high, text=str.tostring(upnl_percentage, format=format.mintick)) order_size := ((risk_per_trade/100) * current_balance)/open strategy.entry("Enter Long", strategy.long, qty=order_size) price_entry := closeif long_or_shorts == "Shorts Only" or long_or_shorts == "Both" if short_condition and strategy.position_size == 0 //label.new(bar_index, high, text=str.tostring(upnl_percentage, format=format.mintick)) order_size := ((risk_per_trade/100) * current_balance)/open strategy.entry("Enter Short", strategy.short, qty=order_size) price_entry := close // Enter Safety Orders Hereif upnl_percentage <= -safety_order_percent //if current_step < safety_order_steps // Enter safety order here order_qty = math.abs(strategy.position_size)// * safety_order_mul //order_size := (((risk_per_trade/100) * current_balance)/open)*safety_order_mul*current_step order_size := (((risk_per_trade/100) * strategy.equity)/open)*safety_order_mul if strategy.position_size > 0 and current_step < safety_order_steps strategy.order("Enter Long", strategy.long, qty=order_size) current_step := current_step + 1 if strategy.position_size < 0 and current_step < safety_order_steps //label.new(bar_index, high, text=str.tostring(strategy.position_size, format=format.mintick)) strategy.order("Enter Short", strategy.short, qty=order_size) current_step := current_step + 1 else if current_step >= safety_order_steps // Maximum number of safety orders reached, closing position. if strategy.position_size > 0 strategy.close(id="Enter Long") if strategy.position_size < 0 strategy.close(id="Enter Short") current_step := 0 // Update Current Balanceif strategy.wintrades != strategy.wintrades[1] current_balance := strategy.equity if current_step >= safety_order_steps current_step := 0if strategy.losstrades != strategy.losstrades[1] current_balance := strategy.equity if current_step >= safety_order_steps current_step := 0// Take Profit/Stop Loss Typeif tp_sl_type == "Base Value" if strategy.openprofit > tpsl*rr_ratio or strategy.openprofit <= -tpsl if strategy.position_size > 0 strategy.close(id="Enter Long") if strategy.position_size < 0 strategy.close(id="Enter Short") current_step := current_step + 1 if tp_sl_type == "Pips" strategy.exit(id="Exit Long", from_entry="Enter Long", profit=long_tp, loss=long_sl, qty_percent = 100) strategy.exit(id="Exit Short", from_entry="Enter Short", profit=short_tp, loss=short_sl, qty_percent = 100)if tp_sl_type == "Opposite Signal" strategy.close(id="Enter Long", when = short_condition and strategy.position_size > 0) strategy.close(id="Enter Short", when = long_condition and strategy.position_size < 0)