Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Momentum Strategy (BTC-USDT; 30m) - STOCH RSI (with source code)

A Pine Script v4 strategy built on RSI (close, 12), EMA or Stoch (3) and EMA (k, 6). It has 8 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 sizeordineInit% of equity and pays no commission. 29 settings; defaults include start year 2020, start month 1 and start day 1.

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 Momentum Strategy (BTC-USDT; 30m) - STOCH RSI (with source code) repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 3 of 3 trades.
How did Momentum Strategy (BTC-USDT; 30m) - STOCH RSI (with source code) do on BTCUSDT 1D with default settings?
+13.26%
From 26 Jan 2024 to 21 Oct 2026, over 12 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Momentum Strategy (BTC-USDT; 30m) - STOCH RSI (with source code) 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 Momentum Strategy (BTC-USDT; 30m) - STOCH RSI (with source code) use a stop loss?
Yes
strategy.exit sets a stop on line 125, 158.
Does Momentum Strategy (BTC-USDT; 30m) - STOCH RSI (with source code) run in Zeal Terminal?
Yes
It compiles in 194 ms and runs 1,000 bars in 125 ms, in the browser.

BTCUSDT · 1D · default settings

  • Plot
  • Plot
  • HLine
  • HLine
  • Plot
  • Plot
  • Plot
  • Plot
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (29)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOctPlot$1,141$2,025Equity from $1,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots.
Net profit
+13.26%
$132.61
Buy and hold
+102.5%
same period
Closed trades
12
7 won · 5 lost
Profitable
58.3%
of closed trades
Profit factor
1.35
gross profit ÷ gross loss
Max drawdown
13.60%
−$150.50

One run with the author's default settings, $1,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

    “------------------------Backtest Period------------------------”, “------------------------Basic Parameters------------------------” are declared but never read.

  • Check

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Note

    4 settings have no label

    In the settings dialog smoothK (line 40), smoothD (line 41), lengthRSI (line 42), lengthStoch (line 45) show an empty name. The labels on this page come from the variable names.

  • Note

    Uses transp =, which v5 removed line 65

    transp = on line 65. 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 rsi → ta.rsi, ema → ta.ema, stoch → ta.stoch, crossover → ta.crossover, crossunder → ta.crossunder, valuewhen → ta.valuewhen, tostring → str.tostring, barssince → ta.barssince.

v4 → v5

Verified

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

  • Line 3: //@version=4 → //@version=5
  • Line 44: rsi → ta.rsi
  • Line 46: ema → ta.ema
  • Line 46: stoch → ta.stoch
  • Line 47: ema → ta.ema
  • Line 48: input(type = input.float) → input.float()
36 more edits
  • Line 49: input(type = input.float) → input.float()
  • Line 51: input(type = input.bool) → input.bool()
  • Line 52: input(type = input.integer) → input.int()
  • Line 53: input(type = input.integer) → input.int()
  • Line 65: transp = 80 → color.new(color.purple, 80)
  • Line 70: crossover → ta.crossover
  • Line 71: crossunder → ta.crossunder
  • Line 73: valuewhen → ta.valuewhen
  • Line 74: valuewhen → ta.valuewhen
  • Line 78: input(type = input.float) → input.float()
  • Line 79: input(type = input.float) → input.float()
  • Line 83: tostring → str.tostring
  • Line 83: tostring → str.tostring
  • Line 83: tostring → str.tostring
  • Line 83: tostring → str.tostring
  • Line 83: tostring → str.tostring
  • Line 84: tostring → str.tostring
  • Line 84: tostring → str.tostring
  • Line 84: tostring → str.tostring
  • Line 84: tostring → str.tostring
  • Line 84: tostring → str.tostring
  • Line 88: ema → ta.ema
  • Line 89: ema → ta.ema
  • Line 101: barssince → ta.barssince
  • Line 102: barssince → ta.barssince
  • Line 114: valuewhen → ta.valuewhen
  • Line 127: input(type = input.float) → input.float()
  • Line 128: input(type = input.float) → input.float()
  • Line 132: tostring → str.tostring
  • Line 132: tostring → str.tostring
  • Line 132: tostring → str.tostring
  • Line 132: tostring → str.tostring
  • Line 132: tostring → str.tostring
  • Line 132: tostring → str.tostring
  • Line 141: barssince → ta.barssince
  • Line 142: barssince → ta.barssince
