Zeal Terminal Open in Zeal Terminal

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
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (25)
0.0050,000100,000AprJulOct2025AprJulOct2026AprJulOctRSI$1,000,000$2,025,273Equity from $1,000,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. The script plots nothing itself; the lines and the lower pane are its own calculations, drawn for reference.
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.

SettingDefaultType and rangeFeeds
Trade Settings
Long/ShortBothstring · options ["Longs Only", "Shorts Only", "Both"]line 73 line 79
Balance/Risk Settings
Starting BalanceThe starting balance for the strategy10000.0floatcurrent_balance
Risk Per TradeRisk per trade as a percentage of the equity1.0float · min 0.01 · max 100order_size
Take Profit / Stop Loss Settings
Take Profit/Stop Loss TypeThe type of TP/SL used to close the position.Pipsstring · 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 Ratio1.0float · min 0.1 · max 10.0line 122
Min Profit/Loss to Close Trade10.0float · min 0.1 · max 1000000line 122
Take Profit/Stop Loss Target Percentage1.0float · min 0.01 · max 100unused
Long Take Profit (mintick)1000floatexit Exit Long
Long Stop Loss (mintick)2000floatexit Exit Long
Short Take Profit (mintick)1000floatexit Exit Short
Short Stop Loss (mintick)2000floatexit Exit Short
Safety Order Settings
Safety Order PercentPercentage of price deviation to open the first safety order.2floatline 89
Safety Order MultiplierMultiplies the current position size for each safety order.1float · min 1 · max 10order_size
Safety Order Max StepsMaximum number of safety orders before the trade is a loss.5int · min 1 · max 10order Enter Long order Enter Short line 96 line 99 line 103 line 114 line 118
Strategy Settings
Sourceclosesourcersi1 MFI EMA_indicator
Stochastic RSI Settings
K1int · min 1kvalue
D1int · min 1stochrsi_d
RSI Length100int · min 1rsi1
Stochastic Length100int · min 1kvalue
Stochastic RSI Long Signal20float · min 0 · max 50stochrsi_long
Stochastic RSI Short Signal80float · min 50 · max 100stochrsi_short
Money Flow Index Settings
MFI Length30int · min 1 · max 2000MFI
MFI Long Signal20float · min 0 · max 50mfi_long
MFI Short Signal80float · min 50 · max 100mfi_short
EMA Settings
EMA Length100intEMA_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.

closecloseprice datalengthRSIRSI Lengthsetting · 100lengthStochStochastic Lengthsetting · 100StochRSI_kvalueKsetting · 1StochRSI_dvalueDsetting · 1MFI_lengthMFI Lengthsetting · 30EMA_lengthEMA Lengthsetting · 100starting_balanceStarting Balancesetting · 10000.0openopenprice datarisk_per_tradeRisk Per Tradesetting · 1.0safety_order_mulSafety Order Multipliersetting · 1StochRSI_longStochastic RSI Long Sig…setting · 20StochRSI_shortStochastic RSI Short Si…setting · 80MFI_longMFI Long Signalsetting · 20MFI_shortMFI Short Signalsetting · 80safety_order_stepsSafety Order Max Stepssetting · 5tp_sl_typeTake Profit/Stop Loss T…setting · Pipsrsi1RSI→ rsi1kvalueSMA / Stoch→ kvaluestochrsi_dSMA→ stochrsi_dMFIMFI→ MFIEMA_indicatorEMA→ EMA_indicatorcurrent_balancecurrent_balancevalueorder_sizeorder_sizevaluecurrent_stepcurrent_stepvalueprice_entryprice_entryvalueupnl_percentage, order_qtyupnl_percentage · order…2 valueslong_conditionlong_conditionconditionshort_conditionshort_conditionconditionstochrsi_longstochrsi_longconditionstochrsi_shortstochrsi_shortconditionmfi_longmfi_longconditionmfi_shortmfi_shortconditionema_long, ema_shortema_long · ema_short2 conditionsentry:Enter LongOpen Enter Longstrategy.entryentry:Enter ShortOpen Enter Shortstrategy.entryorder:Enter Longorder Enter Longstrategy.orderorder:Enter Shortorder Enter Shortstrategy.orderclose:Enter LongClose Enter Longstrategy.closeclose:Enter ShortClose Enter Shortstrategy.closeexit:Exit Longexit Exit Longstrategy.exitexit:Exit Shortexit Exit Shortstrategy.exit

Order rules

OrderFires whenBy defaultLine
Open Enter Long longlong_condition and strategy.position_size == 0On77
Open Enter Short shortshort_condition and strategy.position_size == 0On84
order Enter Long longstrategy.position_size > 0 and current_step < safety_order_stepsOn97
order Enter Short shortstrategy.position_size < 0 and current_step < safety_order_stepsOn101
Close Enter Longstrategy.position_size > 0On106
Close Enter Shortstrategy.position_size < 0On108
Close Enter Longstrategy.position_size > 0On124
Close Enter Shortstrategy.position_size < 0On126
Exit Exit Long stop and limittp_sl_type == "Pips"On130
Exit Exit Short stop and limittp_sl_type == "Pips"On131
Close Enter Longshort_condition and strategy.position_size > 0On133
Close Enter Shortlong_condition and strategy.position_size < 0On134

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.

Not measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D0.0%+102.5%00%—0.0%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−0.0%+5.5%1250%0.720.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−0.0%+9.8%450%0.500.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−0.0%+8.4%1560%0.630.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D0.0%+16.7%00%—0.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.6%+21.5%9100%—0.1%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+0.0%+148.3%367%29.880.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+0.0%+17.1%1100%—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.

ScriptSharesTypeNetTradesMax drawdown
3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders this page—v5 strategy0.0%00.0%
RSI Mean Reversion Bot Strategy by Solutions1978rsi ema stoch smav4 strategyNo trades on this market
MACD, RSI, & RVOL Strategy by BobBarker42069rsi ema smav4 strategy+32.6%11.5%
CCU MFI + RSI + STOCH RSI by Bangsoulmfi rsi smav4 strategy+41.8%637.4%
IFR2 - RSI2 by jocker.soadrsi sma emav4 strategyNo trades on this market
Vin's Playzone Strategy by Vvaz_ema rsi smav5 strategy−908.1%213,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.

Clean v5

VerifiedDownload the v5 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

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 36 msYes 1,000 bars in 58 msNot measured
PineTSNot testedNot testedNot 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)