Indicator · Pine Script v5 · On the chart

Linear Regression

by g-moe· code credited to goodgains

This indicator calculates and plots a linear regression line alongside upper and lower deviation bands directly on the price chart.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code110
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago27 May 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

110 lines of Pine Script v5 from Tradingview/linear-regression-v2.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

linear-regression-v2.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © goodgains


//@version=5
indicator("Linear Regression", overlay = true)

// @keywords: linear-regression, regression-channel, regression-line, deviation-bands, standard-deviation-channel, upper-band, lower-band, middle-line, trend-direction, bullish-trend, bearish-trend, ascending-trend, regression-slope, line-extension, channel-fill, regression-envelope, dynamic-trend-line, support-resistance, price-channel, trend-detection

//
//TF1
//
use_TF1 = true
TF1_timeframe = ""
TF1_price = close
TF1_linreg_length = input.int(title='Length ', defval=50, inline='3', maxval = 5000, minval = 10, group='Settings') 
TF1_linreg_deviation = input.float(title='Deviation ', defval=2.00, step=0.25, minval=0.1, maxval=5.00, inline='3', group='Settings') 
TF1_color = input.color(color.new(#d5d5d5, 0), title='Neut Color', inline='4', group='Settings') 
TF1_bullcolor = input.color(color.new(#58ff63, 0), title='Bull Color', inline='5', group='Settings') 
TF1_bearcolor = input.color(color.new(#c61d1d, 0), title='Bear Color', inline='6', group='Settings') 
TF1_extend = input.string(defval = 'None', title = 'Extension', options = ['Both', 'Right', 'Left', 'None'], inline='7', group='Settings') 
TF1_width = input.int(1, title = 'Width', minval = 1, maxval = 5, inline='8', group='Settings') 
TF1_bg = input.int(90, minval = 0, maxval = 100, title = 'Background Transparency', inline='9', group='Settings') 
TF1_extendStyle = switch
    TF1_extend == "Both" => extend.both
    TF1_extend == "Left" => extend.left
    TF1_extend == "Right" => extend.right
    => extend.none
//


//
//FUNCTION TO CALCULATE VALUES
//
calculate_linreg(source, length, deviation) =>
    a = ta.wma(source, length)
    b = ta.sma(source, length)
    A = 4 * b - 3 * a
    B = 3 * a - 2 * b
    m = (A - B) / (length - 1)
    
    d = 0.00
    for i = 0 to length - 1 by 1
        l = B + m * i
        d += math.pow(source[i] - l, 2)
        d
    linreg_1 = math.sqrt(d / (length - 1)) * deviation
    
    y1_midvalue = A + 0
    y2_midvalue = -m + (B + 0)

    y1a =  A - linreg_1
    y1b = A + linreg_1
    y2a = -m + (B - linreg_1)
    y2b = -m + (B + linreg_1)
    
    y1_uppervalue = math.round_to_mintick(math.max(y1a,y1b))
    y1_lowervalue = math.round_to_mintick(math.min(y1a,y1b))
    y2_uppervalue = math.round_to_mintick(math.max(y2a,y2b))
    y2_lowervalue = math.round_to_mintick(math.min(y2a,y2b))
    
    x1_value = time[length]
    
    [x1_value, y1_midvalue, y2_midvalue, y1_uppervalue, y2_uppervalue, y1_lowervalue, y2_lowervalue]




drawLinReg(color_input, extension_input, width_input, x1_value, y1_value, y2_value, linreg_length, TF_input, draw_label, label_text, line_style) =>

    if draw_label
        label label_variable = label.new(bar_index + 5, y2_value, text=label_text + "" + str.tostring(math.round_to_mintick(y2_value)), style=label.style_label_left, textcolor = color.black, color = color_input, textalign = text.align_left)
        label.delete(label_variable[1])
        
    line line_variable = line.new(x1_value, y1_value, time, y2_value, extend = extension_input,
     color = color_input, width = width_input, xloc = xloc.bar_time, style = line_style)
    line_variable
    


[TF1_x1_value, TF1_y1_midvalue, TF1_y2_midvalue, TF1_y1_uppervalue, TF1_y2_uppervalue, TF1_y1_lowervalue, TF1_y2_lowervalue]= calculate_linreg(TF1_price, TF1_linreg_length, TF1_linreg_deviation)

isAscendingTrend(nBars) =>
    var float sumSlopes = 0.0
    for i = 1 to nBars
        startValue = close[i]
        endValue = close
        slope = (endValue - startValue) / i
        sumSlopes := sumSlopes + slope
    
    averageSlope = sumSlopes / nBars
    averageSlope > 0




// slope1 = tf1_B > tf1_B[1]
IsAscending = isAscendingTrend(10) or (TF1_y2_midvalue > TF1_y1_midvalue)

if true
    TF1_mid = drawLinReg( IsAscending ? color.new(TF1_bullcolor, 0) : color.new(TF1_bearcolor, 0), TF1_extendStyle, TF1_width, TF1_x1_value, TF1_y1_midvalue, TF1_y2_midvalue, TF1_linreg_length, TF1_timeframe, true, "", line.style_dashed)
    TF1_upper = drawLinReg(color.new(TF1_color, 0), TF1_extendStyle, TF1_width, TF1_x1_value, TF1_y1_uppervalue, TF1_y2_uppervalue, TF1_linreg_length, TF1_timeframe, true, "", line.style_dashed)
    TF1_lower = drawLinReg(color.new(TF1_color, 0), TF1_extendStyle, TF1_width, TF1_x1_value, TF1_y1_lowervalue, TF1_y2_lowervalue, TF1_linreg_length, TF1_timeframe,true, "", line.style_dashed)
    linefill TF1_fill = linefill.new(TF1_upper, TF1_lower, color.new(TF1_color,TF1_bg)) 
    
    if not na(TF1_mid[1])
        line.delete(TF1_mid[1])
        line.delete(TF1_upper[1])
        line.delete(TF1_lower[1])
        linefill.delete(TF1_fill[1])

Overview

Linear Regression determines linear regression slope and channel width using weighted and simple moving average formulas across a user-specified lookback period. Traders can use the channel to identify trend slope and dynamic support and resistance levels. Settings allow customizing the calculation length, standard deviation multiplier, line extension style, line thickness, background transparency, and bullish or bearish line color schemes.

Details

Published by

g-moe on GitHub

Code credit

goodgains, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Trend, Support & resistance

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.

Settings

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

SettingTypeDefaultVariable
Length int50TF1_linreg_length
Deviation float2.00TF1_linreg_deviation
Neut Colorcolorcolor.new(#d5d5d5, 0)TF1_color
Bull Colorcolorcolor.new(#58ff63, 0)TF1_bullcolor
Bear Colorcolorcolor.new(#c61d1d, 0)TF1_bearcolor
ExtensionstringNoneTF1_extend
Widthint1TF1_width
Background Transparencyint90TF1_bg
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

575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener

Function - Linear Regression

by ricardosantos79
261 stars

This indicator fits a linear regression through stored pivot highs and lows and draws the resulting channel on the price chart. A function returns predicted values, maximum and minimum deviations, and the average absolute deviation. Confirmed two-bar pivots up

Indicator v5 TrendSupport & resistance
Updated 4 years ago · None stated GitHub repository of Function - Linear Regression

AI Trend

by dearvn
257 stars

AI Trend is an indicator that plots pivot points, trend lines, and support and resistance levels directly on the price chart. It marks high and low pivots based on user-defined length, draws trend lines that check for violations at specified points, and identi

Indicator v5 TrendSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of AI Trend

Ichimoku Cloud

by harryguiacorn
219 stars

This indicator plots Ichimoku Cloud elements on the price chart, including Tenkan-sen, Kijun-sen, Senkou Span A and B lines with optional Chikou Span. It signals trend changes via Tenkan-sen and Kijun-sen crosses and places arrows at Kijun-sen direction shifts

Indicator v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ichimoku Cloud
219 stars

This indicator identifies local swing highs and swing lows to construct a Zig Zag pattern on the main price chart. It evaluates pivot points based on a customizable number of surrounding left and right bars. Using persistent variables, the script tracks previo

Indicator v4 Support & resistanceTrend Repaints
Updated 5 years ago · None stated GitHub repository of Teaching: Finding Highs and Lows 6

Dynamic Linear Regression

by TradersPost
218 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 3 months ago · None stated GitHub repository of Dynamic Linear Regression

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers