Indicator · Pine Script v5 · On the chart

Periodic Linear Regressions LuxAlgo

by theonetrade· code credited to LuxAlgo

Periodic Linear Regressions LuxAlgo calculates linear regression channels anchored periodically across user-defined timeframes or from the first bar.

View on GitHub

GitHub stars34on the repository
Pine versionv5runs as is
Lines of code171
Settings15inputs
LicenceMIT
Last update2 weeks ago8 Nov 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

171 lines of Pine Script v5 from assets/indicator/bit-exact/periodic_linear_regressions_luxalgo_mKEtjG7e.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

periodic_linear_regressions_luxalgo_mKEtjG7e.pine
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo

//@version=5
indicator(    'Periodic Linear Regressions [LuxAlgo]'
 , shorttitle='LuxAlgo - Periodic Linear Regressions'
 , max_lines_count=500
 , overlay=true
 )

//---------------------------------------------------------------------------------------------------------------------}
// Settings
//---------------------------------------------------------------------------------------------------------------------{
choice       =                       input.string   ('Rolling', 'Method'      , options=[ 'Static', 'Rolling'])
anchor       =                       input.string   ('Periodic','Anchor Type' , options=['Periodic', 'First Bar']
             ,                       tooltip        =  "'First Bar' -> Choice: 'Rolling' "                        )
