Back to the Future
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RafaelZioni

//@version=5
indicator(title='Back to the Future', overlay=true)
//INPUTS
//
len = input.int(100, minval=1)
off = 0
dev = input(2, 'Deviation')
len1 = input.int(30, minval=1)
off1 = 0
dev1 = input(2, 'Deviation1')
c1 = close

lreg1 = ta.linreg(c1, len, off)
lreg_x1 = ta.linreg(c1, len, off + 1)
b1 = bar_index
s1 = lreg1 - lreg_x1
intr1 = lreg1 - b1 * s1
dS1 = 0.0
for i1 = 0 to len - 1 by 1
    dS1 += math.pow(c1[i1] - (s1 * (b1 - i1) + intr1), 2)
    dS1
de1 = math.sqrt(dS1 / len)
up1 = -de1 * dev + lreg1
down1 = de1 * dev + lreg1
//

//
t1 = 0
x11 = bar_index - len
x21 = bar_index
y11 = s1 * (bar_index - len) + intr1
y21 = lreg1
u1 = t1 <= 0 or bar_index < t1
if u1
    line pr1 = line.new(x11, y11, x21, y21, xloc.bar_index, extend.right, color.red, width=2)
    line.delete(pr1[1])
    line px1 = line.new(x11, de1 * dev + y11, x21, de1 * dev + y21, xloc.bar_index, extend.right, width=2)
    line.delete(px1[1])
    line pz1 = line.new(x11, -de1 * dev + y11, x21, -de1 * dev + y21, xloc.bar_index, extend.right, width=2)
    line.delete(pz1[1])

//
c = close[len1]

lreg = ta.linreg(c, len1, off1)
lreg_x = ta.linreg(c, len1, off1 + 1)
b = bar_index
s = lreg - lreg_x
intr = lreg - b * s
dS = 0.0
for i = 0 to len1 - 1 by 1
    dS += math.pow(c[i] - (s * (b - i) + intr), 2)
    dS
de = math.sqrt(dS / len1)
up = -de * dev + lreg
down = de * dev + lreg
//

t = 0
x1 = bar_index - len
x2 = bar_index
y1 = s * (bar_index - len) + intr
y2 = lreg
u = t <= 0 or bar_index < t
if u
    line pr = line.new(x1, y1, x2, y2, xloc.bar_index, extend.right, color.red, style=line.style_dashed, width=2)
    line.delete(pr[1])
    line px = line.new(x1, de * dev + y1, x2, de * dev + y2, xloc.bar_index, extend.right, style=line.style_dashed, width=2)
    line.delete(px[1])
    line pz = line.new(x1, -de * dev + y1, x2, -de * dev + y2, xloc.bar_index, extend.right, style=line.style_dashed, width=2)
    line.delete(pz[1])


//
bu = ta.crossover(close, lreg)
sz = ta.crossunder(close, lreg)
bu1 = ta.crossover(close, up)
sz1 = ta.crossunder(close, up)
bu2 = ta.crossover(close, down)
sz2 = ta.crossunder(close, down)
plotshape(sz, style=shape.triangledown, location=location.abovebar, color=color.new(color.orange, 0), size=size.tiny)
plotshape(bu, style=shape.triangleup, location=location.belowbar, color=color.new(color.blue, 0), size=size.tiny)
plotshape(sz1, style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), size=size.tiny)
plotshape(bu1, style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), size=size.tiny)
plotshape(sz2, style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), size=size.tiny)
plotshape(bu2, style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), size=size.tiny)

