Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Strategy Template

A Pine Script v4 strategy built on SMA or EMA or HMA or RMA or VWMA or WMA (source, length), Supertrend (3, 16) and Crossover (0, dir). It has 6 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade commits 90% of equity and pays 0.01% commission. 10 settings; defaults include Higher Timeframe W, HTF Moving Average Type hma and HTFMa Length 20.

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 Strategy Template repaint?
Yes
At least one pattern in the source can repaint: higher-timeframe data.
How did Strategy Template do on BTCUSDT 1D with default settings?
−21.81%
From 26 Jan 2024 to 21 Oct 2026, over 11 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Strategy Template be converted to Pine Script v5?
No
The automatic step from v4 to v5 changes the results, so no v5 download is offered; the edits are shown below.
Does Strategy Template use a stop loss?
Yes
strategy.exit sets a stop on line 49, 52.
Does Strategy Template run in Zeal Terminal?
Yes
It compiles in 37 ms and runs 1,000 bars in 99 ms, in the browser.

BTCUSDT · 1D · default settings

  • MTF MA High
  • MTF MA Low
  • Trailing Stop
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$19,477$40,505Equity from $20,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. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market. The live re-run is not offered here: the script requests BINANCE:BTCUSDT W, which this page cannot load in your browser.
Net profit
−21.81%
−$4,361.75
Buy and hold
+102.5%
same period
Closed trades
11
3 won · 8 lost
Profitable
27.3%
of closed trades
Profit factor
0.59
gross profit ÷ gross loss
Max drawdown
40.51%
−$10,032.90

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

  • Note

    6 settings have no label

    In the settings dialog HigherTimeframe (line 7), HTFMaLength (line 9), HTFUseHighLowRange (line 10), atrLength (line 11), atrMult (line 12), waitForCloseBeforeExit (line 19) show 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.

  • Note

    Uses an argument v6 removed

    when = on line 47, 48, 49, 50, 51, 52. The upgraded version below moves each call inside an if block.

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 security → request.security, sma → ta.sma, ema → ta.ema, hma → ta.hma, rma → ta.rma, vwma → ta.vwma, wma → ta.wma, supertrend → ta.supertrend, crossover → ta.crossover, crossunder → ta.crossunder.
  • 6 strategy calls use the when = argument (line 47, 48, 49, 50, 51, 52). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Differs

Trades differ: 11 before, 11 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 3: //@version=4 → //@version=5
  • Line 7: input(type = input.resolution) → input.timeframe()
  • Line 16: input(type = input.time) → input.time()
  • Line 17: input(type = input.time) → input.time()
  • Line 20: security → request.security
  • Line 22: sma → ta.sma
10 more edits
  • Line 24: ema → ta.ema
  • Line 26: hma → ta.hma
  • Line 28: rma → ta.rma
  • Line 30: vwma → ta.vwma
  • Line 32: wma → ta.wma
  • Line 38: supertrend → ta.supertrend
  • Line 43: crossover → ta.crossover
  • Line 44: crossunder → ta.crossunder
  • Line 45: crossunder → ta.crossunder
  • Line 46: crossover → ta.crossover
⋯// © HeWhoMustNotBeNamed-//@version=4+//@version=5strategy("Strategy Template", overlay=true, initial_capital = 20000, default_qty_type = strategy.percent_of_equity,⋯             margin_long=90, margin_short=90, max_lines_count=500, max_labels_count=500, max_boxes_count=500)-HigherTimeframe = input("W", type=input.resolution)+HigherTimeframe = input.timeframe("W")HTFMAType = input(title="HTF Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])⋯strategy.risk.allow_entry_in(tradeDirection)-i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time, group="Trade Filters")+i_startTime = input.time(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", group="Trade Filters")-i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time, group="Trade Filters")+i_endTime = input.time(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", group="Trade Filters")inDateRange = time >= i_startTime and time <= i_endTimewaitForCloseBeforeExit = input(false)-f_secureSecurity(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on)+f_secureSecurity(_symbol, _res, _src, _offset) => request.security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on)f_getMovingAverage(source, MAType, length)=>-    ma = sma(source, length)+    ma = ta.sma(source, length)    if(MAType == "ema")-        ma := ema(source,length)+        ma := ta.ema(source,length)    if(MAType == "hma")-        ma := hma(source,length)+        ma := ta.hma(source,length)    if(MAType == "rma")-        ma := rma(source,length)+        ma := ta.rma(source,length)    if(MAType == "vwma")-        ma := vwma(source,length)+        ma := ta.vwma(source,length)    if(MAType == "wma")-        ma := wma(source,length)+        ma := ta.wma(source,length)    ma⋯maHTFLow = f_secureSecurity(syminfo.tickerid, HigherTimeframe, f_getMovingAverage(low, HTFMAType, HTFMaLength), 1)-[supertrend, dir] = supertrend(atrMult, atrLength)+[supertrend, dir] = ta.supertrend(atrMult, atrLength)mh = plot(maHTFHigh, "MTF MA High", color=color.new(color.green, 90))⋯plot(strategy.position_size != 0 ? supertrend : na, title="Trailing Stop", color=dir < 0? color.green : color.red, style=plot.style_stepline)-buyCondition = crossover(0, dir) and (close > (HTFUseHighLowRange? maHTFHigh : maHTF)) and inDateRange+buyCondition = ta.crossover(0, dir) and (close > (HTFUseHighLowRange? maHTFHigh : maHTF)) and inDateRange-closeBuyCondition = crossunder(0, dir)+closeBuyCondition = ta.crossunder(0, dir)-sellCondition = crossunder(0, dir) and (close < (HTFUseHighLowRange? maHTFLow : maHTF)) and inDateRange+sellCondition = ta.crossunder(0, dir) and (close < (HTFUseHighLowRange? maHTFLow : maHTF)) and inDateRange-closeSellCondition = crossover(0, dir)+closeSellCondition = ta.crossover(0, dir)strategy.entry("Long", strategy.long, when=buyCondition, oca_name="oca_buy", oca_type=strategy.oca.cancel)⋯