res          =                       input.timeframe(   'W'   ,'Anchor Period'                                     )
src          =                       input.source   (close   , 'Source'                                             )
mult         =                       input.float    (1      ,  'Multiple'     , step=0.1 , minval=0.1                )
bands        =                       input.bool     (true  ,   'Show Extremities'                                     )
col          =                       input.color(#FF5D00 ,'Mono color          ', group='Color Settings', inline='1')
bicolor      =                       input.bool     (true   ,   'Bicolor        ' , group='Color Settings', inline='a')
colA         =                       input.color    (#089981,       ''          , group='Color Settings', inline='a')
colB         =                       input.color    (#F23645 ,      ''          , group='Color Settings', inline='a')
grad         =                       input.bool     (    true   , 'Gradient'      , group='Color Settings', inline='c')
grade        =                       input.int      (15,'    ' ,minval=0,maxval=50, group='Color Settings', inline='c')
showDash     =                       input.bool     (    true , 'Show Dashboard'  , group=    'Dashboard'           )
dashLoc      = str.replace(str.lower(input.string   (  'Top Right'                ,           'Location'  
   , options =                      ['Top Right' , 'Bottom Right', 'Bottom Left'] , group=  'Dashboard'        ))
   , ' ', '_')
textSize     =             str.lower(input.string   ( 'Normal'                    ,             'Size'      
   , options =                      ['Tiny', 'Small', 'Normal']                   , group='Dashboard'    ))

//---------------------------------------------------------------------------------------------------------------------}
//Variables
//---------------------------------------------------------------------------------------------------------------------{
var tb = table.new(dashLoc, 2, 3
  , bgcolor      = #1e222d
  , border_color = #373a46
  , border_width = 1
  , frame_color  = #373a46
  , frame_width  = 1)

lbi = last_bar_index
n   = bar_index
INV = color(na)

//---------------------------------------------------------------------------------------------------------------------}
//Function
//---------------------------------------------------------------------------------------------------------------------{
draw(res, src, choice, anchor, bands, col, idx) =>

    float yMx    = na
    float dist   = na

    ch = timeframe.change(res)

    var line ln  = na
    var line lnU = na
    var line lnD = na

    var aX  = array.new< int >()        
    var aY  = array.new<float>()
    var Ex  = 0.   , var Ey  = 0. 
    var Ex2 = 0.   , var Exy = 0.  
    var N   = 0

    Ex   += n                //sum x
    Ey   += src              //sum y 
    Ex2  += math.pow(n, 2)   //sum x²
    Exy  += n * src          //sum x*y
    N    += 1                //population size

    //add x & y values to array
    aX.unshift( n )
    aY.unshift(src)

    cov   = aY. covariance(aX)
    x_var = aX.   variance(  )
    a_    =            cov / x_var
    b_    = aY.avg() - a_  * aX.avg()
    r2    = math.pow(  cov / (aY.stdev() 
                           *  aX.stdev()), 2)
    rss   = aY.variance()  
          - r2 
          * aY.variance()         

    dist := math.sqrt(rss) 
          * mult

    m = (N * Exy - Ex * Ey) / (N * Ex2 - math.pow(Ex, 2))
    b = (Ey - m * Ex) / N

    yMx := m * n + b
    
    if choice == 'Static'    
        cl = bicolor 
           ? ln.get_y2() > ln.get_y1() 
           ? colA : colB : col

        x1 =      ln.get_x1()    
        ln.set_xy2(n ,   yMx ) 
        ln.set_y1 (m * x1 + b)

        if bicolor 
            ln.set_color(cl)

        if bands 
            lnU.set_xy2(n , yMx   +   dist)
            lnU.set_y1 (m * x1  + b + dist)
            lnU.set_color(cl)

            lnD.set_xy2(n , yMx   -   dist)
            lnD.set_y1 (m * x1  + b - dist)
            lnD.set_color(cl)

    if ch
        if  anchor == 'Periodic' 
         or choice == 'Static' 
            Ex  := 0. 
            Ey  := 0. 
            Ex2 := 0. 
            Exy := 0. 
            aX.clear() 
            aY.clear()
        N   := 0
        if choice == 'Static'    
            ln      := line.new(n, src       , n, src       , color=col)
            if bands 
                lnU := line.new(n, src + dist, n, src + dist, color=col)
                lnD := line.new(n, src - dist, n, src - dist, color=col)

    R = cov / (aX.stdev() * aY.stdev())

    [  choice == 'Rolling'           ? yMx        : na
     , choice == 'Rolling' and bands ? yMx + dist : na
     , choice == 'Rolling' and bands ? yMx - dist : na 
     , R
     ]
            
//---------------------------------------------------------------------------------------------------------------------}
//Execution
//---------------------------------------------------------------------------------------------------------------------{
[yMx, yMx_pos, yMx_min, R]    =    draw(res, src, choice, anchor, bands, col, 0)

//---------------------------------------------------------------------------------------------------------------------}
//Plot
//---------------------------------------------------------------------------------------------------------------------{
rolling    =    bicolor and choice == 'Rolling'
m = plot(yMx    , color=rolling ? color.from_gradient(R, -1, 1, colB, colA) : col, style=plot.style_linebr)
b = plot(yMx_min, color=rolling ? color              (         na         ) : col, style=plot.style_linebr)
t = plot(yMx_pos, color=rolling ? color              (         na         ) : col, style=plot.style_linebr)

fill(m, t, yMx, yMx_pos,  grad  ? color.new          ( 
                                  color.from_gradient(R, -1, 1, colB, colA) , 100                    ) : na
                       ,  grad  ? color.new          ( 
                                  color.from_gradient(R, -1, 1, colB, colA) , 100  -     grade       ) : na)
fill(m, b, yMx, yMx_min,  grad  ? color.new          ( 
                                  color.from_gradient(R, -1, 1, colB, colA) , 100                    ) : na
                       ,  grad  ? color.new          ( 
                                  color.from_gradient(R, -1, 1, colB, colA) , 100  -     grade       ) : na)

//---------------------------------------------------------------------------------------------------------------------}
//Dashboard
//---------------------------------------------------------------------------------------------------------------------{
if barstate.islast
    if showDash
        tb.cell(0, 0,     'HTF'        , text_color=color.white, text_size=textSize)
        tb.cell(1, 0, str.tostring(res), text_color=color.white, text_size=textSize)

//---------------------------------------------------------------------------------------------------------------------}

Overview

Users can select static or rolling calculation methods, adjust standard deviation multiplier bounds, and display outer extremity lines. Visual customization includes monochromatic, dual-color directional modes, and color gradient fills. An optional onscreen table dashboard provides linear regression statistics directly on the main price chart.

Details

Published by

theonetrade on GitHub

Code credit

LuxAlgo, as written in the script's header

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.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

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

SettingTypeDefaultVariable
MethodstringRollingchoice
Anchor TypestringPeriodicanchor
Anchor PeriodtimeframeWres
Sourcesourceclosesrc
Multiplefloat1mult
Show Extremitiesbooltruebands
Mono color color#FF5D00col
Bicolor booltruebicolor
colAcolor#089981colA
colBcolor#F23645colB
Gradientbooltruegrad
int15grade
Show all 15 settings
SettingTypeDefaultVariable
Show DashboardbooltrueshowDash
LocationstringTop RightLocation
SizestringNormalSize
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

257 stars

This indicator overlays an intraday SPX and ES chart with a midnight session range, regular-trading-hours opening levels, and a VWAP projection box. It draws the midnight high, mid, and low, flags edge rejections within an absolute tolerance, and plots optiona

Indicator v6 TrendSupport & resistance
Updated 2 months ago · None stated GitHub repository of SPX Midnight Box + Snag Logic
53 stars

Apex Trend & Liquidity Master calculates a trend cloud using customizable moving averages expanded by a volatility multiplier directly on the main price chart. It identifies dynamic support and resistance liquidity zones from swing high and low pivots, extendi

Indicator v6 TrendSupport & resistance
Updated 3 months ago · MPL-2.0 GitHub repository of Apex Trend & Liquidity Master

TheStrat Suite

by 345-strategies
30 stars

This indicator implements Rob Smith's TheStrat price action methodology across up to six configurable timeframes. It classifies candles into inside, directional, and outside bars, identifies patterns like hammers, shooters, and failed 2s, and calculates magnit

Indicator v6 Candlestick patternsSupport & resistance Repaints
Updated 2 weeks ago · MPL-2.0 GitHub repository of TheStrat Suite

This indicator detects fast and slow Exponential Moving Average crossovers filtered by a long-term trend EMA. Upon a signal, it projects the entry line, dynamic stop loss based on recent swing extremes and an ATR distance multiplier, and up to three R-multiple

Indicator v6 Moving averagesTrend
Updated 3 weeks ago · MIT GitHub repository of EMA Crossover - 9/21 with 200 EMA Filter, Entry, Stop and Targets
13 stars

The Adaptive Trend Finder calculates logarithmic linear regression channels overlaid on the price chart. Operating on the most recent historical bar, it fits a log-transformed regression line and standard deviation bands. It evaluates linear correlation using

Indicator v6 TrendSupport & resistance Repaints
Updated 6 months ago · MIT GitHub repository of Adaptive Trend Finder (log)

Market Monitor - 1m

by chris-c-thomas
13 stars

Market Monitor - 1m is an overlay indicator designed for multi-chart monitoring and directional bias assessment. It plots a fast, mid, and slow EMA ribbon with a fill cloud, session VWAP with standard deviation bands, and previous day key levels. It evaluates

Indicator v6 TrendMoving averages Repaints
Updated 7 months ago · MIT GitHub repository of Market Monitor - 1m

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