⋯// © Drun30 (Federico Magnani)-//@version=4+//@version=5//STRATEGIA PRINCIPALE⋯src = input(close, title="RSI Source")-rsi1 = rsi(src, lengthRSI)+rsi1 = ta.rsi(src, lengthRSI)lengthStoch = input(12, minval=1)-k = ema(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)+k = ta.ema(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)-d = ema(k, smoothD)+d = ta.ema(k, smoothD)-altezzaipercomprato= input(ipercomprato, title="Overbought Height", minval=1, type=input.float)+altezzaipercomprato= input.float(ipercomprato, title="Overbought Height", minval=1)-altezzaipervenduto= input(ipervenduto, title="Oversold Height", minval=1,type=input.float) +altezzaipervenduto= input.float(ipervenduto, title="Oversold Height", minval=1) BarsDelay = input(6,title="Bars delay",minval=0) -GambleSizing = input(wantToUseGambleSizing, title = "Gamble Sizing?",type=input.bool)+GambleSizing = input.bool(wantToUseGambleSizing, title = "Gamble Sizing?")-gambleAdd = input(deltaSize,title="Gamble Add (%)",minval=0,type=input.integer)+gambleAdd = input.int(deltaSize,title="Gamble Add (%)",minval=0)-gambleLimit = input(sizeLimite,title="Gamble MAX (%)",minval=0,type=input.integer)+gambleLimit = input.int(sizeLimite,title="Gamble MAX (%)",minval=0)if GambleSizing and strategy.closedtrades[0]>strategy.closedtrades[1]⋯h1 = hline(altezzaipervenduto)-fill(h0, h1, color=color.purple, transp=80)+fill(h0, h1, color=color.new(color.purple, 80))// n=input(Vicinanzadalcentro,title="Vicinanza dal centro",minval=0) ⋯//     siamoinipercomprato= d>=altezzaipercomprato and d>=d[n] and d<d[1]?true:false //and d>d[3] and d<d[1]-goldencross = crossover(k,d)+goldencross = ta.crossover(k,d)-deathcross = crossunder(k,d)+deathcross = ta.crossunder(k,d)// METTI VARIABILE IN CUI AVVIENE CROSSOVER O CROSSUNDER-valoreoro = valuewhen(goldencross,d,0)+valoreoro = ta.valuewhen(goldencross,d,0)-valoremorte = valuewhen(deathcross,d,0)+valoremorte = ta.valuewhen(deathcross,d,0)siamoinipervenduto = goldencross and valoreoro<=altezzaipervenduto?true:false//d<=altezzaipervenduto?true:false⋯long_separator = input(title="------------------------LONG------------------------", defval = usiLong)-sl_long_inp = input(stopLossPercent_Long, title="Stop Loss LONG %", type=input.float,step=0.1) +sl_long_inp = input.float(stopLossPercent_Long, title="Stop Loss LONG %",step=0.1) -tp_long_inp = input(takeProfitPercent_Long, title="Take Profit LONG %",type=input.float,step=0.1)+tp_long_inp = input.float(takeProfitPercent_Long, title="Take Profit LONG %",step=0.1)stop_level_long = strategy.position_avg_price * (1 - (sl_long_inp/100)) //strategy.position_avg_price corrisponde al prezzo con cui si è aperta la posizione⋯//BINANCE-JSON_long = '{"pair":"'+pair+'","isBuy":true,"isSell":false,"isMarket":true,"isLimit":false,"isClose":false,"price":"9497.59","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"8545.44","stopLossPercent":"-'+tostring(sl_long_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"10257.32","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_long_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}'+JSON_long = '{"pair":"'+pair+'","isBuy":true,"isSell":false,"isMarket":true,"isLimit":false,"isClose":false,"price":"9497.59","unitsPercent":"'+str.tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"8545.44","stopLossPercent":"-'+str.tostring(sl_long_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"10257.32","amount":"'+str.tostring(100-commissionsPercent)+'","takeProfitPercent":"'+str.tostring(tp_long_inp)+'"}],"targetType":"percent","leverage":"'+str.tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}'-JSON_chiusura = '{"pair":"'+pair+'","isBuy":false,"isSell":false,"isMarket":true,"isLimit":false,"isClose":true,"price":"9497.36","units":"0.01","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"8545.44","stopLossPercent":"-'+tostring(sl_long_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"10257.32","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_long_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}' +JSON_chiusura = '{"pair":"'+pair+'","isBuy":false,"isSell":false,"isMarket":true,"isLimit":false,"isClose":true,"price":"9497.36","units":"0.01","unitsPercent":"'+str.tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"8545.44","stopLossPercent":"-'+str.tostring(sl_long_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"10257.32","amount":"'+str.tostring(100-commissionsPercent)+'","takeProfitPercent":"'+str.tostring(tp_long_inp)+'"}],"targetType":"percent","leverage":"'+str.tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}' webhookLong = JSON_long⋯trendFilterL = input(title="TREND FILTER LONG?", defval = true)-EMAfast=ema(close,periodomediamobile_fast)+EMAfast=ta.ema(close,periodomediamobile_fast)-EMAslow=ema(close,periodomediamobile_slow)+EMAslow=ta.ema(close,periodomediamobile_slow)siamoinuptrend_ema=EMAfast>EMAslow?true:false //close>=EMAfast and EMAfast>EMAslow⋯plot(possiamoAprireLong,color=color.green)-sonPassateLeBarreG = barssince(CondizioneAperturaLong) == BarsDelay?true:false+sonPassateLeBarreG = ta.barssince(CondizioneAperturaLong) == BarsDelay?true:false-sonPassateLeBarreD = barssince(CondizioneChiusuraLong) == BarsDelay?true:false+sonPassateLeBarreD = ta.barssince(CondizioneChiusuraLong) == BarsDelay?true:falsehaiUnLongAncoraAperto = false⋯plot(haiUnLongAncoraAperto_float,color=color.red) //FInché la linea rossa si trova a livello "1" allora c'è un ordine long in corso-quantita = (sizeordine/100*(capitaleIniziale+strategy.netprofit))/valuewhen(haiUnLongAncoraAperto==false and CondizioneAperturaLong,close,0)+quantita = (sizeordine/100*(capitaleIniziale+strategy.netprofit))/ta.valuewhen(haiUnLongAncoraAperto==false and CondizioneAperturaLong,close,0)plot(sizeordine,color=color.purple, linewidth=3)⋯short_separator = input(title="------------------------SHORT------------------------", defval = usiShort)    -sl_short_inp = input(stopLossPercent_Short, title="Stop Loss SHORT %",type=input.float,step=0.1)+sl_short_inp = input.float(stopLossPercent_Short, title="Stop Loss SHORT %",step=0.1)-tp_short_inp = input(takeProfitPercent_Short, title="Take Profit SHORT %",type=input.float,step=0.1)+tp_short_inp = input.float(takeProfitPercent_Short, title="Take Profit SHORT %",step=0.1)stop_level_short = strategy.position_avg_price * (1 + (sl_short_inp/100))⋯// BINANCE -JSON_short = '{"pair":"'+pair+'","isBuy":false,"isSell":true,"isMarket":true,"isLimit":false,"isClose":false,"price":"9147.62","units":"'+tostring(sizeordine)+'","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"10062.41","stopLossPercent":"-'+tostring(sl_short_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"7775.50","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_short_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}'+JSON_short = '{"pair":"'+pair+'","isBuy":false,"isSell":true,"isMarket":true,"isLimit":false,"isClose":false,"price":"9147.62","units":"'+str.tostring(sizeordine)+'","unitsPercent":"'+str.tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"10062.41","stopLossPercent":"-'+str.tostring(sl_short_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"7775.50","amount":"'+str.tostring(100-commissionsPercent)+'","takeProfitPercent":"'+str.tostring(tp_short_inp)+'"}],"targetType":"percent","leverage":"'+str.tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}'webhookShort = JSON_short⋯CondizioneChiusuraShort = siamoinipervenduto and siamoindata-sonPassateLeBarreGs = barssince(CondizioneAperturaShort) == BarsDelay?true:false+sonPassateLeBarreGs = ta.barssince(CondizioneAperturaShort) == BarsDelay?true:false-sonPassateLeBarreDs = barssince(CondizioneChiusuraShort) == BarsDelay?true:false+sonPassateLeBarreDs = ta.barssince(CondizioneChiusuraShort) == BarsDelay?true:falsehaiUnoShortAncoraAperto = false⋯

