Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Moving Regression Band Breakout strategy

A Pine Script v4 strategy built on ATR (14), Crossover (close, highband) and Crossunder (close, lowband). It has 5 order rules, 2 entries among them, and trades long and short with the default settings. Exits wait for a signal; there is no stop loss. Each trade is one contract and pays no commission. 16 settings; defaults include Source close, Local Polynomial Degree 2 and Length (must be larger than degree) 80.

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 Moving Regression Band Breakout strategy 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 Moving Regression Band Breakout strategy do on BTCUSDT 1D with default settings?
+19.17%
From 26 Jan 2024 to 21 Oct 2026, over 13 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Moving Regression Band Breakout strategy 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.
What alerts does Moving Regression Band Breakout strategy have?
4
syminfo.tickerid+" Long Signal Triggered"; syminfo.tickerid+" Short Signal Triggered"; syminfo.tickerid+" Exit Signal Triggered for Long Position"; syminfo.tickerid+" Exit Signal Triggered for Short Position".
Does Moving Regression Band Breakout strategy use a stop loss?
No
Every exit waits for a signal; nothing limits a losing trade before it fires.

BTCUSDT · 1D · default settings

  • Upper Band
  • Lower Band
  • MR Prediction
  • sl
  • 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 (16)
0.0050,000100,000AprJulOct2025AprJulOct2026AprJulOct$119,171$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. Zeal Terminal's engine currently reads an order side written as true, false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 278, 281) so the engine trades the way the script says.
Net profit
+19.17%
$19,174.90
Buy and hold
+102.5%
same period
Closed trades
13
5 won · 8 lost
Profitable
38.5%
of closed trades
Profit factor
1.64
gross profit ÷ gross loss
Max drawdown
20.24%
−$23,385.70

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

    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 fixedstart (line 205), backtest_start (line 207), fixedend (line 211), backtest_end (line 213) 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 transp =, which v5 removed line 228

    transp = on line 228, 229, 237, 239, 241, 272. 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 pow → math.pow, sqrt → math.sqrt, abs → math.abs, atr → ta.atr, crossover → ta.crossover, crossunder → ta.crossunder.

v4 → v5

Verified

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

  • Line 19: //@version=4 → //@version=5
  • Line 75: pow → math.pow
  • Line 76: sqrt → math.sqrt
  • Line 163: abs → math.abs
  • Line 171: pow → math.pow
  • Line 182: pow → math.pow
32 more edits
  • Line 186: pow → math.pow
  • Line 193: input(type = input.integer) → input.int()
  • Line 194: input(type = input.integer) → input.int()
  • Line 195: input(type = input.float) → input.float()
  • Line 197: input(type = input.bool) → input.bool()
  • Line 198: input(type = input.bool) → input.bool()
  • Line 205: input(type = input.bool) → input.bool()
  • Line 207: input(type = input.time) → input.time()
  • Line 211: input(type = input.bool) → input.bool()
  • Line 213: input(type = input.time) → input.time()
  • Line 217: input(type = input.bool) → input.bool()
  • Line 218: input(type = input.bool) → input.bool()
  • Line 219: input(type = input.bool) → input.bool()
  • Line 228: transp = 40 → color.new(#3C94B8, 40)
  • Line 229: transp = 40 → color.new(#B83C94, 40)
  • Line 237: transp = clinetype=="Previous-Period MR Prediction"?100:20 → color.new(plt_color, clinetype=="Previous-Period MR Prediction"?100:20)
  • Line 239: transp = clinetype=="MR"?100:20 → color.new(plt_color, clinetype=="MR"?100:20)
  • Line 241: transp = clinetype!="Ribbon"?100:20 → color.new(plt_color, clinetype!="Ribbon"?100:20)
  • Line 243: atr → ta.atr
  • Line 244: crossover → ta.crossover
  • Line 245: crossunder → ta.crossunder
  • Line 246: crossover → ta.crossover
  • Line 247: crossunder → ta.crossunder
  • Line 269: crossover → ta.crossover
  • Line 269: crossunder → ta.crossunder
  • Line 272: transp = 50 → color.new(stoplosscolor, 50)
  • Line 273: crossunder → ta.crossunder
  • Line 274: crossover → ta.crossover
  • Line 278: strategy.entry(…, true) → strategy.entry(…, strategy.long)
  • Line 281: strategy.entry(…, false) → strategy.entry(…, strategy.short)
  • Line 283: crossunder → ta.crossunder
  • Line 286: crossover → ta.crossover
⋯//-//@version=4+//@version=5strategy("Moving Regression Band Breakout strategy", shorttitle = "MRBand Strat", overlay=true)⋯    for i = 0 to _n-1-        _norm := _norm + pow(array.get(_X,i),2)+        _norm := _norm + math.pow(array.get(_X,i),2)-    sqrt(_norm)+    math.sqrt(_norm)qr_diag(_A,_nrows,_ncolumns) => ⋯        for i = 0 to _N-1-            _mae := _mae + abs(array.get(_x,i) - array.get(_xhat,i))/_N+            _mae := _mae + math.abs(array.get(_x,i) - array.get(_xhat,i))/_N    _mae⋯        for j = 0 to _degree-            matrix_set(_J,pow(i,j),i,j,_window)+            matrix_set(_J,math.pow(i,j),i,j,_window)    // Vector of raw datapoints:⋯    for i = 0 to _degree-        _Y := _Y + array.get(_a_coef,i)*pow(_window-1,i)+        _Y := _Y + array.get(_a_coef,i)*math.pow(_window-1,i)    // Trend Direction Forecast⋯    for i = 0 to _degree-        _Y_f := _Y_f + array.get(_a_coef,i)*pow(_window,i)+        _Y_f := _Y_f + array.get(_a_coef,i)*math.pow(_window,i)    // Calculates data estimate (needed for rmse)⋯src = input(title="Source", defval=close, group = "Model Parameters:")-degree = input(title="Local Polynomial Degree", type = input.integer, defval=2, minval = 0,  group = "Model Parameters:")+degree = input.int(title="Local Polynomial Degree", defval=2, minval = 0,  group = "Model Parameters:")-window = input(title="Length (must be larger than degree)", type = input.integer, defval=80, minval = 2,  group = "Model Parameters:")+window = input.int(title="Length (must be larger than degree)", defval=80, minval = 2,  group = "Model Parameters:")-mult = input(title="Multiplier", type=input.float,defval=2.0,minval=0.0,+mult = input.float(title="Multiplier",defval=2.0,minval=0.0,             group = "Model Parameters:", tooltip = "Defines the Band Width.")-doLong = input(title="Allow Long Entries", type=input.bool,defval=true, inline = "linealwd", group = "Allowed Entries:")+doLong = input.bool(title="Allow Long Entries",defval=true, inline = "linealwd", group = "Allowed Entries:")-doShort = input(title="Allow Short Entries", type=input.bool,defval=false, inline = "linealwd", group = "Allowed Entries:")+doShort = input.bool(title="Allow Short Entries",defval=false, inline = "linealwd", group = "Allowed Entries:")stoplong = input(title="Exit Long At", defval="Lower Band - ATR", ⋯                   inline = "lineexit", group = "Exit Conditions:")-fixedstart =input(title="", group = "Fixed Backtest Period Start/End Dates:",+fixedstart =input.bool(title="", group = "Fixed Backtest Period Start/End Dates:",-              inline = "linebac1", type = input.bool, defval = true)+              inline = "linebac1", defval = true)-backtest_start=input(title = "", type = input.time, inline = "linebac1", +backtest_start=input.time(title = "", inline = "linebac1",               group = "Fixed Backtest Period Start/End Dates:",⋯              tooltip="If deactivated, backtest staring from the first available price bar.")-fixedend =  input(title="", group = "Fixed Backtest Period Start/End Dates:",+fixedend =  input.bool(title="", group = "Fixed Backtest Period Start/End Dates:",-              inline = "linebac2", type = input.bool, defval = false)+              inline = "linebac2", defval = false)-backtest_end =input(title = "", type = input.time, inline = "linebac2", +backtest_end =input.time(title = "", inline = "linebac2",               group = "Fixed Backtest Period Start/End Dates:",⋯              tooltip="If deactivated, backtesting ends at the last available price bar.")-istoploss = input(title="Show Stop-Loss Line", type=input.bool,defval=true, group="Additional Options")+istoploss = input.bool(title="Show Stop-Loss Line",defval=true, group="Additional Options")-slopefilter = input(title="Enter Only When MR Slope is Positive/Negative", type=input.bool,defval=false, group="Additional Options")+slopefilter = input.bool(title="Enter Only When MR Slope is Positive/Negative",defval=false, group="Additional Options")-issignal = input(title="Show Breakout Signals Labels", type=input.bool,defval=false, group="Additional Options")+issignal = input.bool(title="Show Breakout Signals Labels",defval=false, group="Additional Options")clinetype = input(title="Show Central Line As", defval="Previous-Period MR Prediction", ⋯centralline = MR_f[1]-hbplt = plot(highband,title='Upper Band',color=#3C94B8,linewidth=2, transp = 40)+hbplt = plot(highband,title='Upper Band',color=color.new(#3C94B8, 40),linewidth=2)-lbplt = plot(lowband,title='Lower Band',color=#B83C94,linewidth=2, transp = 40)+lbplt = plot(lowband,title='Lower Band',color=color.new(#B83C94, 40),linewidth=2)fill(hbplt,lbplt,color=#3C94B8)⋯    plt_color := #B83C71-mrplt = plot(MR,title='MR',color=plt_color,linewidth=1,-             transp = clinetype=="Previous-Period MR Prediction"?100:20)+mrplt = plot(MR,title='MR',color=color.new(plt_color, clinetype=="Previous-Period MR Prediction"?100:20),linewidth=1)-mrfplt = plot(centralline,title='MR Prediction',color=plt_color,linewidth=1, -             transp = clinetype=="MR"?100:20)+mrfplt = plot(centralline,title='MR Prediction',color=color.new(plt_color, clinetype=="MR"?100:20),linewidth=1)-fill(mrplt,mrfplt,color=plt_color,transp = clinetype!="Ribbon"?100:20)+fill(mrplt,mrfplt,color=color.new(plt_color, clinetype!="Ribbon"?100:20))//  breakout signals-ATR = atr(14)+ATR = ta.atr(14)-Breakout = crossover(src,highband)+Breakout = ta.crossover(src,highband)-Breakdown = crossunder(src,lowband)+Breakdown = ta.crossunder(src,lowband)-ATRBreakout = crossover(src,highband + ATR)+ATRBreakout = ta.crossover(src,highband + ATR)-ATRBreakdown = crossunder(src,lowband - ATR)+ATRBreakdown = ta.crossunder(src,lowband - ATR)MRSlopesUp = MR>MR[1]⋯// move SL to position opening price if lowband crosses the initial SL-if (strategy.position_entry_name=="long" and crossover(trailinglong, opprice)) or (strategy.position_entry_name=="short" and crossunder(trailingshort, opprice))+if (strategy.position_entry_name=="long" and ta.crossover(trailinglong, opprice)) or (strategy.position_entry_name=="short" and ta.crossunder(trailingshort, opprice))    stoploss := oppricestoplosscolor = strategy.position_entry_name=="long"?#B83C94:(strategy.position_entry_name=="short"?#3C94B8:color.silver)-plot(istoploss?stoploss:na,title='sl',color=stoplosscolor,linewidth=1,transp=50)+plot(istoploss?stoploss:na,title='sl',color=color.new(stoplosscolor, 50),linewidth=1)-endLong = crossunder(src,trailinglong)+endLong = ta.crossunder(src,trailinglong)-endShort = crossover(src,trailingshort)+endShort = ta.crossover(src,trailingshort)// backtest⋯if goLong and isinrange and doLong-    strategy.entry("long",   true)+    strategy.entry("long",   strategy.long)    alert(syminfo.tickerid+" Long Signal Triggered",alert.freq_once_per_bar_close)if goShort and isinrange and doShort-    strategy.entry("short",  false)+    strategy.entry("short",  strategy.short)    alert(syminfo.tickerid+" Short Signal Triggered",alert.freq_once_per_bar_close)-if endLong or crossunder(src,stoploss)+if endLong or ta.crossunder(src,stoploss)    strategy.close("long")    alert(syminfo.tickerid+" Exit Signal Triggered for Long Position",alert.freq_once_per_bar_close)-if endShort or crossover(src,stoploss)+if endShort or ta.crossover(src,stoploss)    strategy.close("short")⋯

Clean v5

VerifiedDownload the v5 script

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

  • Line 192: input() → input.source()
  • Line 199: input() → input.string()
  • Line 202: input() → input.string()
  • Line 220: input() → input.string()
⋯/// --- main ----src = input(title="Source", defval=close, group = "Model Parameters:")+src = input.source(title="Source", defval=close, group = "Model Parameters:")degree = input.int(title="Local Polynomial Degree", defval=2, minval = 0,  group = "Model Parameters:")⋯doShort = input.bool(title="Allow Short Entries",defval=false, inline = "linealwd", group = "Allowed Entries:")-stoplong = input(title="Exit Long At", defval="Lower Band - ATR", +stoplong = input.string(title="Exit Long At", defval="Lower Band - ATR",                    options = ["Lower Band","Lower Band - ATR","Central Line"],                   inline = "lineexit", group = "Exit Conditions:")-stopshort = input(title="Exit Short At", defval="Central Line", +stopshort = input.string(title="Exit Short At", defval="Central Line",                    options = ["Upper Band","Upper Band + ATR","Central Line"],⋯issignal = input.bool(title="Show Breakout Signals Labels",defval=false, group="Additional Options")-clinetype = input(title="Show Central Line As", defval="Previous-Period MR Prediction", +clinetype = input.string(title="Show Central Line As", defval="Previous-Period MR Prediction",                   options = ["Ribbon","MR","Previous-Period MR Prediction"], group="Additional Options")⋯

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 13 before, 13 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯//-//@version=5+//@version=6strategy("Moving Regression Band Breakout strategy", shorttitle = "MRBand Strat", overlay=true)⋯

Settings

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

SettingDefaultType and rangeFeeds
Model Parameters:
SourceclosesourceMR MR_f div Breakout Breakdown ATRBreakout ATRBreakdown endLong endShort close long close short line 283 line 286
Local Polynomial Degree2int (written input.integer) · min 0MR MR_f div
Length (must be larger than degree)80int (written input.integer) · min 2MR MR_f div
MultiplierDefines the Band Width.2.0float · min 0.0div
Allowed Entries:
Allow Long Entriestrueboolentry long line 277
Allow Short Entriesfalseboolentry short line 280
Exit Conditions:
Exit Long AtLower Band - ATRstring · options ["Lower Band","Lower Band - ATR","Central Line"]trailinglong
Exit Short AtCentral Linestring · options ["Upper Band","Upper Band + ATR","Central Line"]trailingshort
Fixed Backtest Period Start/End Dates:
Fixedstart (no label in the script)trueboolisinrange
Backtest start (no label in the script)If deactivated, backtest staring from the first available price bar.timestamp("01 Jan 2017 13:30 +0000")timeisinrange
Fixedend (no label in the script)falseboolisinrange
Backtest end (no label in the script)If deactivated, backtesting ends at the last available price bar.timestamp("30 Dec 2080 23:30 +0000")timeisinrange
Additional Options
Show Stop-Loss Linetrueboolsl
Enter Only When MR Slope is Positive/NegativefalseboolgoLong goShort
Show Breakout Signals LabelsfalseboolBreakout Breakdown
Show Central Line AsPrevious-Period MR Predictionstring · options ["Ribbon","MR","Previous-Period MR Prediction"]MR MR Prediction line 233 line 235 fill

What it calculates

  • ATR (atr, ta.atr in v5)14ATR · line 243
  • Crossover (crossover, ta.crossover in v5)Source (close), highbandBreakout · line 244
  • Crossunder (crossunder, ta.crossunder in v5)Source (close), lowbandBreakdown · line 245
  • Crossover (crossover, ta.crossover in v5)Source (close), highband + ATRATRBreakout · line 246
  • Crossunder (crossunder, ta.crossunder in v5)Source (close), lowband - ATRATRBreakdown · line 247
  • Crossunder (crossunder, ta.crossunder in v5)Source (close), trailinglongendLong · line 273
  • Crossover (crossover, ta.crossover in v5)Source (close), trailingshortendShort · line 274

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

Order rules

OrderFires whenBy defaultLine
Open long longgoLong and isinrange and doLongOn278
Open short shortgoShort and isinrange and doShortOn281
Close longendLong or crossunder(src,stoploss)On284
Close shortendShort or crossover(src,stoploss)On287
Close (not isinrange)On290

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Alerts

AlertCallMessageLine
(no title)alertsyminfo.tickerid+" Long Signal Triggered"279
(no title)alertsyminfo.tickerid+" Short Signal Triggered"282
(no title)alertsyminfo.tickerid+" Exit Signal Triggered for Long Position"285
(no title)alertsyminfo.tickerid+" Exit Signal Triggered for Short Position"288

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+19.2%+102.5%1338%1.6420.2%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+15.4%+5.5%1250%2.267.3%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−1.0%+9.8%1443%0.782.1%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+0.4%+8.4%1136%1.710.3%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+0.0%+16.7%1443%1.520.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.0%+21.5%1338%1.050.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−0.2%+148.3%1638%0.680.3%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+0.1%+17.1%1457%1.610.1%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 market475%$13,277.20
Sideways market633%$14,725.70
Falling market30%−$8,828.08

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

How bad could the drawdown be?

22.0%

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

0%25%
All 13 trades
SideEntryExitBarsP&L
long4 May 2024 62,882.0013 Jun 2024 68,264.0040$5,381.97
long14 Jul 2024 59,204.006 Aug 2024 54,018.8023−$5,185.19
long14 Sep 2024 60,498.0011 Oct 2024 60,326.4027−$171.59
long11 Nov 2024 80,370.0028 Nov 2024 95,863.1017$15,493.10
long7 Jan 2025 102,236.0026 Feb 2025 88,680.4050−$13,555.20
long16 Mar 2025 84,338.4011 Apr 2025 79,607.3026−$4,731.14
long23 Apr 2025 93,443.0025 May 2025 107,762.0032$14,318.90
long26 Jun 2025 107,341.002 Aug 2025 113,298.0037$5,957.33
long8 Sep 2025 111,137.0012 Oct 2025 110,644.0034−$492.95
long28 Nov 2025 91,333.9021 Jan 2026 88,427.7054−$2,906.28
long26 Feb 2026 67,988.0031 Mar 2026 66,797.4033−$1,190.66
long14 Jun 2026 64,458.002 Aug 2026 62,823.7049−$1,634.36
long20 Aug 2026 69,334.8012 Sep 2026 77,225.7023$7,890.93

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
Moving Regression Band Breakout strategy this page—v4 strategy+19.2%1320.2%
SOJA PIVOT by ParaBellum68atrv4 strategy+3.3%918.2%
Volatility System by EduardoMattjeatrv5 strategy+150.2%221.5%
ATR Stop Buy Strategy by phobo3satrv4 strategyNo trades on this market
VBand Strategy by Saravanan_Ragavanatrv4 strategyNo trades on this market
Volatility Breakout Strategy [Angel Algo] by AngelAlgoatrv5 strategy+3.1%183.6%

Where it runs

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

Zeal Terminal's engine currently reads an order side written as true, false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 278, 281) so the engine trades the way the script says.

“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/// © tbiktag//// Moving Regression Band Breakout strategy//// The strategy based on the Moving Regression Prediction Bands indicator://// https://www.tradingview.com/script/zOaMXJ65-Moving-Regression-Prediction-Bands///// Entry condition: //    Long: the price crosses the Upper Band from below. //    Short: the price crosses the Lower Band from above. // Exit condition Long: //    the price crosses the Lower Band (the Lower Band - ATR, or Central Line)// Exit condition Short: //    the price crosses the Upper Band (the Upper Band + ATR, or Central Line)//////@version=4strategy("Moving Regression Band Breakout strategy", shorttitle = "MRBand Strat", overlay=true)matrix_get(_A,_i,_j,_nrows) =>    // Get the value of the element of an implied 2d matrix    //input:     // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]]    // _i :: integer: row number    // _j :: integer: column number    // _nrows :: integer: number of rows in the implied 2d matrix    array.get(_A,_i+_nrows*_j)matrix_set(_A,_value,_i,_j,_nrows) =>    // Set a value to the element of an implied 2d matrix    //input:     // _A :: array, changed on output: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]]    // _value :: float: the new value to be set    // _i :: integer: row number    // _j :: integer: column number    // _nrows :: integer: number of rows in the implied 2d matrix    array.set(_A,_i+_nrows*_j,_value)transpose(_A,_nrows,_ncolumns) =>    // Transpose an implied 2d matrix    // input:    // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]]    // _nrows :: integer: number of rows in _A    // _ncolumns :: integer: number of columns in _A    // output:    // _AT :: array: pseudo 2d matrix with implied dimensions: _ncolums x _nrows    var _AT = array.new_float(_nrows*_ncolumns,0)    for i = 0 to _nrows-1        for j = 0 to _ncolumns-1            matrix_set(_AT, matrix_get(_A,i,j,_nrows),j,i,_ncolumns)    _ATmultiply(_A,_B,_nrowsA,_ncolumnsA,_ncolumnsB) =>     // Calculate scalar product of two matrices    // input:     // _A :: array: pseudo 2d matrix    // _B :: array: pseudo 2d matrix    // _nrowsA :: integer: number of rows in _A    // _ncolumnsA :: integer: number of columns in _A    // _ncolumnsB :: integer: number of columns in _B    // output:    // _C:: array: pseudo 2d matrix with implied dimensions _nrowsA x _ncolumnsB    var _C = array.new_float(_nrowsA*_ncolumnsB,0)    int _nrowsB = _ncolumnsA    float elementC= 0.0    for i = 0 to _nrowsA-1        for j = 0 to _ncolumnsB-1            elementC := 0            for k = 0 to _ncolumnsA-1                elementC := elementC + matrix_get(_A,i,k,_nrowsA)*matrix_get(_B,k,j,_nrowsB)            matrix_set(_C,elementC,i,j,_nrowsA)    _Cvnorm(_X,_n) =>    //Square norm of vector _X with size _n    float _norm = 0.0    for i = 0 to _n-1        _norm := _norm + pow(array.get(_X,i),2)    sqrt(_norm)qr_diag(_A,_nrows,_ncolumns) =>     //QR Decomposition with Modified Gram-Schmidt Algorithm (Column-Oriented)    // input:    // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]]    // _nrows :: integer: number of rows in _A    // _ncolumns :: integer: number of columns in _A    // output:    // _Q: unitary matrix, implied dimenstions _nrows x _ncolumns    // _R: upper triangular matrix, implied dimansions _ncolumns x _ncolumns    var _Q = array.new_float(_nrows*_ncolumns,0)    var _R = array.new_float(_ncolumns*_ncolumns,0)    var _a = array.new_float(_nrows,0)    var _q = array.new_float(_nrows,0)    float _r = 0.0    float _aux = 0.0    //get first column of _A and its norm:    for i = 0 to _nrows-1        array.set(_a,i,matrix_get(_A,i,0,_nrows))    _r := vnorm(_a,_nrows)    //assign first diagonal element of R and first column of Q    matrix_set(_R,_r,0,0,_ncolumns)    for i = 0 to _nrows-1        matrix_set(_Q,array.get(_a,i)/_r,i,0,_nrows)    if _ncolumns != 1        //repeat for the rest of the columns        for k = 1 to _ncolumns-1            for i = 0 to _nrows-1                array.set(_a,i,matrix_get(_A,i,k,_nrows))            for j = 0 to k-1                //get R_jk as scalar product of Q_j column and A_k column:                _r := 0                for i = 0 to _nrows-1                    _r := _r + matrix_get(_Q,i,j,_nrows)*array.get(_a,i)                matrix_set(_R,_r,j,k,_ncolumns)                //update vector _a                for i = 0 to _nrows-1                    _aux := array.get(_a,i) - _r*matrix_get(_Q,i,j,_nrows)                    array.set(_a,i,_aux)            //get diagonal R_kk and Q_k column            _r := vnorm(_a,_nrows)            matrix_set(_R,_r,k,k,_ncolumns)            for i = 0 to _nrows-1                matrix_set(_Q,array.get(_a,i)/_r,i,k,_nrows)    [_Q,_R]pinv(_A,_nrows,_ncolumns) =>//Pseudoinverse of matrix _A calculated using QR decomposition// Input: // _A:: array: implied as a (_nrows x _ncolumns) matrix _A = [[column_0],[column_1],...,[column_(_ncolumns-1)]]// Output: // _Ainv:: array implied as a (_ncolumns x _nrows) matrix _A = [[row_0],[row_1],...,[row_(_nrows-1)]]// ----// First find the QR factorization of A: A = QR,// where R is upper triangular matrix.// Then _Ainv = R^-1*Q^T.// ----    [_Q,_R] = qr_diag(_A,_nrows,_ncolumns)    _QT = transpose(_Q,_nrows,_ncolumns)    // Calculate Rinv:    var _Rinv = array.new_float(_ncolumns*_ncolumns,0)    float _r = 0.0    matrix_set(_Rinv,1/matrix_get(_R,0,0,_ncolumns),0,0,_ncolumns)    if _ncolumns != 1        for j = 1 to _ncolumns-1            for i = 0 to j-1                _r := 0.0                for k = i to j-1                    _r := _r + matrix_get(_Rinv,i,k,_ncolumns)*matrix_get(_R,k,j,_ncolumns)                matrix_set(_Rinv,_r,i,j,_ncolumns)            for k = 0 to j-1                matrix_set(_Rinv,-matrix_get(_Rinv,k,j,_ncolumns)/matrix_get(_R,j,j,_ncolumns),k,j,_ncolumns)            matrix_set(_Rinv,1/matrix_get(_R,j,j,_ncolumns),j,j,_ncolumns)    //    _Ainv = multiply(_Rinv,_QT,_ncolumns,_ncolumns,_nrows)    _Ainvmae(_x, _xhat) =>    // Mean Average Error    // _x.   :: array float, original data    // _xhat :: array float, model estimate    // output    // _nrmse:: float    float _mae = 0.0    if array.size(_x) != array.size(_xhat)        _mae := na    else        _N = array.size(_x)        for i = 0 to _N-1            _mae := _mae + abs(array.get(_x,i) - array.get(_xhat,i))/_N    _maemr(_src,_window,_degree) =>    // Vandermonde matrix with implied dimensions (window x degree+1)    // Linear form: J = [ [z]^0, [z]^1, ... [z]^degree], with z = [ (1-window)/2 to (window-1)/2 ]     var _J = array.new_float(_window*(_degree+1),0)    for i = 0 to _window-1         for j = 0 to _degree            matrix_set(_J,pow(i,j),i,j,_window)    // Vector of raw datapoints:    var _Y_raw = array.new_float(_window,na)    for j = 0 to _window-1        array.set(_Y_raw,j,_src[_window-1-j])     // Calculate polynomial coefficients which minimize the loss function    _C = pinv(_J,_window,_degree+1)    _a_coef = multiply(_C,_Y_raw,_degree+1,_window,1)    // For smoothing, approximate the last point (i.e. z=window-1) by a0    float _Y = 0.0    for i = 0 to _degree        _Y := _Y + array.get(_a_coef,i)*pow(_window-1,i)    // Trend Direction Forecast    float _Y_f = 0.0    for i = 0 to _degree        _Y_f := _Y_f + array.get(_a_coef,i)*pow(_window,i)    // Calculates data estimate (needed for rmse)    _Y_hat = multiply(_J,_a_coef,_window,_degree+1,1)    float _err = mae(_Y_raw,_Y_hat)    [_Y,_Y_f,_err]/// --- main ---src = input(title="Source", defval=close, group = "Model Parameters:")degree = input(title="Local Polynomial Degree", type = input.integer, defval=2, minval = 0,  group = "Model Parameters:")window = input(title="Length (must be larger than degree)", type = input.integer, defval=80, minval = 2,  group = "Model Parameters:")mult = input(title="Multiplier", type=input.float,defval=2.0,minval=0.0,             group = "Model Parameters:", tooltip = "Defines the Band Width.")doLong = input(title="Allow Long Entries", type=input.bool,defval=true, inline = "linealwd", group = "Allowed Entries:")doShort = input(title="Allow Short Entries", type=input.bool,defval=false, inline = "linealwd", group = "Allowed Entries:")stoplong = input(title="Exit Long At", defval="Lower Band - ATR",                    options = ["Lower Band","Lower Band - ATR","Central Line"],                   inline = "lineexit", group = "Exit Conditions:")stopshort = input(title="Exit Short At", defval="Central Line",                    options = ["Upper Band","Upper Band + ATR","Central Line"],                   inline = "lineexit", group = "Exit Conditions:")fixedstart =input(title="", group = "Fixed Backtest Period Start/End Dates:",              inline = "linebac1", type = input.bool, defval = true)backtest_start=input(title = "", type = input.time, inline = "linebac1",               group = "Fixed Backtest Period Start/End Dates:",              defval = timestamp("01 Jan 2017 13:30 +0000"),              tooltip="If deactivated, backtest staring from the first available price bar.")fixedend =  input(title="", group = "Fixed Backtest Period Start/End Dates:",              inline = "linebac2", type = input.bool, defval = false)backtest_end =input(title = "", type = input.time, inline = "linebac2",               group = "Fixed Backtest Period Start/End Dates:",              defval = timestamp("30 Dec 2080 23:30 +0000"),              tooltip="If deactivated, backtesting ends at the last available price bar.")istoploss = input(title="Show Stop-Loss Line", type=input.bool,defval=true, group="Additional Options")slopefilter = input(title="Enter Only When MR Slope is Positive/Negative", type=input.bool,defval=false, group="Additional Options")issignal = input(title="Show Breakout Signals Labels", type=input.bool,defval=false, group="Additional Options")clinetype = input(title="Show Central Line As", defval="Previous-Period MR Prediction",                   options = ["Ribbon","MR","Previous-Period MR Prediction"], group="Additional Options")[MR,MR_f,div] = mr(src,window,degree)div := div*mult// plot bandshighband = MR_f[1]+div[1]lowband = MR_f[1]-div[1]centralline = MR_f[1]hbplt = plot(highband,title='Upper Band',color=#3C94B8,linewidth=2, transp = 40)lbplt = plot(lowband,title='Lower Band',color=#B83C94,linewidth=2, transp = 40)fill(hbplt,lbplt,color=#3C94B8)// plot central linevar plt_color = #3C94B8if MR_f[1] < MR and clinetype=="Ribbon"    plt_color := #94B83Celse if MR_f[1] > MR and clinetype=="Ribbon"    plt_color := #B83C71mrplt = plot(MR,title='MR',color=plt_color,linewidth=1,             transp = clinetype=="Previous-Period MR Prediction"?100:20)mrfplt = plot(centralline,title='MR Prediction',color=plt_color,linewidth=1,              transp = clinetype=="MR"?100:20)fill(mrplt,mrfplt,color=plt_color,transp = clinetype!="Ribbon"?100:20)//  breakout signalsATR = atr(14)Breakout = crossover(src,highband)Breakdown = crossunder(src,lowband)ATRBreakout = crossover(src,highband + ATR)ATRBreakdown = crossunder(src,lowband - ATR)MRSlopesUp = MR>MR[1]MRSlopesDw = MR<MR[1]plotshape(Breakout and issignal ? high : na, location=location.abovebar,           style=shape.triangleup, color=#88d4ca, size=size.tiny, title='Breakout')plotshape(Breakdown and issignal? low : na, location=location.belowbar,           style=shape.triangledown, color=#f67e7d, size=size.tiny,title='Breakdown')goLong = Breakout and (slopefilter?MRSlopesUp:true)goShort = Breakdown and (slopefilter?MRSlopesDw:true)// trailing stop / stop losstrailinglong = stoplong=="Central Line"?centralline:(stoplong=="Lower Band"?lowband:lowband-ATR)trailingshort= stopshort=="Central Line"?centralline:(stopshort=="Upper Band"?highband:highband+ATR)// if signal has been triggered at previous bar, set position open price and initial SLvar float opprice = 0.0var float stoploss = 0.0if (strategy.position_entry_name[1]=="short" or strategy.position_size[1]==0) and goLong[1]     opprice := open    stoploss := trailinglongelse if (strategy.position_entry_name[1]=="long" or strategy.position_size[1]==0) and goShort[1]     opprice := open    stoploss := trailingshort// move SL to position opening price if lowband crosses the initial SLif (strategy.position_entry_name=="long" and crossover(trailinglong, opprice)) or (strategy.position_entry_name=="short" and crossunder(trailingshort, opprice))    stoploss := oppricestoplosscolor = strategy.position_entry_name=="long"?#B83C94:(strategy.position_entry_name=="short"?#3C94B8:color.silver)plot(istoploss?stoploss:na,title='sl',color=stoplosscolor,linewidth=1,transp=50)endLong = crossunder(src,trailinglong)endShort = crossover(src,trailingshort)// backtestisinrange = (fixedstart?time>=backtest_start:true) and (fixedend?time<=backtest_end:true)if goLong and isinrange and doLong    strategy.entry("long",   true)    alert(syminfo.tickerid+" Long Signal Triggered",alert.freq_once_per_bar_close)if goShort and isinrange and doShort    strategy.entry("short",  false)    alert(syminfo.tickerid+" Short Signal Triggered",alert.freq_once_per_bar_close)if endLong or crossunder(src,stoploss)    strategy.close("long")    alert(syminfo.tickerid+" Exit Signal Triggered for Long Position",alert.freq_once_per_bar_close)if endShort or crossover(src,stoploss)    strategy.close("short")    alert(syminfo.tickerid+" Exit Signal Triggered for Short Position",alert.freq_once_per_bar_close)if (not isinrange)    strategy.close_all()