Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Linear Regression MA - Strategy

A Pine Script v5 strategy built on SMA (close, 200), Linreg (close, 55) and EMA (close, 55). It has 6 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade is one contract and pays no commission. 12 settings; defaults include Start Month 1, Start Day 1 and Start Year 2022.

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 Linear Regression MA - Strategy repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 2 of 2 trades.
How did Linear Regression MA - Strategy do on BTCUSDT 1D with default settings?
−1,240.39%
From 26 Jan 2024 to 21 Oct 2026, over 10 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Linear Regression MA - Strategy 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: 10 before, 0 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download.
Does Linear Regression MA - Strategy use a stop loss?
Yes
strategy.exit sets a stop on line 46, 47.
Does Linear Regression MA - Strategy run in Zeal Terminal?
Yes
It compiles in 18 ms and runs 1,000 bars in 50 ms, in the browser.

BTCUSDT · 1D · default settings

  • Plot
  • Plot
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$-113,974$20,253Equity from $10,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 direction = strategy.long, direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 37, 42) so the engine trades the way the script says. The live re-run is not offered here: the script requests BINANCE:BTCUSDT 240, which this page cannot load in your browser.

Needs BINANCE:BTCUSDT 240 data, not available: a lower timeframe than the chart; the engine does not evaluate intrabar data Values that depend on it are empty on this chart.

Net profit
−1,240.39%
−$124,039.00
Buy and hold
+102.5%
same period
Closed trades
10
7 won · 3 lost
Profitable
70.0%
of closed trades
Profit factor
0.84
gross profit ÷ gross loss
Max drawdown
318.71%
−$634,691.00

One run with the author's default settings, $10,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.

  • Likely bug

    ta.sma(close, 200) ignores the settings line 17

    Line 17 hard-codes 200 where line 26 uses “Linear Regression MA”. Changing those settings moves one band but not this one.

    ta.sma(close, 200)ta.sma(close, lrMAInput)
  • Check

    1 setting does nothing

    “Show Date Range” is declared but never read.

  • Check

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • 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 37, 38, 42, 43. 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
Date Info
Start Month1int · min 1 · max 12start
Start Day1int · min 1 · max 31start
Start Year2022int · min 1970start
Averages
Linear Regression Line55int · min 1lrLine
Linear Regression MA55int · min 1lrMA
EMA Length55int · min 1ema
Execute Long Tradestrueboolentry long_entry close long_entry line 36
Execute Short Tradestrueboolentry short_entry close short_entry line 41
Execute Stop Losstrueboolexit long_entry exit short_entry line 45
Max Profit (%)10.0float · min 0.0maxProfitLong maxProfitShort
Stop Loss (%)1.75float · min 0.0stopLossPriceShort stopLossPriceLong
Show Date Rangetrueboolunused

What it calculates

  • SMAclose, 200fourHrSMAExpr · line 17
  • Linregclose, Linear Regression Line (55), 0lrLine · line 25
  • SMAlrLine, Linear Regression MA (55)lrMA · line 26
  • EMAclose, EMA Length (55)ema · line 27

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 datalrLineInputLinear Regression Linesetting · 55lrMAInputLinear Regression MAsetting · 55emaInputEMA Lengthsetting · 55startYearStart Yearsetting · 2022startMonthStart Monthsetting · 1startDayStart Daysetting · 1maxProfitInputMax Profit (%)setting · 10.0stopLossPercentageInputStop Loss (%)setting · 1.75fourHrSMAExprSMA→ fourHrSMAExprlrLineLinreg→ lrLinelrMASMA→ lrMAemaEMA→ emafourHrMAfourHrMAvaluebullishbullishvaluestartstartvaluemaxProfitLong, maxProfitShortmaxProfitLong · maxProf…2 valuesstopLossPriceShort, stopLossPriceLongstopLossPriceShort · st…2 valueslongExitlongExitconditionshortExitshortExitconditionlongEntry, shortEntrylongEntry · shortEntry2 conditionsentry:long_entryOpen long_entrystrategy.entryclose:long_entryClose long_entrystrategy.closeentry:short_entryOpen short_entrystrategy.entryclose:short_entryClose short_entrystrategy.closeexit:long_entryexit long_entrystrategy.exitexit:short_entryexit short_entrystrategy.exitplot:50plotplotplot:51plotplot