Clean v5

VerifiedDownload the v5 script

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

  • Line 33: input() → input.bool()
  • Line 34: input() → input.int()
  • Line 34: input() → input.int()
  • Line 34: input() → input.int()
  • Line 35: input() → input.int()
  • Line 35: input() → input.int()
12 more edits
  • Line 35: input() → input.int()
  • Line 39: input() → input.bool()
  • Line 40: input() → input.int()
  • Line 41: input() → input.int()
  • Line 42: input() → input.int()
  • Line 43: input() → input.source()
  • Line 45: input() → input.int()
  • Line 50: input() → input.int()
  • Line 59: input() → input.int()
  • Line 60: input() → input.int()
  • Line 87: input() → input.bool()
  • Line 134: input() → input.bool()
⋯strategy("Momentum Strategy (V7.B.4)", initial_capital=capitaleIniziale, currency="USD", default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=commissionsPercent, slippage = 5, default_qty_value=sizeordineInit, overlay=false, pyramiding=0)-backtest = input(title="------------------------Backtest Period------------------------", defval = false)+backtest = input.bool(title="------------------------Backtest Period------------------------", defval = false)-start = timestamp(input(2020, "start year"), input(1, "start month"), input(1, "start day"), 00, 00)+start = timestamp(input.int(2020, "start year"), input.int(1, "start month"), input.int(1, "start day"), 00, 00)-end = timestamp(input(0, "end year"), input(0, "end month"), input(0, "end day"), 00, 00) +end = timestamp(input.int(0, "end year"), input.int(0, "end month"), input.int(0, "end day"), 00, 00) siamoindata=time > start?true:false⋯    siamoindata:=time > start and time <= end?true:false-basicParameters = input(title="------------------------Basic Parameters------------------------", defval = false)+basicParameters = input.bool(title="------------------------Basic Parameters------------------------", defval = false)-smoothK = input(3, minval=1)+smoothK = input.int(3, minval=1)-smoothD = input(6, minval=1)+smoothD = input.int(6, minval=1)-lengthRSI = input(12, minval=1) +lengthRSI = input.int(12, minval=1) -src = input(close, title="RSI Source")+src = input.source(close, title="RSI Source")rsi1 = ta.rsi(src, lengthRSI)-lengthStoch = input(12, minval=1)+lengthStoch = input.int(12, minval=1)k = ta.ema(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)⋯altezzaipervenduto= input.float(ipervenduto, title="Oversold Height", minval=1) -BarsDelay = input(6,title="Bars delay",minval=0) +BarsDelay = input.int(6,title="Bars delay",minval=0) GambleSizing = input.bool(wantToUseGambleSizing, title = "Gamble Sizing?")⋯        sizeordine:=sizeordineInit-periodomediamobile_fast = input(1, title="Fast EMA length",minval=1)+periodomediamobile_fast = input.int(1, title="Fast EMA length",minval=1)-periodomediamobile_slow = input(60, title="Slow EMA length",minval=1)+periodomediamobile_slow = input.int(60, title="Slow EMA length",minval=1)plot(k, color=color.blue)⋯webhookClose= JSON_chiusura-trendFilterL = input(title="TREND FILTER LONG?", defval = true)+trendFilterL = input.bool(title="TREND FILTER LONG?", defval = true)EMAfast=ta.ema(close,periodomediamobile_fast)⋯webhookShort = JSON_short-trendFilterS = input(title="TREND FILTER SHORT?", defval = true)+trendFilterS = input.bool(title="TREND FILTER SHORT?", defval = true)siamoindowntrend_ema=EMAfast<EMAslow?true:false //close<=EMAfast and EMAfast<EMAslow⋯

Does it run in Pine Script v6?

Yes

Same 12 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.

Download the v6 script

⋯// © Drun30 (Federico Magnani)-//@version=5+//@version=6//STRATEGIA PRINCIPALE⋯

Settings

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

SettingDefaultType and rangeFeeds
------------------------Backtest Period------------------------falseboolunused
start year2020intsiamoindata
start month1intsiamoindata
start day1intsiamoindata
end year0intsiamoindata line 37
end month0intsiamoindata line 37
end day0intsiamoindata line 37
------------------------Basic Parameters------------------------falseboolunused
Smooth K (no label in the script)3int · min 1k
Smooth D (no label in the script)6int · min 1d
Length RSI (no label in the script)12int · min 1rsi1
RSI Sourceclosesourcersi1
Length Stoch (no label in the script)12int · min 1k
Overbought Heightipercompratofloat · min 1h0 siamoinipercomprato hline
Oversold Heightipervendutofloat · min 1h1 siamoinipervenduto hline
Bars delay6int · min 0sonPassateLeBarreG sonPassateLeBarreD sonPassateLeBarreGs sonPassateLeBarreDs
Gamble Sizing?wantToUseGambleSizingboolline 54
Gamble Add (%)deltaSizeint (written input.integer) · min 0sizeordine
Gamble MAX (%)sizeLimiteint (written input.integer) · min 0line 55
Fast EMA length1int · min 1EMAfast
Slow EMA length60int · min 1EMAslow
------------------------LONG------------------------usiLongvalueCondizioneAperturaLong
Stop Loss LONG %stopLossPercent_Longfloat · step 0.1stop_level_long JSON_long JSON_chiusura
Take Profit LONG %takeProfitPercent_Longfloat · step 0.1take_level_long JSON_long JSON_chiusura
TREND FILTER LONG?trueboolline 94 line 98
------------------------SHORT------------------------usiShortvalueCondizioneAperturaShort
Stop Loss SHORT %stopLossPercent_Shortfloat · step 0.1stop_level_short JSON_short
Take Profit SHORT %takeProfitPercent_Shortfloat · step 0.1take_level_short JSON_short
TREND FILTER SHORT?trueboolline 138

