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
- 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Moving Average Type (MA Candles) | hma | string · 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) | 60 | int · step 10 | oOpen oClose oHigh oLow longStop shortStop dir |
| Moving Average Type (Momentum) | ema | string · options ['ema', 'sma', 'hma', 'rma', 'vwma', 'wma'] | ma col val absVal linRegColor maDiff absMaDiff |
| MA Length (Momentum) | 20 | int · step 10 | ma wvf sDev midLine col val absVal linRegColor vixFixState maDiff absMaDiff vval vabsVal vcol vlinRegColor |
| Look Back Period Percentile High/Low | 40 | int · min 10 · max 100 · step 10 | rangeHigh rangeLow col val absVal linRegColor maDiff absMaDiff |
| Highest Percentile - 0.90=90%, 0.95=95%, 0.99=99% | .85 | float | rangeHigh col val absVal linRegColor maDiff absMaDiff |
| Lowest Percentile - 1.10=90%, 1.05=95%, 1.01=99% | 1.01 | float | rangeLow col val absVal linRegColor maDiff absMaDiff |
| Bollinger Band Standard Devaition Up | 3.0 | float · min 1 · max 5 | sDev col val absVal linRegColor maDiff absMaDiff |
| Aggressive Long (no label in the script) | true | bool | longCondition exitLongCondition |
| Long Trades (no label in the script) | true | bool | exitColor exitPreviousColor |
| Use Vix Fix (no label in the script) | false | bool | longCondition Momentum VIX Fix Linear Regression (Momentum) Linear Regression (VIX Fix) |
| 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
- 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | longCondition | On | 113 |
| Close Long | exitLongCondition | On | 114 |
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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +26.7% | +102.5% | 3 | 67% | 1.69 | 46.7% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +8.8% | +5.5% | 3 | 67% | 1.53 | 25.3% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −63.6% | +9.8% | 4 | 25% | 0.12 | 72.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +8.9% | +8.4% | 8 | 50% | 1.28 | 30.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −37.9% | +16.7% | 3 | 33% | 0.56 | 77.5% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −7.7% | +21.5% | 6 | 33% | 0.73 | 30.3% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −4.2% | +148.3% | 6 | 50% | 0.94 | 38.0% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +20.0% | +17.1% | 6 | 67% | 2.75 | 19.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 3 | 67% | $26,740.40 |
| Sideways market | 0 | — | $0.00 |
| Falling market | 0 | — | $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.
All 3 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 10 May 2024 63,074.00 | 21 Dec 2024 97,805.40 | 225 | $55,033.60 |
| long | 9 Jan 2025 95,060.60 | 6 Jun 2025 101,509.00 | 148 | $10,483.00 |
| long | 30 Jun 2025 108,357.00 | 11 Oct 2026 82,988.40 | 468 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| MACandles-LinearRegression-Strategy this page | — | v5 strategy | +26.7% | 3 | 46.7% |
| Lawyers Trend Pro Strategy by ErdemDemir | sma stdev lowest highest | v4 strategy | +12.1% | 102 | 41.7% |
| BTC Volatility Band Strategy by gary_trades | sma stdev lowest highest | v4 strategy | −33.5% | 80 | 45.0% |
| VixFixLinReg-Strategy by Trendoscope | highest stdev sma lowest | v4 strategy | −49.3% | 12 | 51.1% |
| Chandelier + BB + EMAS by juanchez | highest lowest sma stdev | v4 strategy | −20.6% | 10 | 38.6% |
| Crunchster's Turtle and Trend System by Crunchster1 | lowest highest stdev sma | v5 strategy | +18.0% | 31 | 16.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.
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.
⋯// © 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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 39 ms | Yes 1,000 bars in 158 ms | Not measured |
| PineTS | Not tested | Not tested | 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.
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)