Order rules

OrderFires whenBy defaultLine
Open long_entry longlongEntry and window()On37
Close long_entrylongExitlrMA < emaOn38
Open short_entry shortshortEntry and window()On42
Close short_entryshortExitema < lrMAOn43
Exit long_entry stop(strategy.position_size > 0 and executeStopLoss)On46
Exit short_entry stop(strategy.position_size > 0 and executeStopLoss)On47

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, and the live replay matched history.

2/2trades 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 data1 request.security call(s), none with lookahead on.
  • 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 BINANCE:BTCUSDT 240, and that data is not available here (a lower timeframe than the chart; the engine does not evaluate intrabar data). Its results would rest on empty values.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market1100%$70,814.80
Sideways market667%−$146,635.00
Falling market367%−$48,219.20

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

How bad could the drawdown be?

2,571.2%

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

0%2,957%
All 10 trades
SideEntryExitBarsP&L
short4 Jun 2024 68,809.9027 Jun 2024 60,865.0023$79,449.10
short31 Jul 2024 66,188.007 Aug 2024 56,022.007$101,660.00
short14 Aug 2024 60,587.206 Sep 2024 56,180.0023$44,071.60
short22 Sep 2024 63,349.0026 Dec 2024 99,429.6095−$360,806.00
short15 Apr 2025 84,591.6017 Jun 2025 106,795.0063−$222,029.00
short23 Jul 2025 119,954.0020 Aug 2025 112,873.0028$70,814.80
short6 Oct 2025 123,482.0023 Oct 2025 107,567.0017$159,149.00
short25 Dec 2025 87,669.407 Feb 2026 70,580.3044$170,892.00
short18 Mar 2026 73,909.4029 May 2026 73,617.5072$2,918.50
short19 Jul 2026 64,834.2013 Oct 2026 81,850.0086−$170,158.00

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
Linear Regression MA - Strategy this page—v5 strategy−1,240.4%10318.7%
Profit Maximizer PMax Strategy - Long-Short by melihtunasma ema linregv4 strategy+16.2%427.8%
Strategy - Profit Maximizer by PMax by MartinCresposma ema linregv4 strategyNo trades on this market
OTT-Stoch-TP-SL by BigCoinHunterema linreg smav5 strategyNo trades on this market
MACD Long Strat by TheGrindTodayema smav4 strategy+24.0%7920.1%
Stock trending strategy by exlux99ema smav4 strategy+35.3%2114.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.

  • 4 strategy calls use the when = argument (line 37, 38, 42, 43). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • 1 setting uses the untyped input() (line 24). 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 10 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 24: input() → input.bool()
  • Line 37: when = longEntry and window() → if block
  • Line 38: when = longExit → if block
  • Line 42: when = shortEntry and window() → if block
  • Line 43: when = shortExit → if block
⋯window()    => time >= start ? true : false                              // create function "within window of time"-showDate    = input(defval = true, title = "Show Date Range")+showDate    = input.bool(defval = true, title = "Show Date Range")lrLine = ta.linreg(close, lrLineInput, 0)⋯if(executeLongInput and bullish)-    strategy.entry( id="long_entry", direction=strategy.long,   when=longEntry and window(),    qty=10,  comment="long_entry")+    if longEntry and window()+        strategy.entry( id="long_entry", direction=strategy.long,    qty=10,  comment="long_entry")-    strategy.close( id="long_entry", when=longExit,     comment="long_exit")+    if longExit+        strategy.close( id="long_entry",     comment="long_exit")    // strategy.close( id="long_entry", when=maxProfitLong <= close, comment="long_exit_mp")⋯if(executeShortInput and not bullish)-    strategy.entry( id="short_entry", direction=strategy.short,   when=shortEntry and window(),    qty=10,  comment="short_entry")+    if shortEntry and window()+        strategy.entry( id="short_entry", direction=strategy.short,    qty=10,  comment="short_entry")-    strategy.close( id="short_entry", when=shortExit,     comment="short_exit")+    if shortExit+        strategy.close( id="short_entry",     comment="short_exit")    // strategy.close( id="short_entry", when=maxProfitShort <= close, comment="short_exit_mp")⋯

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: 10 before, 0 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.

