TradingView indicator guide

Linear regression channel: formula, width and rolling updates

A linear regression channel fits a straight line to prices over a selected window and adds parallel upper and lower boundaries. Its slope describes that window; its width depends on the chosen deviation calculation. When the window rolls forward, the entire fitted segment can move. A historical candle outside the latest redrawn channel is therefore not proof that a breakout signal existed when that candle closed.

Draft a regression channel

Read the TradingView inputs before comparing channels

TradingView documents its Linear Regression indicator with a Count input for the latest N bars, a Source input and separate upper and lower deviation settings. Increasing a deviation multiplier moves that boundary farther from the center. The help page does not specify the variance divisor. The calculation below is an explicitly defined residual-RMS channel, not a claim of exact numerical parity with every built-in or community script.

  • Use the same symbol, timeframe, session, source and window when comparing values. Five daily observations and five hourly observations describe different data.
  • A longer window includes more history and can span several different price regimes. A shorter window can change slope sharply when one observation enters or leaves.
  • A Gaussian Channel smooths a series through a filter. This channel instead fits one straight line to a chosen window; its residual width is not filtered True Range.

Fit the line, then measure residuals from that same line

Let x run from 0 at the oldest bar to N−1 at the newest, with prices y. Fit yhat = a + bx by minimizing the sum of squared residuals. Every residual in one window must use that window's a and b. Subtracting each bar's separately calculated rolling endpoint produces a different residual series.

  • This example uses equal observation weights, raw prices and symmetric bands. A log-price fit, asymmetric multipliers or a maximum-deviation envelope changes the definition.
  • The regression residual standard deviation described by NIST uses sqrt(SSE / (N−2)) for a straight line with two estimated parameters. It differs from the RMS convention here; require N > 2 for that divisor.
  • The standard deviation of raw prices around their mean is also different: it includes the fitted trend. A perfectly straight rising sequence has zero residual width even though its raw prices vary.
  • A multiplier of 2 does not by itself establish a 95% prediction interval. A descriptive parallel band supplies neither a verified price distribution nor a forecast-coverage guarantee.
QuantityFormulaMeaning
Slope bΣ[(x − mean(x))(y − mean(y))] / Σ[(x − mean(x))²]Price change per bar in the fitted line.
Intercept amean(y) − b × mean(x)Fitted price at the oldest observation, x = 0.
Residual ey − (a + bx)Signed vertical distance from this window's line.
SSEΣe²Sum of squared residuals across all N observations.
RMS width d used heresqrt(SSE / N)A descriptive residual scale, in price units.
Upper and lowera + bx + kd; a + bx − kdParallel boundaries with half-width kd.

Reproduce a five-bar fit and its channel width

Use hypothetical closes A=100, B=102, C=101, D=105 and E=107. Set N=5 and k=2. The means are x=2 and y=103. The slope numerator is 17 and its denominator is 10, so b=1.7 and a=99.6. These small inputs are an arithmetic fixture, not market observations or a backtest.

  • SSE = 0.16 + 0.49 + 4.00 + 0.09 + 0.36 = 5.10. Thus d = sqrt(5.10 / 5) = 1.00995049 and kd = 2.01990099.
  • At E, the lower boundary is 104.38009901 and the upper is 108.41990099. Close 107 is inside. The full channel width is 4.03980198 at every x in this fitted segment.
  • Changing only the divisor to N−2 gives sqrt(5.10 / 3) = 1.30384048. Its upper boundary at E would be 109.00768096. The same length and multiplier can therefore produce visibly different bands.
  • Keep full precision in calculations and round only the displayed result. A boundary comparison near equality can change if rounded labels are used as inputs.
Bar / xClose yFit a + bxResidual ee²
A / 010099.60.40.16
B / 1102101.30.70.49
C / 2101103.0−2.04.00
D / 3105104.70.30.09
E / 4107106.40.60.36

Watch the window roll when the next close is 112

Now add F=112 and remove A to keep N=5. Reset local x to 0..4 for B..F and refit. The new line is 100.2 + 2.6x, with residuals 1.8, −1.8, −0.4, −1.0 and 1.4. SSE becomes 9.6, so d = sqrt(9.6 / 5) = 1.38564065. Both the slope and band width have changed.

  • The old projection uses only A..E and is available before F closes. Comparing F with that threshold is a different rule from comparing F with a channel that already includes F.
  • If the latest line is redrawn over B..F, E now appears against a center of 108 even though its endpoint center was 106.4 at its own close. Reusing that new line to label an old signal introduces information that was unavailable at E.
  • Projecting a line one bar ahead is a mathematical extension, not evidence that price should follow it. In this fixture, 112 exceeds the old projected band; no subsequent price or trade outcome is assumed.
MeasurementFit using A..EFit using B..F
Slope per bar1.72.6
Residual RMS1.009950491.38564065
Fitted value at the same historical bar E106.4 at old x=4108.0 at new x=3
Center at F108.1 at old x=5, extrapolated110.6 at new x=4, fitted
Upper boundary at F110.11990099, old fit extended113.37128129, current fit
Is F close 112 above that boundary?YesNo

Separate historical redraws from an open-bar signal

There are two separate timing questions: whether the display replaces earlier fitted values, and whether the current condition can change before the candle closes. TradingView documents that live high, low and close values can change during an open bar. Waiting for the close settles that bar's inputs; it does not preserve a historical line segment that the script later redraws.

  • Define an outside state separately from a first-cross event. Repeated closes outside can produce repeated true states; a first-cross rule needs an explicit prior-state test.
  • Keep signal markers at their evaluation bars and check the saved threshold alongside them. A later redraw should not move or retrospectively create those markers.
  • Least squares is sensitive to outliers. A large incoming close can pull the center and widen the bands at once, as F does here. Close confirmation does not prevent the next bar from reversing.
DesignWhat the reader seesWhat to retain for verification
Latest-window drawingOne straight segment spanning the most recent N bars, replaced as the fit changes.The window end time and its a, b and d; do not treat today's segment as yesterday's signal history.
Rolling endpoint seriesOne current fitted endpoint per bar; connected endpoints need not form a straight line.Each bar's confirmed center and bands, calculated from data available through that bar.
Intrabar comparisonPrice and a channel including the current bar can both move.Whether the condition was provisional or evaluated on a completed close.
Previous-window projectionA threshold formed from the preceding completed window and extended one bar.The old slope and width; a prior endpoint alone is not the projected threshold.

Turn the calculation into a script acceptance checklist

Use Pineify's Pine Script AI Coding Agent to draft an implementation from a stated calculation contract. Provide the fixture above and require matching intermediate values before adding trading rules. A compiling script still needs numerical and chart-behavior checks.

  • Specify close as the source, a fixed chart timeframe, equal weights, N ≥ 3 and k ≥ 0. Require N valid observations; return no channel when the window is incomplete or contains missing values.
  • Request the fitted center, slope, SSE and RMS for each completed bar. Require every residual in a window to use the same fitted coefficients and divisor N.
  • Choose the display explicitly: latest-window drawing, saved endpoint series, or both with distinct labels. For a flat-price fixture, require zero slope and zero width without division by zero.
  • Choose either the current-window upper boundary or the prior-window one-bar projection for the alert. Require a strict greater-than comparison on a completed close; equality is not an upside break.
  • Check A..E and B..F against the numbers above, then inspect the calculation one bar at a time on the chart. If a first-cross alert is required, also test a second consecutive outside close.
  • Define entry timing, exits, position size, commissions and slippage separately before evaluating a strategy. The channel alone supplies none of those rules.
Where Pineify fits

Pine Script AI Coding Agent

Draft a regression channel from explicit window, residual-width and confirmation rules. Use the five-bar fixture to review the generated calculations before adding strategy orders or costs.

Draft a regression channel

Frequently asked questions

Educational calculation example, not investment advice. The numbers are hypothetical and no trading performance has been tested. Channel boundaries, projections and confirmed breaks do not guarantee future price behavior.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.