Strategy · Pine Script v5 · On the chart

Linear Regression Channel - Eterna

by EternaHybridExchange

This strategy plots a linear regression of close and deviation bands on the price chart.

View on GitHub

Repaints

GitHub stars9on the repository
Pine versionv5runs as is
Lines of code89
Settings6inputs
LicenceMIT
Last update7 months ago12 Mar 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

89 lines of Pine Script v5 from strategies/trend-following/linear-regression-channel/strategy.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

strategy.pine
//@version=5
strategy("Linear Regression Channel - Eterna", 
         overlay=true, 
         initial_capital=10000,
         default_qty_type=strategy.percent_of_equity, 
         default_qty_value=10,
         commission_type=strategy.commission.percent,
         commission_value=0.075)

// ==================== Parameters ====================
lengthLR = input.int(100, "Linear Regression Length", minval=10)
deviationMultiplier = input.float(2.0, "Deviation Multiplier", minval=0.5, step=0.1)
trendEMA = input.int(50, "Trend Filter EMA", minval=1)
leverage = input.int(5, "Leverage", minval=1, maxval=100)
positionSize = input.float(0.01, "Position Size", minval=0.001, step=0.001)

webhookMessage = input.string('{"action":"{{strategy.order.action}}", "symbol":"{{ticker}}", "size":' + str.tostring(positionSize) + ', "leverage":' + str.tostring(leverage) + '}', 
                               "Webhook JSON", group="Webhook")

// ==================== Linear Regression Calculation ====================
linReg = ta.linreg(close, lengthLR, 0)

// Calculate standard deviation for bands
calcDev() =>
    sumDev = 0.0
    for i = 0 to lengthLR - 1
        sumDev := sumDev + math.pow(close[i] - ta.linreg(close, lengthLR, i), 2)
    math.sqrt(sumDev / lengthLR)

dev = calcDev()
upperBand = linReg + (dev * deviationMultiplier)
lowerBand = linReg - (dev * deviationMultiplier)
emaFilter = ta.ema(close, trendEMA)

// ==================== Entry Conditions ====================
// Trend direction based on EMA and linear regression slope
uptrend = close > emaFilter and linReg > linReg[5]
downtrend = close < emaFilter and linReg < linReg[5]

// Long: Price bounces off lower band in uptrend
longBounce = ta.crossover(close, lowerBand) and low <= lowerBand
longCondition = uptrend and longBounce

// Short: Price rejects from upper band in downtrend
shortReject = ta.crossunder(close, upperBand) and high >= upperBand
shortCondition = downtrend and shortReject

// Exit when price crosses back to linear regression line
exitLong = ta.crossunder(close, linReg)
exitShort = ta.crossover(close, linReg)

// ==================== Strategy Execution ====================
if longCondition
    strategy.entry("Long", strategy.long, alert_message=str.replace(webhookMessage, "{{strategy.order.action}}", "buy"))

if shortCondition
    strategy.entry("Short", strategy.short, alert_message=str.replace(webhookMessage, "{{strategy.order.action}}", "sell"))

if exitLong
    strategy.close("Long", alert_message='{"action":"close", "symbol":"{{ticker}}"}')

if exitShort
    strategy.close("Short", alert_message='{"action":"close", "symbol":"{{ticker}}"}')

// ==================== Plotting ====================
linRegPlot = plot(linReg, "Linear Regression", color=color.blue, linewidth=2)
upperPlot = plot(upperBand, "Upper Band", color=color.new(color.green, 0), linewidth=1)
lowerPlot = plot(lowerBand, "Lower Band", color=color.new(color.red, 0), linewidth=1)
plot(emaFilter, "Trend EMA", color=color.orange, linewidth=1)

// Fill channel
fill(upperPlot, lowerPlot, color=color.new(color.blue, 93))

// Entry signals
plotshape(longCondition, "Long", shape.triangleup, location.belowbar, color.green, size=size.normal)
plotshape(shortCondition, "Short", shape.triangledown, location.abovebar, color.red, size=size.normal)

// Show regression slope
slopeUp = linReg > linReg[5]
bgcolor(slopeUp ? color.new(color.green, 96) : color.new(color.red, 96))

// Plot channel slope angle indicator
slopeAngle = math.atan((linReg - linReg[10]) / 10) * (180 / math.pi)
var label slopeLabel = na
if bar_index % 20 == 0
    label.delete(slopeLabel)
    slopeLabel := label.new(bar_index, high, "Slope: " + str.tostring(slopeAngle, "#.#") + "°", 
                            color=slopeAngle > 0 ? color.green : color.red, 
                            textcolor=color.white, size=size.small, style=label.style_label_down)

Overview

Linear Regression Channel - Eterna enters long when price crosses up from the lower band in an uptrend defined by an EMA and a rising regression line, and enters short on a rejection from the upper band in a downtrend. It closes when price crosses the regression line. Length, deviation multiplier, EMA period, leverage, and webhook size are adjustable. There is no stop loss, and signals can change on the live bar.

Details

Published by

EternaHybridExchange on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Mean reversion, Volatility & bands

Markets

Crypto

Timeframes

H4 and above

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)
  • The strategy enters trades without a stop loss

Topics

algorithmic-tradingautomated-tradingbacktestingbybitcrypto-tradingeternamcppine-scripttrading-strategiestradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Linear Regression Lengthint100lengthLR
Deviation Multiplierfloat2.0deviationMultiplier
Trend Filter EMAint50trendEMA
Leverageint5leverage
Position Sizefloat0.01positionSize
Webhook JSONstring'{"action":"{{strategy.order.action}}", "symbol":"{{ticker}}webhookMessage
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

This strategy calculates Bollinger Bands and Aroon oscillator values to identify mean-reversion opportunities. It enters a long position using full equity when the closing price crosses below the lower Bollinger Band while Aroon Up remains above a user-specifi

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger bands + Aroon [Alorse]

[TradersPost] Sick Sigma

by TradersPost
218 stars

Sick Sigma detects extreme statistical standard deviation moves (sigma events) to execute trades directly on the main price chart. The strategy supports both momentum and mean-reversion trading styles. Traders can configure calculation lookback periods, sigma

Strategy v6 Volatility & bandsMean reversion Repaints
Updated 3 months ago · None stated GitHub repository of [TradersPost] Sick Sigma

This strategy combines Volume Weighted Moving Average (VWMA) Bollinger Bands with 200-period and 50-period Exponential Moving Averages (EMAs). It identifies long trade opportunities when the 50 EMA is above the 200 EMA and price falls to or below the lower Fib

Strategy v4 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of Bollinger Band with Fib Golden Ratio (0.618)

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers