Indicator · Pine Script v4 · On the chart

Linear Regression Channel

by jerryinyang· code credited to LonesomeTheBlue

The Linear Regression Channel indicator calculates the middle line via linear regression on a user-selected source over a configurable length.

View on GitHub

GitHub stars5on the repository
Pine versionv4older, still runs
Lines of code85
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago12 May 2024

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

85 lines of Pine Script v4 from Codebase/Line Regression.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Line Regression.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LonesomeTheBlue

//@version=4
study("Linear Regression Channel", overlay = true, max_bars_back = 1000, max_lines_count = 300)
src = input(defval = close, title = "Source")
len = input(defval = 100, title = "Length", minval = 10)
devlen = input(defval = 2., title = "Deviation", minval = 0.1, step = 0.1)
extendit = input(defval = true, title = "Extend Lines")
showfibo = input(defval = false, title = "Show Fibonacci Levels")
showbroken = input(defval = true, title = "Show Broken Channel")
upcol = input(defval = color.lime, title = "Up Color")
dncol = input(defval = color.red, title = "Down Color")
widt = input(defval = 2, title = "Line Width")

var fibo_ratios = array.new_float(0)
var colors = array.new_color(2)
if barstate.isfirst
    array.unshift(colors, upcol)
    array.unshift(colors, dncol)
    array.push(fibo_ratios, 0.236)
    array.push(fibo_ratios, 0.382)
    array.push(fibo_ratios, 0.618)
    array.push(fibo_ratios, 0.786)



get_channel(src, len)=>
    mid = sum(src, len) / len
    slope = linreg(src, len, 0) - linreg(src, len, 1)
    intercept  = mid - slope * floor(len / 2) + ((1 - (len % 2)) / 2) * slope
    endy = intercept  + slope * (len - 1) 
    dev = 0.0
    for x = 0 to len - 1
        dev := dev + pow(src[x] - (slope * (len - x) + intercept), 2)
    dev := sqrt(dev/len)
    [intercept, endy, dev, slope]

[y1_, y2_, dev, slope] = get_channel(src, len)

outofchannel = (slope > 0 and close < y2_ - dev * devlen) ? 0 : (slope < 0 and close > y2_ + dev * devlen) ? 2 : -1

var reglines = array.new_line(3)
var fibolines = array.new_line(4)
for x = 0 to 2
    if not showbroken or outofchannel != x or nz(outofchannel[1], -1) != -1
        line.delete(array.get(reglines, x))
    else
        line.set_color(array.get(reglines, x), color = color.blue)
        line.set_width(array.get(reglines, x), width = 2)
        line.set_style(array.get(reglines, x), style = line.style_dotted)
        line.set_extend(array.get(reglines, x), extend = extend.none)
    
    array.set(reglines, x, 
              line.new(x1 = bar_index - (len - 1), 
                       y1 = y1_ + dev * devlen * (x - 1), 
                       x2 = bar_index, 
                       y2 = y2_ + dev * devlen * (x - 1),
                       color = array.get(colors, round(max(sign(slope), 0))),
                       style =  x % 2 == 1 ? line.style_solid : line.style_dashed,
                       width = widt,
                       extend = extendit ? extend.right : extend.none))
if showfibo
    for x = 0 to 3
        line.delete(array.get(fibolines, x))
        array.set(fibolines, x, 
                  line.new(x1 = bar_index - (len - 1), 
                           y1 = y1_ - dev * devlen + dev * devlen * 2 * array.get(fibo_ratios, x), 
                           x2 = bar_index, 
                           y2 = y2_ - dev * devlen + dev * devlen * 2 * array.get(fibo_ratios, x),
                           color = array.get(colors, round(max(sign(slope), 0))),
                           style =  line.style_dotted,
                           width = widt,
                           extend = extendit ? extend.right : extend.none))
    
var label sidelab = label.new(x = bar_index - (len - 1), y = y1_, text = "S",  size = size.large)
txt = slope > 0 ? slope > slope[1] ? "⇑" : "⇗" : slope < 0 ? slope < slope[1] ? "⇓" : "⇘" : "⇒"
stl = slope > 0 ? slope > slope[1] ? label.style_label_up : label.style_label_upper_right : slope < 0 ? slope < slope[1] ? label.style_label_down :  label.style_label_lower_right : label.style_label_right
label.set_style(sidelab, stl)
label.set_text(sidelab, txt)
label.set_x(sidelab, bar_index - (len - 1))
label.set_y(sidelab, slope > 0 ? y1_ - dev * devlen : slope < 0 ? y1_ + dev * devlen : y1_)
label.set_color(sidelab, slope > 0 ? upcol : slope < 0 ? dncol : color.blue)

alertcondition(outofchannel, title='Channel Broken', message='Channel Broken')

Overview

Linear Regression Channel plots upper and lower channel bands using a deviation multiplier and draws these lines directly on the price chart. Options include extending lines rightward, displaying Fibonacci retracement levels, and highlighting broken channel segments with dotted lines. The script detects price breaks above or below the bands and allows customization of colors for up and down trends, line width, and whether to show broken channel. It works on any market and timeframe with no stop loss or pyramiding.

Details

Published by

jerryinyang on GitHub

Code credit

LonesomeTheBlue, as written in the script's header

Type

Indicator, Pine Script v4

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.

Settings

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

SettingTypeDefaultVariable
Sourcesourceclosesrc
Lengthint100len
Deviationinput2.devlen
Extend Linesbooltrueextendit
Show Fibonacci Levelsboolfalseshowfibo
Show Broken Channelbooltrueshowbroken
Up Colorcolorcolor.limeupcol
Down Colorcolorcolor.reddncol
Line Widthint2widt
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

MA Envelope (MAE)

by mihakralj
99 stars

The MA Envelope indicator calculates upper and lower channel bands shifted by a user-defined percentage around a baseline moving average. It supports Simple Moving Average, Exponential Moving Average, and Weighted Moving Average calculation types. The script p

Indicator v6 Moving averagesSupport & resistance
Updated 4 weeks ago · Apache-2.0 GitHub repository of MA Envelope (MAE)

Trend Compass 4H

by chris-c-thomas
14 stars

Trend Compass 4H plots a multi-EMA ribbon (10/21/50) along with higher-timeframe reference levels on the price chart. It classifies trend phase into six states and calculates a composite weighted trend score. The script detects RSI and MACD divergences, analyz

Indicator v6 TrendMoving averages
Updated 6 months ago · MIT GitHub repository of Trend Compass 4H
10 stars

My Macro Cycle Indicator plots daily and weekly simple and exponential moving averages on the price chart, plus Pi Cycle and Mayer Multiple levels derived from the 200-day average. Optional toggles add support-band fills, a Keltner channel, CME futures gaps, a

Indicator v4 Moving averagesVolatility & bands
Updated 5 years ago · None stated GitHub repository of My Macro Cycle Indicator

This indicator plots a double-smoothed Supertrend baseline on the price chart, combining a Supertrend midline with WMA and EMA smoothing to show trend direction. Direction uses an ATR-scaled baseline slope with hysteresis, while percentile-ranked slope magnitu

Indicator v6 TrendMoving averages
Updated 3 days ago · MIT GitHub repository of Smooth Trend Radar [WavesUnchained]

SRI Indicator ft. MSB

by kingmalitha
7 stars

This indicator overlays an all-in-one technical analysis toolkit on the price chart. It plots multiple moving averages, including standard EMAs, SMAs, and a Trend Regularity Adaptive Moving Average, alongside Bollinger Bands, Supertrend, Nadaraya-Watson envelo

Indicator v5 Moving averagesTrend Repaints
Updated 3 years ago · None stated GitHub repository of SRI Indicator ft. MSB

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