Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Relative Returns Strategy

A Pine Script v4 strategy built on SMA or EMA or HMA or RMA or VWMA or WMA (source, length). It has 2 order rules, 1 entry among them, and trades long only with the default settings. Exits wait for a signal; there is no stop loss. Each trade commits 100% of equity and pays 0.01% commission. 8 settings; defaults include Index ticker XJO, Loopback 40 and Moving Average Type sma.

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 Relative Returns Strategy repaint?
Yes
At least one pattern in the source can repaint: higher-timeframe data.
How did Relative Returns Strategy 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 code limits trading to a date window, which can leave this period out. It closed no trades on the other markets either. A backtest, not investment advice.
Can Relative Returns Strategy be converted to Pine Script v5?
Not tested
The steps are shown below, but neither version placed a trade on any market tested, so there was nothing to compare and no download is offered.
Does Relative Returns Strategy use a stop loss?
No
Every exit waits for a signal; nothing limits a losing trade before it fires.
Does Relative Returns Strategy run in Zeal Terminal?
Yes
It compiles in 15 ms and runs 1,000 bars in 55 ms, in the browser.

BTCUSDT · 1D · default settings

  • StockReturn
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOctStockReturn$100,000$202,527Equity from $100,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 live re-run is not offered here: the script requests XJO 1D, which this page cannot load in your browser.

Needs XJO 1D data, not available: not a Binance spot market Values that depend on it are empty on this chart.

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, $100,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

    No stop loss

    Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    5 settings have no label

    In the settings dialog index_ticker (line 5), Loopback (line 6), useStopAndIndexReturns (line 7), useStopAndIndexReturnsMa (line 8), MALength (line 11) 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 42, 43. 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.
  • 2 strategy calls use the when = argument (line 42, 43). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 3: //@version=4 → //@version=5
  • Line 12: input(type = input.time) → input.time()
  • Line 13: input(type = input.time) → input.time()
  • Line 15: security → request.security
  • Line 17: sma → ta.sma
  • Line 19: ema → ta.ema
4 more edits
  • Line 21: hma → ta.hma
  • Line 23: rma → ta.rma
  • Line 25: vwma → ta.vwma
  • Line 27: wma → ta.wma
⋯// © HeWhoMustNotBeNamed-//@version=4+//@version=5strategy("Relative Returns Strategy", overlay=false, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)⋯MALength = input(10, minval=10,step=10)-i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Backtest Start Time", type = input.time)+i_startTime = input.time(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Backtest Start Time")-i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "Backtest End Time", type = input.time)+i_endTime = input.time(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "Backtest End Time")inDateRange = time >= i_startTime and time <= i_endTime-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⋯

Clean v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 5: input() → input.string()
  • Line 6: input() → input.int()
  • Line 7: input() → input.bool()
  • Line 8: input() → input.bool()
  • Line 10: input() → input.string()
  • Line 11: input() → input.int()
  • Line 42: when = buyCondition and inDateRange → if block
  • Line 43: when = closeBuyCondition → if block
⋯strategy("Relative Returns Strategy", overlay=false, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)-index_ticker=input("XJO")+index_ticker=input.string("XJO")-Loopback = input(40, step=20)+Loopback = input.int(40, step=20)-useStopAndIndexReturns = input(true)+useStopAndIndexReturns = input.bool(true)-useStopAndIndexReturnsMa = input(true)+useStopAndIndexReturnsMa = input.bool(true)useDifference = not useStopAndIndexReturns-MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])+MAType = input.string(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])-MALength = input(10, minval=10,step=10)+MALength = input.int(10, minval=10,step=10)i_startTime = input.time(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Backtest Start Time")⋯closeBuyCondition = (useStopAndIndexReturns ? useStopAndIndexReturnsMa ? stock_return_ma < index_return_ma : stock_return < index_return : relativeReturns < relativeReturns_ma)-strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca", oca_type=strategy.oca.cancel)+if buyCondition and inDateRange+    strategy.entry("Buy", strategy.long, oca_name="oca", oca_type=strategy.oca.cancel)-strategy.close("Buy", when=closeBuyCondition)+if closeBuyCondition+    strategy.close("Buy")

Does it run in Pine Script v6?

Not tested

Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version 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("Relative Returns Strategy", overlay=false, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)⋯

Settings

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

SettingDefaultType and rangeFeeds
Index ticker (no label in the script)XJOstringindex
Loopback (no label in the script)40int · step 20stock_return index_return
Use Stop And Index Returns (no label in the script)truebooluseDifference buyCondition closeBuyCondition StockReturn IndexReturn
Use Stop And Index Returns MA (no label in the script)trueboolbuyCondition closeBuyCondition StockReturn IndexReturn
Moving Average Typesmastring · options ["ema", "sma", "hma", "rma", "vwma", "wma"]stock_return_ma index_return_ma relativeReturns_ma line 18 line 20 line 22 line 24 line 26
MALength (no label in the script)10int · min 10 · step 10stock_return_ma index_return_ma relativeReturns_ma
Backtest Start Timetimestamp("01 Jan 2010 00:00 +0000")timeinDateRange
Backtest 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 17

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 dataindex_tickerIndex tickersetting · XJOLoopbackLoopbacksetting · 40MATypeMoving Average Typesetting · smaMALengthMALengthsetting · 10timetimeprice datai_startTimeBacktest Start Timesetting · timestamp("01 Jan 2…i_endTimeBacktest End Timesetting · timestamp("01 Jan 2…maSMA / EMA / HMA / RMA /…→ maindexindexvaluestock_returnstock_returnvalueindex_returnindex_returnvaluestock_return_mastock_return_mavalueindex_return_maindex_return_mavaluerelativeReturnsrelativeReturnsvaluerelativeReturns_marelativeReturns_mavaluebuyCondition, closeBuyConditionbuyCondition · closeBuy…2 valuesuseDifferenceuseDifferenceconditioninDateRangeinDateRangeconditionentry:BuyOpen Buystrategy.entryclose:BuyClose Buystrategy.closeplot:36StockReturnplotplot:37IndexReturnplotplot:38Relative-Returnsplotplot:39MAplot

Order rules

OrderFires whenBy defaultLine
Open Buy longbuyCondition and inDateRangeOn42
Close BuycloseBuyConditionOn43

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.
  • CheckHigher-timeframe data1 security call(s) use lookahead_on (line 15). 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

Not run on other markets: the script requests XJO 1D, and that data is not available here (not a Binance spot market). Its results would rest on empty values.

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
Relative Returns Strategy this page—v4 strategy0.0%00.0%
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
Multi Trend Cross Strategy Template by TradeAutomationema hma rma sma vwma wmav5 strategy+33.0%37.3%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 15 msYes 1,000 bars in 55 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/// © HeWhoMustNotBeNamed//@version=4strategy("Relative Returns Strategy", overlay=false, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)index_ticker=input("XJO")Loopback = input(40, step=20)useStopAndIndexReturns = input(true)useStopAndIndexReturnsMa = input(true)useDifference = not useStopAndIndexReturnsMAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])MALength = input(10, minval=10,step=10)i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Backtest Start Time", type = input.time)i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "Backtest End Time", type = input.time)inDateRange = time >= i_startTime and time <= i_endTimef_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)    maindex = f_secureSecurity(index_ticker, '1D', close, 0)stock_return = (close - close[Loopback])*100/closeindex_return = (index - index[Loopback])*100/indexstock_return_ma = f_getMovingAverage(stock_return, MAType, MALength)index_return_ma = f_getMovingAverage(index_return, MAType, MALength)relativeReturns = stock_return - index_returnrelativeReturns_ma = f_getMovingAverage(relativeReturns, MAType, MALength)plot(useStopAndIndexReturns ? useStopAndIndexReturnsMa ? stock_return_ma : stock_return : na, title="StockReturn", color=color.green, linewidth=1)plot(useStopAndIndexReturns ? useStopAndIndexReturnsMa ? index_return_ma : index_return : na, title="IndexReturn", color=color.red, linewidth=1)plot(useDifference?relativeReturns:na, title="Relative-Returns", color=color.blue, linewidth=1)plot(useDifference?relativeReturns_ma:na, title="MA", color=color.red, linewidth=1)buyCondition = (useStopAndIndexReturns ? useStopAndIndexReturnsMa ? stock_return_ma > index_return_ma : stock_return > index_return : relativeReturns > relativeReturns_ma)closeBuyCondition = (useStopAndIndexReturns ? useStopAndIndexReturnsMa ? stock_return_ma < index_return_ma : stock_return < index_return : relativeReturns < relativeReturns_ma)strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca", oca_type=strategy.oca.cancel)strategy.close("Buy", when=closeBuyCondition)