Indicator · Pine Script v5 · On the chart

Linear Regression Channel

by theonetrade· code credited to ChartPrime

Linear Regression Channel is a chart overlay indicator that calculates linear regression slope, intercept, and standard deviation bands over user-defined lookback windows.

View on GitHub

GitHub stars34on the repository
Pine versionv5runs as is
Lines of code169
Settings10inputs
LicenceMIT
Last update2 weeks ago8 Nov 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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

169 lines of Pine Script v5 from assets/indicator/bit-exact/linear_regression_channel_7a8mTJpS.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

linear_regression_channel_7a8mTJpS.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime

//@version=5
indicator('Linear Regression Channel', overlay = true, max_lines_count = 3)

// ---------------------------------------------------------------------------------------------------------------------}
// 𝙐𝙎𝙀𝙍 𝙄𝙉𝙋𝙐𝙏𝙎
// ---------------------------------------------------------------------------------------------------------------------{
bool bands      = input.bool(true, "Plot Linear Regression Bands", group = "Settings Bands")

int window      = input.int(150, "Length", group = "Settings Bands")
float devlen_b  = input.float(3., "Deviation Linear Regression Bands",step=0.1, group = "Settings Bands")

bool channel    = input.bool(false, "Plot Linear Regression Channel", group = "Settings Channel")
int window1     = input.int(150, "Channel Length", group = "Settings Channel")
float devlen1   = input.float(1., "Deviation Linear Regression Channel",step=0.1, group = "Settings Channel") 

bool channel1   = input.bool(false, "Plot Future Projection of linear regression", group = "Future Projection Channel")
bool arr_dirc   = input.bool(false, "Plot Arrow Direction", group = "Future Projection Channel")
int window2     = input.int(50, "Length", group = "Future Projection Channel")
float devlen2   = input.float(1., "Deviation Future Projection Regression Channel",step=0.1, group = "Future Projection Channel") 

// Define colors for up, down, and mid lines
color col_dn      = #f01313
color col_up      = color.aqua
color col_mid     = color.yellow
color gray        = color.gray
color fg_col      = chart.fg_color

// Regression Channel Arrays Line
var reglines  = array.new_line(3)
var reglines_ = array.new_line(3)


// ---------------------------------------------------------------------------------------------------------------------}
// 𝙄𝙉𝘿𝙄𝘾𝘼𝙏𝙊𝙍 𝘾𝘼𝙇𝘾𝙐𝙇𝘼𝙏𝙄𝙊𝙉𝙎
// ---------------------------------------------------------------------------------------------------------------------{

//@function linear_regression
//@description Calculates linear regression coefficients for a given source and window.
//@param src  (series float) The data series on which linear regression is calculated.
//@param window  (int) The number of bars to use in the calculation.
//@returns the intercept slope, Deviation, end of the channel.
linear_regression(src, window) =>
    sum_x = 0.0
    sum_y = 0.0
    sum_xy = 0.0
    sum_x_sq = 0.0

    // Calculate sums
    for i = 0 to window - 1 by 1
        sum_x += i + 1
        sum_y += src[i]
        sum_xy += (i + 1) * src[i]
        sum_x_sq += math.pow(i + 1, 2)

    // Calculate linear regression coefficients
    slope     = (window * sum_xy - sum_x * sum_y) / (window * sum_x_sq - math.pow(sum_x, 2))
    intercept = (sum_y - slope * sum_x) / window

    y1 = intercept  + slope * (window - 1) 
    dev = 0.0
    for i = 0 to window - 1
        dev := dev + math.pow(src[i] - (slope * (window - i) + intercept), 2)
    dev := math.sqrt(dev/window)

    [intercept, y1, dev, slope]

[y2, y1, dev, slope] = linear_regression(close, window)

[y2_, y1_, dev_, slope_] = linear_regression(close, window1)

[y2__, y1__, dev__, slope__] = linear_regression(close, window2)

// Linear Regression Channel Lines
series float mid     = y2 + slope
series float upper   = mid  + ta.rma(high - low, window) * devlen_b
series float lower   = mid  - ta.rma(high - low, window) * devlen_b

// Returns True for window length period
isAllowed = (last_bar_index - bar_index < window1)


// ---------------------------------------------------------------------------------------------------------------------}
// 𝙑𝙄𝙎𝙐𝘼𝙇𝙄𝙕𝘼𝙏𝙄𝙊𝙉
// ---------------------------------------------------------------------------------------------------------------------{

// Plot upper, lower, and mid lines if channel is not enabled
p_u = plot(upper, color = bands and channel ? na : bands ? gray : na, linewidth = 2)
p_l = plot(lower, color = bands and channel ? na : bands ? gray : na, linewidth = 2)
p_m = plot(mid,   color = bands and channel ? na : bands ? gray : na)

// Fill areas between upper/mid and lower/mid lines
fill(p_u, p_m, mid, upper, na, bands and channel ? na : bands ? color.new(col_up, 80) : na)
fill(p_m, p_l, lower, mid,     bands and channel ? na : bands ? color.new(col_dn, 80) : na, na)


