Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

MACandles-LinearRegression-Strategy

A Pine Script v5 strategy built on Stdev (maDiff, 20), SMA (maDiff, 20) and Highest (maDiff, 40). 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. 13 settings; defaults include Moving Average Type (MA Candles) hma, Length (MA Candles) 60 and Moving Average Type (Momentum) ema.

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 MACandles-LinearRegression-Strategy repaint?
No
No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
How did MACandles-LinearRegression-Strategy do on BTCUSDT 1D with default settings?
+26.74%
From 26 Jan 2024 to 21 Oct 2026, over 3 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does MACandles-LinearRegression-Strategy run in Pine Script v6?
Yes
Same 3 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. The v6 script can be downloaded below.
Does MACandles-LinearRegression-Strategy use a stop loss?
No
Every exit waits for a signal; nothing limits a losing trade before it fires.
Does MACandles-LinearRegression-Strategy run in Zeal Terminal?
Yes
It compiles in 39 ms and runs 1,000 bars in 158 ms, in the browser.

BTCUSDT · 1D · default settings

  • Momentum
  • Linear Regression (Momentum)
  • 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 (13)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOctMomentum$126,733$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.
Net profit
+26.74%
$26,740.40
Buy and hold
+102.5%
same period
Closed trades
3
2 won · 1 lost
Profitable
66.7%
of closed trades
Profit factor
1.69
gross profit ÷ gross loss
Max drawdown
46.66%
−$77,234.90

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

    3 settings have no label

    In the settings dialog aggressiveLong (line 14), longTrades (line 15), useVixFix (line 16) 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 113, 114. The upgraded version below moves each call inside an if block.

Settings

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

SettingDefaultType and rangeFeeds
Moving Average Type (MA Candles)hmastring · options ['ema', 'sma', 'hma', 'rma', 'vwma', 'wma']oOpen oClose oHigh oLow longStop shortStop line 22 line 25 line 28 line 31 line 34 dir
Length (MA Candles)60int · step 10oOpen oClose oHigh oLow longStop shortStop dir
Moving Average Type (Momentum)emastring · options ['ema', 'sma', 'hma', 'rma', 'vwma', 'wma']ma col val absVal linRegColor maDiff absMaDiff
MA Length (Momentum)20int · step 10ma wvf sDev midLine col val absVal linRegColor vixFixState maDiff absMaDiff vval vabsVal vcol vlinRegColor
Look Back Period Percentile High/Low40int · min 10 · max 100 · step 10rangeHigh rangeLow col val absVal linRegColor maDiff absMaDiff
Highest Percentile - 0.90=90%, 0.95=95%, 0.99=99%.85floatrangeHigh col val absVal linRegColor maDiff absMaDiff
Lowest Percentile - 1.10=90%, 1.05=95%, 1.01=99%1.01floatrangeLow col val absVal linRegColor maDiff absMaDiff
Bollinger Band Standard Devaition Up3.0float · min 1 · max 5sDev col val absVal linRegColor maDiff absMaDiff
Aggressive Long (no label in the script)trueboollongCondition exitLongCondition
Long Trades (no label in the script)trueboolexitColor exitPreviousColor
Use Vix Fix (no label in the script)falseboollongCondition Momentum VIX Fix Linear Regression (Momentum) Linear Regression (VIX Fix)
Start Timetimestamp('01 Jan 2010 00:00 +0000')timeinDateRange
End Timetimestamp('01 Jan 2099 00:00 +0000')timeinDateRange

What it calculates

  • StdevmaDiff, MA Length (Momentum) (20)sDev · line 67
  • SMAmaDiff, MA Length (Momentum) (20)midLine · line 68
  • HighestmaDiff, Look Back Period Percentile High/Low (40)rangeHigh · line 71
  • LowestmaDiff, Look Back Period Percentile High/Low (40)rangeLow · line 72

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.

MLengthMA Length (Momentum)setting · 20multBollinger Band Standard…setting · 3.0lbLook Back Period Percen…setting · 40phHighest Percentile - 0.…setting · .85plLowest Percentile - 1.1…setting · 1.01MMATypeMoving Average Type (Mo…setting · emaMATypeMoving Average Type (MA…setting · hmaLoopbackBarsLength (MA Candles)setting · 60timetimeprice datai_startTimeStart Timesetting · timestamp('01 Jan 2…i_endTimeEnd Timesetting · timestamp('01 Jan 2…sDevStdev→ sDevmidLineSMA→ midLinerangeHighHighest→ rangeHighrangeLowLowest→ rangeLowmamavalueoOpen, oClose, oHigh, oLowoOpen · oClose +24 valueswvf, vixFixState, vval, vabsVal, vcol, vlinRegColorwvf · vixFixState +46 valueslowerBand, upperBandlowerBand · upperBand2 valuescol, val, absVal, linRegColor, maDiff, absMaDiffcol · val +46 valuestruerangetruerangevalueaveragetruerangeaveragetruerangevalueatratrvaluelongWicks, shortWickslongWicks · shortWicks2 valueslongStop, shortStoplongStop · shortStop2 valueslongStopPrevlongStopPrevvalueshortStopPrevshortStopPrevvalueinDateRangeinDateRangeconditioniff_1, iff_2, candleColor, exitColor, exitPreviousColor, longCondition, exitLongConditionColouriff_1 · iff_2 +5entry:LongOpen Longstrategy.entryclose:LongClose Longstrategy.closeplot:105Momentumplotplot:106VIX Fixplotplot:107Linear Regression (Mome…plotplot:108Linear Regression (VIX …plot

Order rules

OrderFires whenBy defaultLine
Open Long longlongConditionOn113
Close LongexitLongConditionOn114

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

Does it repaint?

No

No repainting patterns in the source.

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.
  • 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+26.7%+102.5%367%1.6946.7%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+8.8%+5.5%367%1.5325.3%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−63.6%+9.8%425%0.1272.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+8.9%+8.4%850%1.2830.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−37.9%+16.7%333%0.5677.5%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−7.7%+21.5%633%0.7330.3%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−4.2%+148.3%650%0.9438.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+20.0%+17.1%667%2.7519.0%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 market367%$26,740.40
Sideways market0—$0.00
Falling market0—$0.00

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

How bad could the drawdown be?

23.4%

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

0%27%
All 3 trades
SideEntryExitBarsP&L
long10 May 2024 63,074.0021 Dec 2024 97,805.40225$55,033.60
long9 Jan 2025 95,060.606 Jun 2025 101,509.00148$10,483.00
long30 Jun 2025 108,357.0011 Oct 2026 82,988.40468−$38,776.20

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
MACandles-LinearRegression-Strategy this page—v5 strategy+26.7%346.7%
Lawyers Trend Pro Strategy by ErdemDemirsma stdev lowest highestv4 strategy+12.1%10241.7%
BTC Volatility Band Strategy by gary_tradessma stdev lowest highestv4 strategy−33.5%8045.0%
VixFixLinReg-Strategy by Trendoscopehighest stdev sma lowestv4 strategy−49.3%1251.1%
Chandelier + BB + EMAS by juanchezhighest lowest sma stdevv4 strategy−20.6%1038.6%
Crunchster's Turtle and Trend System by Crunchster1lowest highest stdev smav5 strategy+18.0%3116.7%

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • 2 strategy calls use the when = argument (line 113, 114). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • 5 settings use the untyped input() (line 11, 12, 14, 15, 16). It still compiles in v6; input.int, input.float or input.source state the type.
  • No v6-only features. v6 is not needed to run this script.

Clean v5

VerifiedDownload the v5 script

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

  • Line 11: input() → input.float()
  • Line 12: input() → input.float()
  • Line 14: input() → input.bool()
  • Line 15: input() → input.bool()
  • Line 16: input() → input.bool()
  • Line 113: when = longCondition → if block
  • Line 114: when = exitLongCondition → if block
⋯lb = input.int(40, title='Look Back Period Percentile High/Low', step=10, minval=10, maxval=100)-ph = input(.85, title='Highest Percentile - 0.90=90%, 0.95=95%, 0.99=99%')+ph = input.float(.85, title='Highest Percentile - 0.90=90%, 0.95=95%, 0.99=99%')-pl = input(1.01, title='Lowest Percentile - 1.10=90%, 1.05=95%, 1.01=99%')+pl = input.float(1.01, title='Lowest Percentile - 1.10=90%, 1.05=95%, 1.01=99%')mult = input.float(3.0, minval=1, maxval=5, title='Bollinger Band Standard Devaition Up')-aggressiveLong = input(true)+aggressiveLong = input.bool(true)-longTrades = input(true)+longTrades = input.bool(true)-useVixFix = input(false)+useVixFix = input.bool(false)i_startTime = input.time(defval=timestamp('01 Jan 2010 00:00 +0000'), title='Start Time')⋯exitLongCondition = col == exitColor and col[1] == exitColor and col[2] == exitPreviousColor and (linRegColor != color.green or not aggressiveLong)-strategy.entry('Long', strategy.long, when=longCondition, oca_name='oca_buy', oca_type=strategy.oca.cancel)+if longCondition+    strategy.entry('Long', strategy.long, oca_name='oca_buy', oca_type=strategy.oca.cancel)-strategy.close('Long', when=exitLongCondition)+if exitLongCondition+    strategy.close('Long')

Does it run in Pine Script v6?

Yes

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

Download the v6 script

⋯// © HeWhoMustNotBeNamed-//@version=5+//@version=6strategy('MACandles-LinearRegression-Strategy', shorttitle='MALinReg - 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)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 39 msYes 1,000 bars in 158 msNot measured
PineTSNot testedNot testedNot 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.

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=5strategy('MACandles-LinearRegression-Strategy', shorttitle='MALinReg - 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)resolution = ''MAType = input.string(title='Moving Average Type (MA Candles)', defval='hma', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma'])LoopbackBars = input.int(60, title='Length (MA Candles)', step=10)MMAType = input.string(title='Moving Average Type (Momentum)', defval='ema', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma'])MLength = input.int(20, title='MA Length (Momentum)', step=10)lb = input.int(40, title='Look Back Period Percentile High/Low', step=10, minval=10, maxval=100)ph = input(.85, title='Highest Percentile - 0.90=90%, 0.95=95%, 0.99=99%')pl = input(1.01, title='Lowest Percentile - 1.10=90%, 1.05=95%, 1.01=99%')mult = input.float(3.0, minval=1, maxval=5, title='Bollinger Band Standard Devaition Up')aggressiveLong = input(true)longTrades = input(true)useVixFix = input(false)i_startTime = input.time(defval=timestamp('01 Jan 2010 00:00 +0000'), title='Start Time')i_endTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End Time')inDateRange = time >= i_startTime and time <= i_endTimef_getMovingAverage(source, MAType, length) =>    ma = ta.sma(source, length)    if MAType == 'ema'        ma := ta.ema(source, length)        ma    if MAType == 'hma'        ma := ta.hma(source, length)        ma    if MAType == 'rma'        ma := ta.rma(source, length)        ma    if MAType == 'vwma'        ma := ta.vwma(source, length)        ma    if MAType == 'wma'        ma := ta.wma(source, length)        ma    maf_getMACandles(resolution, MAType, LoopbackBars) =>    oOpen = f_getMovingAverage(open, MAType, LoopbackBars)    oClose = f_getMovingAverage(close, MAType, LoopbackBars)    oHigh = f_getMovingAverage(high, MAType, LoopbackBars)    oLow = f_getMovingAverage(low, MAType, LoopbackBars)    [oOpen, oClose, oHigh, oLow]f_getVixFixLinReg(oClose, oLow, MLength) =>    wvf = (ta.highest(oClose, MLength) - oLow) / ta.highest(oClose, MLength) * 100    sDev = mult * ta.stdev(wvf, MLength)    midLine = ta.sma(wvf, MLength)    lowerBand = midLine - sDev    upperBand = midLine + sDev    rangeHigh = ta.highest(wvf, lb) * ph    rangeLow = ta.lowest(wvf, lb) * pl    col = wvf >= upperBand or wvf >= rangeHigh ? color.lime : color.gray    val = ta.linreg(wvf, MLength, 0)    absVal = math.abs(val)    linRegColor = val > val[1] ? val > 0 ? color.green : color.orange : val > 0 ? color.lime : color.red    vixFixState = col == color.lime ? 1 : 0    vixFixState := strategy.position_size == 0 ? math.max(vixFixState, nz(vixFixState[1], 0)) : vixFixState    [val, absVal, wvf, col, linRegColor, vixFixState]f_getMACandlesLinReg(oClose, MMAType, MLength, mult, lb, ph, pl) =>    ma = f_getMovingAverage(oClose, MMAType, MLength)    maDiff = oClose - ma    val = ta.linreg(maDiff, MLength, 0)    absVal = math.abs(val)    iff_1 = val > nz(val[1]) ? color.green : color.lime    iff_2 = val < nz(val[1]) ? color.red : color.orange    linRegColor = val > 0 ? iff_1 : iff_2    sDev = mult * ta.stdev(maDiff, MLength)    midLine = ta.sma(maDiff, MLength)    lowerBand = midLine - sDev    upperBand = midLine + sDev    rangeHigh = ta.highest(maDiff, lb) * ph    rangeLow = ta.lowest(maDiff, lb) * pl    col = maDiff >= upperBand or maDiff >= rangeHigh ? color.lime : maDiff <= lowerBand or maDiff <= rangeLow ? color.orange : color.silver    absMaDiff = math.abs(maDiff)    [val, absVal, maDiff, absMaDiff, col, linRegColor]f_getSupertrend(resolution, oOpen, oClose, oHigh, oLow, AtrMAType, AtrLength, AtrMult, wicks) =>    truerange = math.max(oHigh, oClose[1]) - math.min(oLow, oClose[1])    averagetruerange = f_getMovingAverage(truerange, AtrMAType, AtrLength)    atr = averagetruerange * AtrMult    longWicks = wicks    shortWicks = wicks    longStop = oClose - atr    longStopPrev = nz(longStop[1], longStop)    longStop := (longWicks ? oLow[1] : oClose[1]) > longStopPrev ? math.max(longStop, longStopPrev) : longStop    shortStop = oClose + atr    shortStopPrev = nz(shortStop[1], shortStop)    shortStop := (shortWicks ? oHigh[1] : oClose[1]) < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop    dir = 1    dir := nz(dir[1], dir)    dir := dir == -1 and (longWicks ? oHigh : oClose) > shortStopPrev ? 1 : dir == 1 and (shortWicks[1] ? oLow : oClose) < longStopPrev ? -1 : dir    [dir, longStop, shortStop]f_getMACandlesAndSupertrend(MAType, LoopbackBars, AtrMult, wicks) =>    oOpen = f_getMovingAverage(open, MAType, LoopbackBars)    oClose = f_getMovingAverage(close, MAType, LoopbackBars)    oHigh = f_getMovingAverage(high, MAType, LoopbackBars)    oLow = f_getMovingAverage(low, MAType, LoopbackBars)    [dir, longStop, shortStop] = f_getSupertrend(resolution, oOpen, oClose, oHigh, oLow, MAType, LoopbackBars, AtrMult, wicks)    dir[oOpen, oClose, oHigh, oLow] = f_getMACandles(resolution, MAType, LoopbackBars)dir = f_getMACandlesAndSupertrend('sma', 200, 1, false)colorByPreviousClose = falsecandleColor = colorByPreviousClose ? oClose[1] < oClose ? color.green : oClose[1] > oClose ? color.red : color.silver : oOpen < oClose ? color.green : oOpen > oClose ? color.red : color.silver[vval, vabsVal, wvf, vcol, vlinRegColor, vixFixState] = f_getVixFixLinReg(oClose, oLow, MLength)[val, absVal, maDiff, absMaDiff, col, linRegColor] = f_getMACandlesLinReg(oClose, MMAType, MLength, mult, lb, ph, pl)plot(useVixFix ? na : absMaDiff, title='Momentum', style=plot.style_histogram, linewidth=4, color=col)plot(useVixFix ? wvf : na, title='VIX Fix', style=plot.style_histogram, linewidth=4, color=vcol)plot(useVixFix ? na : -absVal, title='Linear Regression (Momentum)', style=plot.style_histogram, linewidth=4, color=linRegColor)plot(useVixFix ? -vabsVal : na, title='Linear Regression (VIX Fix)', style=plot.style_histogram, linewidth=4, color=vlinRegColor)exitColor = longTrades ? color.orange : color.silverexitPreviousColor = longTrades ? color.silver : color.limelongCondition = (useVixFix ? vixFixState == 1 and vlinRegColor == color.lime : linRegColor == color.orange and linRegColor[1] == color.red or linRegColor == color.green and linRegColor[1] != color.green and aggressiveLong) and inDateRange and dir > 0exitLongCondition = col == exitColor and col[1] == exitColor and col[2] == exitPreviousColor and (linRegColor != color.green or not aggressiveLong)strategy.entry('Long', strategy.long, when=longCondition, oca_name='oca_buy', oca_type=strategy.oca.cancel)strategy.close('Long', when=exitLongCondition)