What it calculates

  • RSI (rsi, ta.rsi in v5)RSI Source (close), Length RSI (12)rsi1 · line 44
  • EMA / Stoch (ema, ta.ema in v5)stoch(rsi1, rsi1, rsi1, lengthStoch), Smooth K (3)k · line 46
  • EMA (ema, ta.ema in v5)k, Smooth D (6)d · line 47
  • Crossover (crossover, ta.crossover in v5)k, dgoldencross · line 70
  • Crossunder (crossunder, ta.crossunder in v5)k, ddeathcross · line 71
  • Valuewhen (valuewhen, ta.valuewhen in v5)goldencross, d, 0valoreoro · line 73
  • Valuewhen (valuewhen, ta.valuewhen in v5)deathcross, d, 0valoremorte · line 74
  • EMA (ema, ta.ema in v5)close, Fast EMA length (1)EMAfast · line 88
  • EMA (ema, ta.ema in v5)close, Slow EMA length (60)EMAslow · line 89
  • Barssince (barssince, ta.barssince in v5)CondizioneAperturaLongsonPassateLeBarreG · line 101
  • Barssince (barssince, ta.barssince in v5)CondizioneChiusuraLongsonPassateLeBarreD · line 102
  • Barssince (barssince, ta.barssince in v5)CondizioneAperturaShortsonPassateLeBarreGs · line 141
  • Barssince (barssince, ta.barssince in v5)CondizioneChiusuraShortsonPassateLeBarreDs · line 142

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 66 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open Vamonos longstrategy.position_size<=0 and CondizioneAperturaLongOn117
Close Vamonossiamoinuptrend == true and sonPassateLeBarreDOn120
Close Vamonossiamoinuptrend == false and CondizioneChiusuraLongOn122
Exit Vamonos stop and limitstrategy.position_size>0 and siamoindataOn125
Open Andale shortCondizioneAperturaShort and strategy.position_size>=0On151
Close Andalesiamoindowntrend == true and sonPassateLeBarreDsOn154
Close Andalesiamoindowntrend == false and CondizioneChiusuraShortOn156
Exit Andale stop and limitstrategy.position_size<0 and siamoindataOn158

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.

3/3trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Other markets

The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D+13.3%+102.5%1258%1.3513.6%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+10.8%+5.5%1258%1.738.7%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−9.1%+9.8%1953%0.8738.9%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+10.2%+8.4%1070%1.5215.3%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−5.7%+16.7%1346%0.8933.2%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+26.6%+21.5%1377%2.4610.6%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+43.1%+148.3%1776%2.2213.5%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+10.1%+17.1%1070%2.019.9%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market863%$105.44
Sideways market333%−$83.64
Falling market1100%$111.59

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

How bad could the drawdown be?

25.6%

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