Clean v5

Verified

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

  • Line 8: input() → input.string()
  • Line 9: input() → input.int()
  • Line 10: input() → input.bool()
  • Line 11: input() → input.int()
  • Line 12: input() → input.int()
  • Line 19: input() → input.bool()
6 more edits
  • Line 47: when = buyCondition → if block
  • Line 48: when = closeBuyCondition and waitForCloseBeforeExit → if block
  • Line 49: when = not waitForCloseBeforeExit → if block
  • Line 50: when = sellCondition → if block
  • Line 51: when = closeSellCondition and waitForCloseBeforeExit → if block
  • Line 52: when = not waitForCloseBeforeExit → if block
⋯HigherTimeframe = input.timeframe("W")-HTFMAType = input(title="HTF Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])+HTFMAType = input.string(title="HTF Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])-HTFMaLength= input(20, step=10)+HTFMaLength= input.int(20, step=10)-HTFUseHighLowRange = input(true)+HTFUseHighLowRange = input.bool(true)-atrLength = input(16, step=5)+atrLength = input.int(16, step=5)-atrMult = input(3, step=0.5)+atrMult = input.int(3, step=0.5)tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, ⋯inDateRange = time >= i_startTime and time <= i_endTime-waitForCloseBeforeExit = input(false)+waitForCloseBeforeExit = input.bool(false)f_secureSecurity(_symbol, _res, _src, _offset) => request.security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on)⋯closeSellCondition = ta.crossover(0, dir)-strategy.entry("Long", strategy.long, when=buyCondition, oca_name="oca_buy", oca_type=strategy.oca.cancel)+if buyCondition+    strategy.entry("Long", strategy.long, oca_name="oca_buy", oca_type=strategy.oca.cancel)-strategy.close("Long", when=closeBuyCondition and waitForCloseBeforeExit)+if closeBuyCondition and waitForCloseBeforeExit+    strategy.close("Long")-strategy.exit("ExitLong", "Long", stop=supertrend, when=not waitForCloseBeforeExit)+if not waitForCloseBeforeExit+    strategy.exit("ExitLong", "Long", stop=supertrend)-strategy.entry("Short", strategy.short, when=sellCondition, oca_name="oca_sell", oca_type=strategy.oca.cancel)+if sellCondition+    strategy.entry("Short", strategy.short, oca_name="oca_sell", oca_type=strategy.oca.cancel)-strategy.close("Short", when=closeSellCondition and waitForCloseBeforeExit)+if closeSellCondition and waitForCloseBeforeExit+    strategy.close("Short")-strategy.exit("ExitShort", "Short", stop=supertrend, when=not waitForCloseBeforeExit)+if not waitForCloseBeforeExit+    strategy.exit("ExitShort", "Short", stop=supertrend)

Does it run in Pine Script v6?

No

Same 11 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. The v6 version matches the upgraded v5 version, but the upgrade from the original already changed the results, so it is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © HeWhoMustNotBeNamed-//@version=5+//@version=6strategy("Strategy Template", overlay=true, initial_capital = 20000, default_qty_type = strategy.percent_of_equity,⋯

Settings

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

SettingDefaultType and rangeFeeds
Higher Timeframe (no label in the script)Wtimeframe (written input.resolution)maHTF maHTFHigh maHTFLow
HTF Moving Average Typehmastring · options ["ema", "sma", "hma", "rma", "vwma", "wma"]maHTF maHTFHigh maHTFLow
HTFMa Length (no label in the script)20int · step 10maHTF maHTFHigh maHTFLow
HTFUse High Low Range (no label in the script)trueboolbuyCondition sellCondition
ATR Length (no label in the script)16int · step 5supertrend dir
ATR Mult (no label in the script)3int · step 0.5supertrend dir
Wait For Close Before Exit (no label in the script)falseboolclose Long exit ExitLong close Short exit ExitShort
Trade Filters
Trade Directionstrategy.direction.allvalue · options [strategy.direction.all, strategy.direction.long, strategy.direction.short]line 15
Start Timetimestamp("01 Jan 2010 00:00 +0000")timeinDateRange
End Timetimestamp("01 Jan 2099 00:00 +0000")timeinDateRange

What it calculates

  • SMA / EMA / HMA / RMA / VWMA / WMA (sma, ta.sma in v5)source, lengthma · line 22
  • Supertrend (supertrend, ta.supertrend in v5)ATR Mult (3), ATR Length (16)supertrend · line 38
  • Supertrend (supertrend, ta.supertrend in v5)ATR Mult (3), ATR Length (16)dir · line 38
  • Crossover (crossover, ta.crossover in v5)0, dirbuyCondition · line 43
  • Crossunder (crossunder, ta.crossunder in v5)0, dircloseBuyCondition · line 44
  • Crossunder (crossunder, ta.crossunder in v5)0, dirsellCondition · line 45
  • Crossover (crossover, ta.crossover in v5)0, dircloseSellCondition · line 46

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.

