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
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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Date Info | |||
| Start Month | 1 | int · min 1 · max 12 | start |
| Start Day | 1 | int · min 1 · max 31 | start |
| Start Year | 2022 | int · min 1970 | start |
| Averages | |||
| Linear Regression Line | 55 | int · min 1 | lrLine |
| Linear Regression MA | 55 | int · min 1 | lrMA |
| EMA Length | 55 | int · min 1 | ema |
| Execute Long Trades | true | bool | entry long_entry close long_entry line 36 |
| Execute Short Trades | true | bool | entry short_entry close short_entry line 41 |
| Execute Stop Loss | true | bool | exit long_entry exit short_entry line 45 |
| Max Profit (%) | 10.0 | float · min 0.0 | maxProfitLong maxProfitShort |
| Stop Loss (%) | 1.75 | float · min 0.0 | stopLossPriceShort stopLossPriceLong |
| Show Date Range | true | bool | unused |
What it calculates
- SMAclose, 200
fourHrSMAExpr · line 17 - Linregclose, Linear Regression Line (55), 0
lrLine · 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long_entry long | longEntry and window() | On | 37 |
| Close long_entry | longExitlrMA < ema | On | 38 |
| Open short_entry short | shortEntry and window() | On | 42 |
| Close short_entry | shortExitema < lrMA | On | 43 |
| Exit long_entry stop | (strategy.position_size > 0 and executeStopLoss) | On | 46 |
| Exit short_entry stop | (strategy.position_size > 0 and executeStopLoss) | On | 47 |
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.
- 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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 1 | 100% | $70,814.80 |
| Sideways market | 6 | 67% | −$146,635.00 |
| Falling market | 3 | 67% | −$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.
All 10 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| short | 4 Jun 2024 68,809.90 | 27 Jun 2024 60,865.00 | 23 | $79,449.10 |
| short | 31 Jul 2024 66,188.00 | 7 Aug 2024 56,022.00 | 7 | $101,660.00 |
| short | 14 Aug 2024 60,587.20 | 6 Sep 2024 56,180.00 | 23 | $44,071.60 |
| short | 22 Sep 2024 63,349.00 | 26 Dec 2024 99,429.60 | 95 | −$360,806.00 |
| short | 15 Apr 2025 84,591.60 | 17 Jun 2025 106,795.00 | 63 | −$222,029.00 |
| short | 23 Jul 2025 119,954.00 | 20 Aug 2025 112,873.00 | 28 | $70,814.80 |
| short | 6 Oct 2025 123,482.00 | 23 Oct 2025 107,567.00 | 17 | $159,149.00 |
| short | 25 Dec 2025 87,669.40 | 7 Feb 2026 70,580.30 | 44 | $170,892.00 |
| short | 18 Mar 2026 73,909.40 | 29 May 2026 73,617.50 | 72 | $2,918.50 |
| short | 19 Jul 2026 64,834.20 | 13 Oct 2026 81,850.00 | 86 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Linear Regression MA - Strategy this page | — | v5 strategy | −1,240.4% | 10 | 318.7% |
| Profit Maximizer PMax Strategy - Long-Short by melihtuna | sma ema linreg | v4 strategy | +16.2% | 4 | 27.8% |
| Strategy - Profit Maximizer by PMax by MartinCrespo | sma ema linreg | v4 strategy | No trades on this market | ||
| OTT-Stoch-TP-SL by BigCoinHunter | ema linreg sma | v5 strategy | No trades on this market | ||
| MACD Long Strat by TheGrindToday | ema sma | v4 strategy | +24.0% | 79 | 20.1% |
| Stock trending strategy by exlux99 | ema sma | v4 strategy | +35.3% | 21 | 14.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.
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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 18 ms | With a workaround 1,000 bars in 50 ms | Not measured |
| PineTS | Not tested | Not tested | Not 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)