Three Linear Regression Channels
// This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License https://creativecommons.org/licenses/by-sa/4.0/
// © alexgrover

import Fuwn/StringToNumber/1

//@version=5
indicator('Three Linear Regression Channels', overlay = true)

int N = bar_index

int   length  = input.int(100,"Length")
float source  = input.source(close)
bool  e0      = input.bool(true, "Midline Visibility")
color midline = input.color(color.white, "Midline Colour")
bool  e1      = input.bool(true, "Channel One Visibility")
float m1      = input.float(1, "Channel One Multiplicative Factor")
color c1      = input.color(color.green, "Channel One Colour")
bool  e2      = input.bool(true, "Channel Two Visibility")
float m2      = input.float(2, "Channel Two Multiplicative Factor")
color c2      = input.color(color.yellow, "Channel Two Colour")
bool  e3      = input.bool(true, "Channel Three Visibility")
float m3      = input.float(3, "Channel Three Multiplicative Factor")
color c3      = input.color(color.red, "Channel Three Colour")
float a       = ta.wma(source, length)
float b       = ta.sma(source, length)
float A       = 4 * b - 3 * a
float B       = 3 * a - 2 * b
float m       = (A - B) / (length - 1)
float d       = 0

for i = 0 to length - 1 by 1
    l  = B + m * i
    d += math.pow(source[i] - l, 2)
    
    d

l(color c, float k, s = line.style_solid) => line.delete(line.new(N - length + 1, A + k, N, B + k, extend = extend.right, color = c, style = s)[1])

c(float mf, color c) =>
    rmse = math.sqrt(d / (length - 1)) * mf

    l(c, rmse)
    l(c, -rmse)

if e0
    l(midline, 0, line.style_dashed)

if e1
    c(m1, c1)

if e2
    c(m2, c2)

if e3
    c(m3, c3)