if barstate.islast and channel
    for i = 0 to 2
        array.set(reglines, i,
             line.new(x1 = bar_index - (window1 - 1), 
                     y1 = y1_ + dev_ * devlen1 * (i - 1), 
                     x2 = bar_index, 
                     y2 = y2_ + dev_ * devlen1 * (i - 1), 
                     color = color.gray,
                     style = i % 2 == 1 ? line.style_dashed : line.style_solid,
                     width = 2,
                     extend = extend.none)
                     )

    linefill.new(array.get(reglines, 1), array.get(reglines, 2), color = color.new(col_up, 90))
    linefill.new(array.get(reglines, 1), array.get(reglines, 0), color = color.new(col_dn, 90))


if barstate.islast and channel1
    for i = 0 to 2
        array.set(reglines_, i,
             line.new(x1 = bar_index - (window2 - 1), 
                     y1 = y1__ + dev__ * devlen2 * (i - 1), 
                     x2 = bar_index, 
                     y2 = y2__ + dev__ * devlen2 * (i - 1), 
                     color = color.gray,
                     style = i % 2 == 1 ? line.style_dotted : line.style_dashed,
                     width = 1,
                     extend = extend.right)
                     )               

    linefill.new(array.get(reglines_, 1), array.get(reglines_, 2), color = color.new(col_up, 95))
    linefill.new(array.get(reglines_, 1), array.get(reglines_, 0), color = color.new(col_dn, 95))


if arr_dirc
    l1 = label.new(chart.point.from_index(bar_index, hl2 > y2__ ? high : low), 
             text = hl2 > y2__ ? "⇗" : hl2 < y2__ ? "⇘" : "⇒",
             textcolor = hl2 > y2__ ? col_up : hl2 < y2__ ? col_dn : gray, 
             color = color(na), 
             size = size.huge, 
             style =  label.style_label_left
             )     
    label.delete(l1[1])

// Bar Heat Map
b_c = (close - lower) / (upper - lower)
b_c := b_c > 1 ? 1 : b_c < 0 ? 0 : b_c

bar_color = channel ? 
     (isAllowed ?
         (b_c <= 0.5 ? color.from_gradient(b_c, 0, 0.5, col_up, col_mid) : color.from_gradient(b_c, 0.5, 1, col_mid, col_dn))
         : na) 
     : (b_c >= 0.5 ? color.from_gradient(b_c, 0.5, 1, col_mid, col_up) : color.from_gradient(b_c, 0, 0.5, col_dn, col_mid))

plotcandle(open, high, low, close, 
             title = "Bar HeatMap", 
               color = bar_color,
                 wickcolor = bar_color,
                  bordercolor = bar_color
                     )
barcolor(bar_color)

// Conditions for crossovers
condition1 = bands and channel ? na : bands ? ta.pivotlow(3, 3) and close < lower : na 
condition2 = bands and channel ? na : bands ? ta.pivothigh(3, 3) and close > upper: na

// Plot markers for channel break outs
plotchar(condition1, "", "◆", size=size.tiny, location=location.belowbar, color = col_up)
plotchar(condition2, "", "◆", size=size.tiny, location=location.abovebar, color = col_dn)

// ---------------------------------------------------------------------------------------------------------------------}

Overview

Linear Regression Channel plots middle regression trendlines along with upper and lower channel boundaries based on standard deviation or average true range multipliers. The script supports up to three separate regression configurations, including standard regression bands, an overlay channel, and a future projection channel with optional direction indicators.

Details

Published by

theonetrade on GitHub

Code credit

ChartPrime, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

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

SettingTypeDefaultVariable
Plot Linear Regression Bandsbooltruebands
Lengthint150window
Deviation Linear Regression Bandsfloat3.devlen_b
Plot Linear Regression Channelboolfalsechannel
Channel Lengthint150window1
Deviation Linear Regression Channelfloat1.devlen1
Plot Future Projection of linear regressionboolfalsechannel1
Plot Arrow Directionboolfalsearr_dirc
Lengthint50window2
Deviation Future Projection Regression Channelfloat1.devlen2
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

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 5 years ago · None stated GitHub repository of [RS]Donchian Fans

Dynamic Linear Regression

by TradersPost
228 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 4 months ago · None stated GitHub repository of Dynamic Linear Regression

ATR Trailing Stop

by mihakralj
99 stars

Calculates an ATR-based trailing stop overlaid on the price chart to assist with trend identification and stop placement. Using a specified ATR period and multiplier, it projects upper and lower bounds around the closing price. The stop line ratchets up during

Indicator v5 TrendVolatility & bands
Updated 8 weeks ago · Apache-2.0 GitHub repository of ATR Trailing Stop

Moon Dev Lunar Sniper

by moondevonyt
98 stars

Moon Dev Lunar Sniper is a multi-indicator overlay that scores confluence across fast and slow EMAs, RSI, MACD, DMI, and BB width to fire signals only when score meets the minimum threshold. It plots buy and sell signals on the price chart, highlights cosmic b

Indicator v6 TrendOscillators & momentum Repaints
Updated 2 months ago · Custom licence GitHub repository of Moon Dev Lunar Sniper

SuperTrend & Pivots

by dcaoyuan
55 stars

This overlay indicator plots a SuperTrend line on the price chart using a fixed ATR length of 10 and a factor of 3. When the trend direction is up it draws a green line and a light green fill toward the candle midpoint; when down it draws a red line and a ligh

Indicator v6 TrendVolatility & bands
Updated 7 months ago · Apache-2.0 GitHub repository of SuperTrend & Pivots

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers