You drop a moving average on the chart, and it lags. You drop a Bollinger Band on top, and the bands swell and shrink around a line that cannot tell the difference between a drift and a spike. Eventually you start drawing a trend channel by hand, dragging two parallel lines until they hug the swings, and then you wonder why a computer is not doing that for you. It can. A linear regression channel is the algorithmic version of that hand-drawn trend channel: one best-fit line through the last N bars, with parallel bands a set distance above and below it.
This guide builds one in Pine Script v6, in three stages. First the regression line itself with ta.linreg, including how to read its slope. Then a rolling channel you can plot on every bar. Then a true drawn channel, with deviation measured from the residuals of the fit, that updates on the last bar. Along the way we cover the traps that make regression channels behave oddly: the endpoint that moves, the difference between price deviation and residual deviation, and the history limits that stop a loop from running.
What a regression line actually computes
Linear regression fits a straight line through a window of prices by minimizing the sum of squared vertical distances between each close and the line. The result is two numbers, a slope and an intercept, which together place the line on the window. In Pine Script you do not compute either by hand. The built-in ta.linreg(source, length, offset) returns the value of that fitted line at one point in the window.
The offset argument is the part people miss. With an offset of 0, ta.linreg returns the fitted value at the current bar, the right-hand end of the line. With an offset of 1 it returns the fitted value one bar earlier on the same line. With an offset of length - 1 it returns the value at the left-hand end of the window. That is enough to recover everything you need: two endpoints give you a line to draw, and the difference between adjacent offsets gives you the slope. You can confirm the argument order in TradingView's ta.linreg reference.
Here is the smallest useful version, the line alone:
//@version=6
indicator("Linear Regression Line", overlay = true)
length = input.int(100, "Length", minval = 2)
src = input.source(close, "Source")
basis = ta.linreg(src, length, 0)
plot(basis, "Regression value", color = color.blue, linewidth = 2)Notice what this plot is. At each bar it shows the end of a different line, fitted to a different window. It is not a single straight line sliding along the chart. It is the trail left by the right-hand end of a line that is refitted on every bar. That makes it a smoother, less laggy cousin of a moving average, because a regression line extrapolates the trend inside the window instead of averaging it. If you want to compare it with the averages you already know, the moving average types guide lays out how SMA, EMA, RMA, and WMA weight the same window.
Reading the slope
Because ta.linreg accepts an offset, the slope of the fitted line costs one subtraction. The fitted value now minus the fitted value one bar back is the rise per bar:
//@version=6
indicator("Regression Slope", overlay = false)
length = input.int(100, "Length", minval = 2)
src = input.source(close, "Source")
now = ta.linreg(src, length, 0)
prior = ta.linreg(src, length, 1)
slope = now - prior
plot(slope, "Slope per bar", style = plot.style_columns,
color = slope >= 0 ? color.teal : color.maroon)
hline(0)A few points are worth knowing about this number. It is in price units per bar, so a slope of 12 means very different things on a 60,000 asset and a 0.40 asset. If you want to compare slopes across symbols, divide by the current price, or by ta.atr(length), to get a unitless number. It is also a statement about the past window only. A positive slope says the best-fit line through the last 100 bars rises. It makes no claim about the next bar.
The window length changes what the slope means more than any other setting. A length of 20 produces a slope that flips often and follows short swings. A length of 200 produces a slope that changes direction rarely and describes the broad drift. There is no correct value. Pick the length that matches the swing you care about, and look at several before settling.
A rolling channel you can plot on every bar
The quick way to get bands is to take the regression value and add or subtract a multiple of a deviation. Because everything here runs on every bar, the result is a set of ordinary plots that you can alert on and read in the data window:
//@version=6
indicator("Rolling Regression Bands", overlay = true)
length = input.int(100, "Length", minval = 2)
mult = input.float(2.0, "Deviation multiplier", minval = 0.1, step = 0.1)
src = input.source(close, "Source")
basis = ta.linreg(src, length, 0)
dev = ta.stdev(src, length)
upper = basis + mult * dev
lower = basis - mult * dev
pBasis = plot(basis, "Basis", color = color.blue, linewidth = 2)
pUpper = plot(upper, "Upper", color = color.gray)
pLower = plot(lower, "Lower", color = color.gray)
fill(pUpper, pLower, color = color.new(color.blue, 90))This works, and it is a reasonable first version, but be honest about what ta.stdev(src, length) measures. It is the standard deviation of the prices in the window around their own mean. In a flat range that is exactly the spread you want. In a strong trend it is not, because a steadily rising price has a large deviation from its mean even if every close sits right on the fitted line. The bands come out wider than the actual scatter around the trend. If you have used Bollinger Bands, you have seen the same behavior: the bands measure dispersion around a flat average, not around a slope.
For a channel that hugs a sloped trend properly, you want the standard deviation of the residuals, the vertical distances between each close and the fitted line. That is the version a hand-drawn channel approximates, and it is the one worth building.
The drawn channel with residual deviation
A classic regression channel is a drawing, not a trail of plots. It is three straight lines laid over the last N bars: the fitted line and two parallels. To build it, compute the endpoints and the slope outside any conditional block, then do the drawing and the residual loop only on the last bar. Running the loop on every historical bar would burn calculation time for no visible benefit.
//@version=6
indicator("Linear Regression Channel", overlay = true,
max_bars_back = 500, max_lines_count = 10)
length = input.int(100, "Length", minval = 2, maxval = 500)
mult = input.float(2.0, "Deviation multiplier", minval = 0.1, step = 0.1)
src = input.source(close, "Source")
// ta.* calls stay at global scope so they run on every bar
endVal = ta.linreg(src, length, 0)
startVal = ta.linreg(src, length, length - 1)
prior = ta.linreg(src, length, 1)
var line midLine = na
var line upLine = na
var line loLine = na
if barstate.islast
slope = endVal - prior
// population standard deviation of the residuals
float sumSq = 0.0
for i = 0 to length - 1
fitted = endVal - slope * i
res = src[i] - fitted
sumSq += res * res
dev = math.sqrt(sumSq / length)
x1 = bar_index - length + 1
x2 = bar_index
line.delete(midLine)
line.delete(upLine)
line.delete(loLine)
midLine := line.new(x1, startVal, x2, endVal,
color = color.blue, width = 2)
upLine := line.new(x1, startVal + mult * dev, x2, endVal + mult * dev,
color = color.gray)
loLine := line.new(x1, startVal - mult * dev, x2, endVal - mult * dev,
color = color.gray)There are four decisions in this script worth explaining.
The three ta.linreg calls sit at global scope on purpose. Pine's ta functions keep internal state from bar to bar, so calling them only inside an if block means they skip bars and produce inconsistent values. The compiler warns about exactly that. Compute first, branch later. If you want the background on why, how Pine Script's execution model works walks through the bar-by-bar loop.
The residual loop reads src[i] with a variable index, which means Pine cannot know in advance how far back the script will look. That is what max_bars_back = 500 is for, together with the maxval = 500 on the length input so the loop can never ask for more than the buffer holds. Leave that out and a script that looks fine on short windows can stop with a history error when someone raises the length. The max_bars_back error guide covers the failure in detail.
The fitted value at bar i back is endVal - slope * i. That works because the regression line is straight, so stepping back one bar lowers it by exactly one slope. The residual is the actual price minus that fitted value, and the deviation is the root mean square of those residuals. This is a population deviation, divided by length. TradingView's own regression tool and various community scripts differ on that divisor and on the source they use, so do not expect the numbers to match another tool to the last decimal. What matters is that you pick one definition and apply it consistently.
Finally, the old lines are deleted and recreated each time the script runs on the last bar. Reusing three var handles keeps the drawing count at three no matter how many bars load, which is the habit that keeps scripts clear of the object cap discussed in the drawing objects guide.
Why the channel moves, and why that matters
The most common confusion with a regression channel is that it changes. Scroll back after a few new bars and the channel you were looking at is gone. This is not a bug. It is built into the idea. The line is the best fit to the last N bars, so when a new bar arrives and the oldest bar leaves the window, the whole fit is recomputed. The slope changes, the intercept changes, and the deviation changes.
That has a consequence that is easy to miss when you study a chart afterward. A channel drawn as a single object always describes the latest window. If you want to judge how the channel would have looked at an earlier moment, you cannot read it off a screenshot of the current one. The rolling-plot version records the end of the fit as it was on each bar, but even then the right-hand edge of the current bar moves until the bar closes, so a close above the upper band can disappear if the price falls back before the bar finishes. The repainting guide breaks this down into its separate causes, and the barstate.isconfirmed explainer shows how to wait for the closed bar.
If you add alerts to the rolling version, put the confirmation check in the condition so the alert refers to a closed bar:
//@version=6
indicator("Regression Band Alerts", overlay = true)
length = input.int(100, "Length", minval = 2)
mult = input.float(2.0, "Deviation multiplier", minval = 0.1, step = 0.1)
src = input.source(close, "Source")
basis = ta.linreg(src, length, 0)
dev = ta.stdev(src, length)
upper = basis + mult * dev
lower = basis - mult * dev
crossedUp = ta.crossover(close, upper)
crossedDown = ta.crossunder(close, lower)
closeAbove = barstate.isconfirmed and crossedUp
closeBelow = barstate.isconfirmed and crossedDown
plot(basis, "Basis", color = color.blue)
plot(upper, "Upper", color = color.gray)
plot(lower, "Lower", color = color.gray)
alertcondition(closeAbove, "Close above upper band", "Close crossed above the upper band")
alertcondition(closeBelow, "Close below lower band", "Close crossed below the lower band")Note that the crossover calls sit on their own lines, before the confirmation test. In v6 the right-hand side of and is skipped when the left side is false, and a ta function that gets skipped misses bars of history. Computing first and combining after avoids it. The lazy evaluation article explains that trap in full.
Choosing length and multiplier
Two inputs control the whole channel, and both are judgment calls rather than constants.
For the length, think in terms of the structure you want to describe. A short window, say 30 to 50 bars, makes a channel that bends to recent swings and breaks often. A long window, 200 to 500 bars, produces a broad channel that rarely changes direction and holds most of the price action inside it. If the same script has to serve more than one timeframe, make the length an input and test it on each one instead of assuming a number that suits the daily chart also suits the 15 minute chart.
For the multiplier, 2.0 is a common default, borrowed from Bollinger Bands, where it brackets roughly 95 percent of observations if prices were normally distributed. Prices are not, so treat 2.0 as a starting point, not a boundary with a probability attached to it. Some people prefer 1.0 and 2.0 together, so that the inner pair shows a normal excursion and the outer pair shows an unusual one. Because a multiplier is just a number you multiply by, adding a second pair of bands is two extra lines of code.
Both settings only describe how a channel is drawn. They do not tell you what price will do next, and a close outside the outer band is a fact about the past window, not a forecast.
Where this goes wrong in practice
A handful of mistakes cause most of the confused questions about regression channels. The first is calling ta.linreg inside a conditional and then wondering why the values drift from what a chart-wide plot shows. The second is using ta.stdev of price for a trending market and concluding the bands are too wide. The third is drawing the channel with line.new on every bar without deleting the old ones, which fills the drawing cap quickly. The fourth is comparing the channel with a screenshot from another tool without checking which deviation definition it used.
There is also a subtler issue with the source. input.source(close) is fine for a regression of closes, but the same code applied to hl2 or to another indicator's plot changes what the channel describes. The input.source guide covers how to feed another script's plot in. For a related volatility channel built around an average instead of a regression line, see the Keltner Channels build, which uses ATR for its width.
Extending it without rewriting it
Once the base channel works, the natural follow-ups are small: a second pair of bands at a different multiplier, a fill that changes color with the slope, a label showing the current slope in percent, a switch between price deviation and residual deviation. Each one is a few lines in a script you already understand.
That is a good fit for an AI editor, because the request is a change to existing code rather than a new script. In PineScripter you can describe the change in plain English, for example "add inner bands at one deviation and color the fill by slope", and the editor changes only the lines that are affected instead of regenerating the whole script. The Code Changes view then shows what each edit touched, line by line, so you can review it before it goes anywhere. Each script is also checked for compile errors, and the AI fixes the ones it finds, so you are not copying error text between TradingView and a chat window. You can run the result on the built-in chart against crypto market data, and step through it with Replay to watch how the channel refits as each bar arrives, which is the quickest way to see the moving-endpoint behavior described above for yourself. Plans and credits are on the pricing page.
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.
Frequently asked questions
What does the offset argument in ta.linreg do?
It chooses where on the fitted line the value is read. An offset of 0 returns the value at the current bar, 1 returns the value one bar earlier on the same line, and length - 1 returns the value at the left edge of the window.
Why does my regression channel change when new bars arrive?
The line is the best fit to the last N bars. Each new bar shifts the window, so the slope, intercept, and deviation are recomputed. A channel always describes the latest window.
Should I use ta.stdev of price or the standard deviation of residuals?
Residuals give bands that hug a sloped trend. The standard deviation of price measures spread around a flat mean, so in a strong trend it makes the bands wider than the scatter around the fitted line.
Why is ta.linreg flagged when I call it inside an if block?
ta functions keep state from bar to bar. Calling them only on some bars makes them skip history and return inconsistent values, so compute them at global scope and branch afterward.
How many bars should the regression length be?
There is no correct value. Around 30 to 50 bars follows recent swings, and 200 to 500 bars describes the broad drift. Make it an input and compare several on your timeframe.
Describe your indicator in plain English and get Pine Script that compiles →
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.