⋯// © lazy_capitalist-//@version=5+//@version=6strategy('Linear Regression MA', overlay=true, initial_capital=10000)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 18 msWith a workaround 1,000 bars in 50 msNot measured
PineTSNot testedNot testedNot measured

Zeal Terminal's engine currently reads an order side written as direction = strategy.long, direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 37, 42) 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.

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/// © lazy_capitalist//@version=5strategy('Linear Regression MA', overlay=true, initial_capital=10000)datesGroup = "Date Info"startMonth = input.int(defval = 1,    title = "Start Month",  minval = 1, maxval = 12,  group=datesGroup)startDay   = input.int(defval = 1,    title = "Start Day",    minval = 1, maxval = 31,  group=datesGroup)startYear  = input.int(defval = 2022, title = "Start Year",   minval = 1970,            group=datesGroup)averagesGroup = "Averages"lrLineInput     = input.int(title="Linear Regression Line",   defval=55, minval = 1, group=averagesGroup)lrMAInput       = input.int(title="Linear Regression MA",     defval=55, minval = 1, group=averagesGroup)emaInput        = input.int(title="EMA Length",               defval=55, minval = 1, group=averagesGroup)tradesGroup = "Execute Trades"executeLongInput    = input.bool(title="Execute Long Trades",       defval=true)executeShortInput   = input.bool(title="Execute Short Trades",      defval=true)executeStopLoss     = input.bool(title="Execute Stop Loss",         defval=true)fourHrSMAExpr       = ta.sma(close, 200)fourHrMA            = request.security(symbol=syminfo.tickerid, timeframe="240", expression=fourHrSMAExpr)bullish             = close > fourHrMA ? true : falsemaxProfitInput              = input.float(  title="Max Profit (%)",         defval=10.0,    minval=0.0)   * 0.01stopLossPercentageInput     = input.float(  title="Stop Loss (%)",          defval=1.75,    minval=0.0)   * 0.01start       = timestamp(startYear, startMonth, startDay, 00, 00)            // backtest start  windowwindow()    => time >= start ? true : false                              // create function "within window of time"showDate    = input(defval = true, title = "Show Date Range")lrLine = ta.linreg(close, lrLineInput, 0)lrMA   = ta.sma(lrLine, lrMAInput)ema     = ta.ema(close, emaInput)longEntry   = ema   < lrMAlongExit    = lrMA  < emashortEntry  = lrMA  < emashortExit   = ema   < lrMAmaxProfitLong   = strategy.opentrades.entry_price(0) * (1 + maxProfitInput)maxProfitShort  = strategy.opentrades.entry_price(0) * (1 - maxProfitInput)stopLossPriceShort  = strategy.position_avg_price * (1 + stopLossPercentageInput)stopLossPriceLong   = strategy.position_avg_price * (1 - stopLossPercentageInput)if(executeLongInput and bullish)    strategy.entry( id="long_entry", direction=strategy.long,   when=longEntry and window(),    qty=10,  comment="long_entry")    strategy.close( id="long_entry", when=longExit,     comment="long_exit")    // strategy.close( id="long_entry", when=maxProfitLong <= close, comment="long_exit_mp")    if(executeShortInput and not bullish)    strategy.entry( id="short_entry", direction=strategy.short,   when=shortEntry and window(),    qty=10,  comment="short_entry")    strategy.close( id="short_entry", when=shortExit,     comment="short_exit")    // strategy.close( id="short_entry", when=maxProfitShort <= close, comment="short_exit_mp")if(strategy.position_size > 0 and executeStopLoss)    strategy.exit(  id="long_entry",        stop=stopLossPriceLong,             comment="exit_long_SL")    strategy.exit(  id="short_entry",       stop=stopLossPriceShort,            comment="exit_short_SL")    // plot(series=lrLine,     color=color.green)plot(series=lrMA,       color=color.red)plot(series=ema,        color=color.blue)