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
- 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
DiffersTrades 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
VerifiedSame 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Higher Timeframe (no label in the script) | W | timeframe (written input.resolution) | maHTF maHTFHigh maHTFLow |
| HTF Moving Average Type | hma | string · options ["ema", "sma", "hma", "rma", "vwma", "wma"] | maHTF maHTFHigh maHTFLow |
| HTFMa Length (no label in the script) | 20 | int · step 10 | maHTF maHTFHigh maHTFLow |
| HTFUse High Low Range (no label in the script) | true | bool | buyCondition sellCondition |
| ATR Length (no label in the script) | 16 | int · step 5 | supertrend dir |
| ATR Mult (no label in the script) | 3 | int · step 0.5 | supertrend dir |
| Wait For Close Before Exit (no label in the script) | false | bool | close Long exit ExitLong close Short exit ExitShort |
| Trade Filters | |||
| Trade Direction | strategy.direction.all | value · options [strategy.direction.all, strategy.direction.long, strategy.direction.short] | line 15 |
| Start Time | timestamp("01 Jan 2010 00:00 +0000") | time | inDateRange |
| End Time | timestamp("01 Jan 2099 00:00 +0000") | time | inDateRange |
What it calculates
- SMA / EMA / HMA / RMA / VWMA / WMA (
sma,ta.smain v5)source, lengthma · line 22 - Supertrend (
supertrend,ta.supertrendin v5)ATR Mult (3), ATR Length (16)supertrend · line 38 - Supertrend (
supertrend,ta.supertrendin v5)ATR Mult (3), ATR Length (16)dir · line 38 - Crossover (
crossover,ta.crossoverin v5)0, dirbuyCondition · line 43 - Crossunder (
crossunder,ta.crossunderin v5)0, dircloseBuyCondition · line 44 - Crossunder (
crossunder,ta.crossunderin v5)0, dirsellCondition · line 45 - Crossover (
crossover,ta.crossoverin 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | buyCondition | On | 47 |
| Close Long | closeBuyCondition and waitForCloseBeforeExit | On | 48 |
| Exit ExitLong stop | not waitForCloseBeforeExit | On | 49 |
| Open Short short | sellCondition | On | 50 |
| Close Short | closeSellCondition and waitForCloseBeforeExit | On | 51 |
| Exit ExitShort stop | not waitForCloseBeforeExit | On | 52 |
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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −21.8% | +102.5% | 11 | 27% | 0.59 | 40.5% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +3.8% | +5.5% | 10 | 20% | 1.23 | 9.1% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +54.8% | +9.8% | 11 | 64% | 1.86 | 24.4% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +28.7% | +8.4% | 10 | 40% | 2.47 | 8.2% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −30.9% | +16.7% | 9 | 33% | 0.47 | 36.7% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +3.3% | +21.5% | 7 | 29% | 1.21 | 12.4% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +0.2% | +148.3% | 13 | 38% | 1.01 | 31.2% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +6.4% | +17.1% | 11 | 64% | 1.71 | 5.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 1 | 100% | $4,095.97 |
| Sideways market | 9 | 22% | −$5,653.55 |
| Falling market | 1 | 0% | −$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.
All 11 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 15 Feb 2024 51,795.20 | 19 Mar 2024 63,594.10 | 33 | $4,095.97 |
| short | 22 Jun 2024 64,143.60 | 15 Jul 2024 62,149.30 | 23 | $669.89 |
| long | 20 Sep 2024 62,948.00 | 10 Oct 2024 59,629.90 | 20 | −$1,179.13 |
| short | 25 Feb 2025 91,552.90 | 2 Mar 2025 93,455.40 | 5 | −$445.37 |
| short | 11 Mar 2025 78,595.90 | 22 Apr 2025 89,157.00 | 42 | −$2,802.77 |
| long | 23 Apr 2025 93,443.00 | 5 Jun 2025 101,553.00 | 43 | $1,584.70 |
| long | 14 Aug 2025 123,306.00 | 19 Aug 2025 112,864.00 | 5 | −$1,674.56 |
| short | 22 Aug 2025 112,500.00 | 18 Sep 2025 117,610.00 | 27 | −$831.48 |
| long | 2 Oct 2025 118,595.00 | 10 Oct 2025 116,616.00 | 8 | −$295.06 |
| long | 15 Jan 2026 96,951.80 | 20 Jan 2026 88,385.40 | 5 | −$1,523.76 |
| long | 17 Mar 2026 74,884.70 | 27 Mar 2026 65,636.60 | 10 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Strategy Template this page | — | v4 strategy | −21.8% | 11 | 40.5% |
| Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTEST by TraderHalai | sma ema hma vwma rma | v5 strategy | +1.3% | 113 | 5.6% |
| High-Low Channel Multi averages Crypto Swing strategy by exlux99 | sma ema wma rma vwma | v4 strategy | No trades on this market | ||
| Ultra Moving Average Rating Trend Strategy by exlux99 | ema wma sma rma vwma hma | v5 strategy | +2.8% | 5 | 2.4% |
| VCP pivot buy by perrycc007 | sma ema rma vwma wma | v4 strategy | does not run in Zeal Terminal | ||
| Strategy Myth-Busting #3 - BB_BUY+SuperTrend - [MYN] by myncrypto | ema sma supertrend rma | v5 strategy | −115.1% | 6 | 123.3% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 37 ms | With a workaround 1,000 bars in 99 ms | Not measured |
| PineTS | No 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)