Standard Deviation Channels (ThinkorSwim identical)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SUNNY29081975

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

price = input(close, "price")
deviations = input(2.0, "deviations")
fullRange = input(false, "fullRange")
length = input(21, "length")

uppercolor = input(color.yellow, "Upper line")
middlecolor = input(color.yellow, "Middle line")
lowercolor = input(color.yellow, "Lower line")



//-- change this variable to the miximum number of bars you want to cover. must be bigger then length  --//
//-- even if full range is off.
max_bars_back=1560
//----------------------------------------------------------------------------//

max_bars_back(price, max_bars_back)

Sqr(x) => x*x

newlength = fullRange ? max_bars_back : length 

InertiaAll (y, n) =>
    var x = 0
    x := x + 1
    a = (n * math.sum(x * y, n) - math.sum(x, n) * math.sum(y, n) ) / ( n * math.sum(Sqr(x), n) - Sqr(math.sum(x, n)))
    b = (math.sum(Sqr(x), n) * math.sum(y, n) - math.sum(x, n) * math.sum(x * y, n) ) / ( n * math.sum(Sqr(x), n) - Sqr(math.sum(x, n)))
    InertiaTS = a * x + b
    [InertiaTS, x, a, b]

[regression, x1, a1, b1] = InertiaAll(price, newlength)
stdDeviation = ta.stdev(price, newlength)

var UpperLine = line.new(0, low, 0, low, color=uppercolor, extend=extend.right) //regression + deviations * stdDeviation;
var MiddleLine = line.new(0, low, 0, low, color=uppercolor, extend=extend.right) //regression;
var LowerLine = line.new(0, low, 0, low, color=uppercolor, extend=extend.right) // regression - deviations * stdDeviation;


if barstate.islast 

    line.set_xy1(UpperLine, last_bar_index - newlength + 1, a1*x1[newlength - 1] +b1 + deviations * stdDeviation) 
    line.set_xy2(UpperLine, last_bar_index, a1*x1 +b1 + deviations * stdDeviation)    

    line.set_xy1(MiddleLine, last_bar_index - newlength + 1, a1*x1[newlength - 1] +b1) 
    line.set_xy2(MiddleLine, last_bar_index, a1*x1 +b1)    
    
    line.set_xy1(LowerLine, last_bar_index - newlength + 1, a1*x1[newlength - 1] +b1 - deviations * stdDeviation) 
    line.set_xy2(LowerLine, last_bar_index, a1*x1 +b1 - deviations * stdDeviation)    