0%29%
All 12 trades
SideEntryExitBarsP&L
long20 Apr 2024 63,818.101 May 2024 57,436.2011−$71.33
long4 May 2024 62,882.1020 May 2024 67,912.6016$68.74
long4 Jun 2024 68,809.9024 Jun 2024 61,928.9020−$71.15
long7 Oct 2024 62,820.0015 Oct 2024 67,845.608$68.57
long30 Nov 2024 97,460.1016 Dec 2024 105,257.0016$54.26
long25 Dec 2024 98,663.6020 Jan 2025 106,557.0026$57.22
long4 Feb 2025 101,329.0025 Feb 2025 91,195.6021−$78.91
long3 Jun 2025 105,858.0010 Jul 2025 114,327.0037$76.05
long28 Jul 2025 119,416.0029 Aug 2025 107,474.0032−$78.71
short8 Jan 2026 91,364.102 Feb 2026 76,968.3025$111.59
long22 May 2026 77,615.602 Jun 2026 69,854.0011−$81.06
long13 Sep 2026 77,278.8021 Sep 2026 83,461.108$78.12

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
Momentum Strategy (BTC-USDT; 30m) - STOCH RSI (with source code) this page—v4 strategy+13.3%1213.6%
Tendency EMA + RSI [Alorse] by alorsersi ema valuewhenv5 strategy+4.3%41.9%
Bitcoin Scalping Strategy (Sampled with- PMARP+MADRID MA RIBBON) by CheatCode1ema rsi stochv5 strategy−3.0%7245.4%
12-26-IT strategy by Abdul-Rahimema valuewhen rsiv5 strategy−11.9%2021.9%
RSI Mean Reversion Bot Strategy by Solutions1978rsi ema stochv4 strategyNo trades on this market
RSI Cross [xaurr] by livetrendrsi emav4 strategy+24.4%5335.3%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 194 msYes 1,000 bars in 125 msNot measured
PineTSNo 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/// © Drun30 (Federico Magnani)//@version=4//STRATEGIA PRINCIPALE/////////////////// CHANGE THESE VARIABLES FOR TV-HUB ///////////////////var pair = "BTCUSDT" //metti il valore associato a "pair" nel JSON generato da TVHUBvar orderSizePercent = 70 // → % di capitale investita per ogni trade, la percentuale è da riferirsi alla PERCENTUALE DI CRIPTOVALUTA PRESENTE NEL PORTAFOGLIO SPOT (se ho messo la coppia "BTCUSDT", ho 1200 USDT liberi nel portafoglio e lascio "orderSizePercent"=50, mi eseguirà un ordine di acquisto spendendo 600 USDT (=1200*0.5) per comprare BTC (in caso di ordine long))var stopLossPercent_Long = 10 //è lo stop loss (percentuale) per le posizioni Long, metti il valore associato a "stopLossPercent" nel JSON generato da TVHUB per le posizioni longvar takeProfitPercent_Long = 8 //è il take profit (percentuale) per le posizioni Long, metti il valore associato a "takeProfitPercent" nel JSON generato da TVHUB per le posizioni longvar stopLossPercent_Short = 20 //è lo stop loss (percentuale) per le posizioni Short, metti il valore associato a "stopLossPercent" nel JSON generato da TVHUB per le posizioni shortvar takeProfitPercent_Short = 35 //è il take profit (percentuale) per le posizioni Short, metti il valore associato a "takeProfitPercent" nel JSON generato da TVHUB per le posizioni shortvar tokenTVHUB = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" //è il token associato al tuo account su TV-HUB, metti il valore associato a "token" nel JSON generato da TVHUBvar exchange = "Binance-Futures-Testnet" //metti il valore associato a "exchange" nel JSON generato da TVHUB//Excgange possibili: Bitmex, Bitmex-Testnet, Binance, Binance-Futures, Binance-Futures-Testnet, Bybit, Bybit-Testnetvar leverage = 1 //lascia 1 se non stai usando binance futures o bitmexcommissionsPercent = 0.1 //commissioni dell'exchange (0.1 = 0.1%, sono le commissioni di Binance)/////////////////////////////////////////////////////////////////////////////////////////// QUICK CHANGE VARIABLES OF THE STRATEGY ///////////////////wantToUseGambleSizing=true //se "true" aumenterà la size del trade successivo a quello perdente per il valore percentuale associato a "deltasize" (se ho fallito un trade con il 50% della size, se wantToUseGambleSizing=true e deltaSize=25, il trade successivo impiegherà il 75% della valuta in portafoglio)var deltaSize = 25 // → delta% di capitale investito se trade precedente è stato in perdita (cumulabile: se parto con il 50% del capitale ed il trade va in perdita, il trade successivo userà il 75% (=50+25), se fallisce anche quello userà il 100%(=50+25+25) (ammesso che sia stato raggiunto il valore "sizeLimite"))var sizeLimite = 100 //il trade non impiegherà mai una percentuale superiore a questa nei trade successivi a quello andato in perditacapitaleIniziale=1000var sizeordineInit= orderSizePercentvar sizeordine = sizeordineInit//Parametri ottimali 30 minusiShort=trueusiLong=trueipercomprato=85.29ipervenduto=30.6////////////////////////////////////////////////////////////////////////////////strategy("Momentum Strategy (V7.B.4)", initial_capital=capitaleIniziale, currency="USD", default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=commissionsPercent, slippage = 5, default_qty_value=sizeordineInit, overlay=false, pyramiding=0)backtest = input(title="------------------------Backtest Period------------------------", defval = false)start = timestamp(input(2020, "start year"), input(1, "start month"), input(1, "start day"), 00, 00)end = timestamp(input(0, "end year"), input(0, "end month"), input(0, "end day"), 00, 00) siamoindata=time > start?true:falseif end > 0    siamoindata:=time > start and time <= end?true:falsebasicParameters = input(title="------------------------Basic Parameters------------------------", defval = false)smoothK = input(3, minval=1)smoothD = input(6, minval=1)lengthRSI = input(12, minval=1) src = input(close, title="RSI Source")rsi1 = rsi(src, lengthRSI)lengthStoch = input(12, minval=1)k = ema(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)d = ema(k, smoothD)altezzaipercomprato= input(ipercomprato, title="Overbought Height", minval=1, type=input.float)altezzaipervenduto= input(ipervenduto, title="Oversold Height", minval=1,type=input.float) BarsDelay = input(6,title="Bars delay",minval=0) GambleSizing = input(wantToUseGambleSizing, title = "Gamble Sizing?",type=input.bool)gambleAdd = input(deltaSize,title="Gamble Add (%)",minval=0,type=input.integer)gambleLimit = input(sizeLimite,title="Gamble MAX (%)",minval=0,type=input.integer)if GambleSizing and strategy.closedtrades[0]>strategy.closedtrades[1]    if strategy.losstrades[0]>strategy.losstrades[1] and sizeordine<gambleLimit        sizeordine:=sizeordine+gambleAdd    if strategy.wintrades[0]>strategy.wintrades[1]        sizeordine:=sizeordineInitperiodomediamobile_fast = input(1, title="Fast EMA length",minval=1)periodomediamobile_slow = input(60, title="Slow EMA length",minval=1)plot(k, color=color.blue)plot(d, color=color.orange)h0 = hline(altezzaipercomprato)h1 = hline(altezzaipervenduto)fill(h0, h1, color=color.purple, transp=80)// n=input(Vicinanzadalcentro,title="Vicinanza dal centro",minval=0) //sarebbe il livello di D in cui si acquista o si vende, maggiore è la vicinanza maggiore sarà la frequenza dei trades, SE 0 è DISABILITATO//     siamoinipervenduto= d<=altezzaipervenduto and d<=d[n] and d>d[1]?true:false //and d<d[3] and d>d[1]//     siamoinipercomprato= d>=altezzaipercomprato and d>=d[n] and d<d[1]?true:false //and d>d[3] and d<d[1]goldencross = crossover(k,d)deathcross = crossunder(k,d)// METTI VARIABILE IN CUI AVVIENE CROSSOVER O CROSSUNDERvaloreoro = valuewhen(goldencross,d,0)valoremorte = valuewhen(deathcross,d,0)siamoinipervenduto = goldencross and valoreoro<=altezzaipervenduto?true:false//d<=altezzaipervenduto?true:falsesiamoinipercomprato = deathcross and valoremorte>=altezzaipercomprato?true:false//d>=altezzaipercomprato?true:falselong_separator = input(title="------------------------LONG------------------------", defval = usiLong)sl_long_inp = input(stopLossPercent_Long, title="Stop Loss LONG %", type=input.float,step=0.1) tp_long_inp = input(takeProfitPercent_Long, title="Take Profit LONG %",type=input.float,step=0.1)stop_level_long = strategy.position_avg_price * (1 - (sl_long_inp/100)) //strategy.position_avg_price corrisponde al prezzo con cui si è aperta la posizionetake_level_long = strategy.position_avg_price * (1 + (tp_long_inp/100))//BINANCEJSON_long = '{"pair":"'+pair+'","isBuy":true,"isSell":false,"isMarket":true,"isLimit":false,"isClose":false,"price":"9497.59","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"8545.44","stopLossPercent":"-'+tostring(sl_long_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"10257.32","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_long_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}'JSON_chiusura = '{"pair":"'+pair+'","isBuy":false,"isSell":false,"isMarket":true,"isLimit":false,"isClose":true,"price":"9497.36","units":"0.01","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"8545.44","stopLossPercent":"-'+tostring(sl_long_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"10257.32","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_long_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}' webhookLong = JSON_longwebhookClose= JSON_chiusuratrendFilterL = input(title="TREND FILTER LONG?", defval = true)EMAfast=ema(close,periodomediamobile_fast)EMAslow=ema(close,periodomediamobile_slow)siamoinuptrend_ema=EMAfast>EMAslow?true:false //close>=EMAfast and EMAfast>EMAslowsiamoinuptrend = siamoinuptrend_ema// CondizioneAperturaLong = siamoinipervenduto and siamoindata // and siamoinuptrendCondizioneAperturaLong = siamoinipervenduto and siamoindata and long_separatorif trendFilterL    CondizioneAperturaLong := siamoinipervenduto and siamoindata and long_separator and siamoinuptrendCondizioneChiusuraLong = siamoinipercomprato and siamoindata possiamoAprireLong=0if trendFilterL and siamoinuptrend    possiamoAprireLong:=5plot(possiamoAprireLong,color=color.green)sonPassateLeBarreG = barssince(CondizioneAperturaLong) == BarsDelay?true:falsesonPassateLeBarreD = barssince(CondizioneChiusuraLong) == BarsDelay?true:falsehaiUnLongAncoraAperto = falsehaiUnLongAncoraAperto := strategy.position_size>0?true:false// Se l'ultimo valore della serie "CondizioneAperturaLong" è TRUE, allora hai un long ancora aperto// Se l'ultimo valore della serie "CondizioneAperturaLong" è FALSE, allora://       Se l'ultimo valore della serie "CondizioneChiusuraLong" è TRUE, allora NON hai un long ancora aperto //       Se l'ultimo valore della serie "CondizioneChiusuraLong" è FALSE, allora restituisce l'ultimo valore della serie "haiUnLongAncoraAperto"haiUnLongAncoraAperto_float = if(haiUnLongAncoraAperto==true)    10else    0plot(haiUnLongAncoraAperto_float,color=color.red) //FInché la linea rossa si trova a livello "1" allora c'è un ordine long in corsoquantita = (sizeordine/100*(capitaleIniziale+strategy.netprofit))/valuewhen(haiUnLongAncoraAperto==false and CondizioneAperturaLong,close,0)plot(sizeordine,color=color.purple, linewidth=3)if  strategy.position_size<=0 and CondizioneAperturaLong //and sonPassateLeBarreG and haiUnLongAncoraAperto==false strategy.opentrades==0    strategy.entry("Vamonos",strategy.long, alert_message=webhookLong, comment="OPEN LONG", qty=quantita)if  strategy.position_size>0 //and sonPassateLeBarreD // and CondizioneChiusuraLong     if siamoinuptrend == true and sonPassateLeBarreD        strategy.close("Vamonos", alert_message=webhookClose, comment="CLOSE LONG")    else if siamoinuptrend == false and CondizioneChiusuraLong        strategy.close("Vamonos", alert_message=webhookClose, comment="CLOSE LONG")    if strategy.position_size>0 and siamoindata    strategy.exit("Vamonos", stop=stop_level_long, limit=take_level_long, alert_message=webhookClose, comment="CLOSE LONG (LIMIT/STOP)")short_separator = input(title="------------------------SHORT------------------------", defval = usiShort)    sl_short_inp = input(stopLossPercent_Short, title="Stop Loss SHORT %",type=input.float,step=0.1)tp_short_inp = input(takeProfitPercent_Short, title="Take Profit SHORT %",type=input.float,step=0.1)stop_level_short = strategy.position_avg_price * (1 + (sl_short_inp/100))take_level_short= strategy.position_avg_price * (1 - (tp_short_inp/100))// BINANCE JSON_short = '{"pair":"'+pair+'","isBuy":false,"isSell":true,"isMarket":true,"isLimit":false,"isClose":false,"price":"9147.62","units":"'+tostring(sizeordine)+'","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"10062.41","stopLossPercent":"-'+tostring(sl_short_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"7775.50","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_short_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}'webhookShort = JSON_shorttrendFilterS = input(title="TREND FILTER SHORT?", defval = true)siamoindowntrend_ema=EMAfast<EMAslow?true:false //close<=EMAfast and EMAfast<EMAslowsiamoindowntrend=siamoindowntrend_emaCondizioneAperturaShort = short_separator and siamoinipercomprato and siamoindata if trendFilterS    CondizioneAperturaShort:=short_separator and siamoinipercomprato and siamoindata and siamoindowntrendCondizioneChiusuraShort = siamoinipervenduto and siamoindatasonPassateLeBarreGs = barssince(CondizioneAperturaShort) == BarsDelay?true:falsesonPassateLeBarreDs = barssince(CondizioneChiusuraShort) == BarsDelay?true:falsehaiUnoShortAncoraAperto = falsehaiUnoShortAncoraAperto := strategy.position_size<0?true:falsehaiUnoShortAncoraAperto_float = if(haiUnoShortAncoraAperto==true)    15else    0plot(haiUnoShortAncoraAperto_float,color=color.purple) //FInché la linea viola si trova a livello "2" allora c'è un ordine short in corsoif CondizioneAperturaShort and strategy.position_size>=0 //and haiUnoShortAncoraAperto==false    strategy.entry("Andale",strategy.short,alert_message=webhookShort, comment="OPEN SHORT")if  strategy.position_size<0 //and sonPassateLeBarreD // and CondizioneChiusuraLong     if siamoindowntrend == true and sonPassateLeBarreDs        strategy.close("Andale",alert_message=webhookClose, comment="CLOSE SHORT")    else if siamoindowntrend == false and CondizioneChiusuraShort        strategy.close("Andale",alert_message=webhookClose, comment="CLOSE SHORT")if strategy.position_size<0 and siamoindata    strategy.exit("Andale", stop=stop_level_short, limit=take_level_short, alert_message=webhookClose, comment="CLOSE SHORT (LIMIT/STOP)")