high · low · closehigh · low · closeprice dataatrMultATR Multsetting · 3atrLengthATR Lengthsetting · 16closecloseprice dataHigherTimeframeHigher Timeframesetting · WHTFMATypeHTF Moving Average Typesetting · hmaHTFMaLengthHTFMa Lengthsetting · 20highhighprice datalowlowprice datatimetimeprice datai_startTimeStart Timesetting · timestamp("01 Jan 2…i_endTimeEnd Timesetting · timestamp("01 Jan 2…maSMA / EMA / HMA / RMA /…→ masupertrendSupertrend→ supertrenddirSupertrend→ dirbuyConditionCrossover→ buyConditioncloseBuyConditionCrossunder→ closeBuyConditionsellConditionCrossunder→ sellConditioncloseSellConditionCrossover→ closeSellConditionmaHTFmaHTFvaluemaHTFHighmaHTFHighvaluemaHTFLowmaHTFLowvalueinDateRangeinDateRangeconditionentry:LongOpen Longstrategy.entryclose:LongClose Longstrategy.closeexit:ExitLongexit ExitLongstrategy.exitentry:ShortOpen Shortstrategy.entryclose:ShortClose Shortstrategy.closeexit:ExitShortexit ExitShortstrategy.exitplot:39MTF MA Highplotplot:40MTF MA Lowplotfill:No Trade ZoneNo Trade Zonefillplot:42Trailing Stopplot

Order rules

OrderFires whenBy defaultLine
Open Long longbuyConditionOn47
Close LongcloseBuyCondition and waitForCloseBeforeExitOn48
Exit ExitLong stopnot waitForCloseBeforeExitOn49
Open Short shortsellConditionOn50
Close ShortcloseSellCondition and waitForCloseBeforeExitOn51
Exit ExitShort stopnot waitForCloseBeforeExitOn52

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.

2/2trades 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.
  • CheckHigher-timeframe data1 security call(s) use lookahead_on (line 20). Without a [1] offset this reads future bars in history.
  • 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−21.8%+102.5%1127%0.5940.5%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+3.8%+5.5%1020%1.239.1%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+54.8%+9.8%1164%1.8624.4%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+28.7%+8.4%1040%2.478.2%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−30.9%+16.7%933%0.4736.7%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+3.3%+21.5%729%1.2112.4%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+0.2%+148.3%1338%1.0131.2%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+6.4%+17.1%1164%1.715.0%8 May 2026 – 21 Oct 2026

Higher-timeframe data for request.security(): BINANCE:BTCUSDT W (Binance BTCUSDT 1w), fetched from Binance's public market data for each market.

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

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market1100%$4,095.97
Sideways market922%−$5,653.55
Falling market10%−$2,802.77

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

How bad could the drawdown be?

39.8%

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

0%46%
All 11 trades
SideEntryExitBarsP&L
long15 Feb 2024 51,795.2019 Mar 2024 63,594.1033$4,095.97
short22 Jun 2024 64,143.6015 Jul 2024 62,149.3023$669.89
long20 Sep 2024 62,948.0010 Oct 2024 59,629.9020−$1,179.13
short25 Feb 2025 91,552.902 Mar 2025 93,455.405−$445.37
short11 Mar 2025 78,595.9022 Apr 2025 89,157.0042−$2,802.77
long23 Apr 2025 93,443.005 Jun 2025 101,553.0043$1,584.70
long14 Aug 2025 123,306.0019 Aug 2025 112,864.005−$1,674.56
short22 Aug 2025 112,500.0018 Sep 2025 117,610.0027−$831.48
long2 Oct 2025 118,595.0010 Oct 2025 116,616.008−$295.06
long15 Jan 2026 96,951.8020 Jan 2026 88,385.405−$1,523.76
long17 Mar 2026 74,884.7027 Mar 2026 65,636.6010−$1,958.80

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
Strategy Template this page—v4 strategy−21.8%1140.5%
Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTEST by TraderHalaisma ema hma vwma rmav5 strategy+1.3%1135.6%
High-Low Channel Multi averages Crypto Swing strategy by exlux99sma ema wma rma vwmav4 strategyNo trades on this market
Ultra Moving Average Rating Trend Strategy by exlux99ema wma sma rma vwma hmav5 strategy+2.8%52.4%
VCP pivot buy by perrycc007sma ema rma vwma wmav4 strategydoes not run in Zeal Terminal
Strategy Myth-Busting #3 - BB_BUY+SuperTrend - [MYN] by myncryptoema sma supertrend rmav5 strategy−115.1%6123.3%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 37 msWith a workaround 1,000 bars in 99 msNot measured
PineTSNo v5 and v6 only—Not measured

The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © HeWhoMustNotBeNamed//@version=4strategy("Strategy Template", overlay=true, initial_capital = 20000, default_qty_type = strategy.percent_of_equity,             default_qty_value = 90, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01,             margin_long=90, margin_short=90, max_lines_count=500, max_labels_count=500, max_boxes_count=500)HigherTimeframe = input("W", type=input.resolution)HTFMAType = input(title="HTF Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])HTFMaLength= input(20, step=10)HTFUseHighLowRange = input(true)atrLength = input(16, step=5)atrMult = input(3, step=0.5)tradeDirection = input(title="Trade Direction", defval=strategy.direction.all,              options=[strategy.direction.all, strategy.direction.long, strategy.direction.short], group="Trade Filters")strategy.risk.allow_entry_in(tradeDirection)i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time, group="Trade Filters")i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time, group="Trade Filters")inDateRange = time >= i_startTime and time <= i_endTimewaitForCloseBeforeExit = input(false)f_secureSecurity(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on)f_getMovingAverage(source, MAType, length)=>    ma = sma(source, length)    if(MAType == "ema")        ma := ema(source,length)    if(MAType == "hma")        ma := hma(source,length)    if(MAType == "rma")        ma := rma(source,length)    if(MAType == "vwma")        ma := vwma(source,length)    if(MAType == "wma")        ma := wma(source,length)    ma    maHTF = f_secureSecurity(syminfo.tickerid, HigherTimeframe, f_getMovingAverage(close, HTFMAType, HTFMaLength), 1)maHTFHigh = f_secureSecurity(syminfo.tickerid, HigherTimeframe, f_getMovingAverage(high, HTFMAType, HTFMaLength), 1)maHTFLow = f_secureSecurity(syminfo.tickerid, HigherTimeframe, f_getMovingAverage(low, HTFMAType, HTFMaLength), 1)[supertrend, dir] = supertrend(atrMult, atrLength)mh = plot(maHTFHigh, "MTF MA High", color=color.new(color.green, 90))ml = plot(maHTFLow, "MTF MA Low", color=color.new(color.red, 90))fill(mh, ml, title="No Trade Zone", color=color.new(color.yellow, 50))plot(strategy.position_size != 0 ? supertrend : na, title="Trailing Stop", color=dir < 0? color.green : color.red, style=plot.style_stepline)buyCondition = crossover(0, dir) and (close > (HTFUseHighLowRange? maHTFHigh : maHTF)) and inDateRangecloseBuyCondition = crossunder(0, dir)sellCondition = crossunder(0, dir) and (close < (HTFUseHighLowRange? maHTFLow : maHTF)) and inDateRangecloseSellCondition = crossover(0, dir)strategy.entry("Long", strategy.long, when=buyCondition, oca_name="oca_buy", oca_type=strategy.oca.cancel)strategy.close("Long", when=closeBuyCondition and waitForCloseBeforeExit)strategy.exit("ExitLong", "Long", stop=supertrend, when=not waitForCloseBeforeExit)strategy.entry("Short", strategy.short, when=sellCondition, oca_name="oca_sell", oca_type=strategy.oca.cancel)strategy.close("Short", when=closeSellCondition and waitForCloseBeforeExit)strategy.exit("ExitShort", "Short", stop=supertrend, when=not waitForCloseBeforeExit)