Linear Regression Channel
At every bar, the least-squares straight line through the last N values of the price, evaluated at that bar, with lines at plus and minus k standard deviations of the residuals around the fit; the deviation is the population one, divided by N.
It measures where the recent trend line stands and how tightly price has kept to it. It is drawn as a curve of each bar's own fit, unlike the regression channel drawing, which is one straight fit over a range chosen by hand.
01The study, live
Computed by Bentrix’s own code over the same synthetic bars on every page — an illustration of how the study behaves, not a market.
What this figure shows
The figure is computed over 300 sample bars. LR Channel has no value on the first 99 — the bars it needs before it can answer — and its first value stands on bar 100. Counting the conditions the study declares on these bars: price crosses above the line twice; price crosses below the line once; price crosses above the upper band once; price crosses below the lower band 13 times; price comes back inside the bands 15 times. Press a condition under the figure to see each place marked. As states rather than moments: price is above the line on 72 bars; price is below the line on 129 bars.
02Its parts, named
03What you see
LR Channel is three curves drawn over the candles. At every bar a straight line is fitted by least squares through the last closes, and the study draws where that line ends — at the bar itself — with a line a number of standard deviations above it and one below. The next bar gets its own fit. So the middle curve is the end point of a different straight line on every bar, and the three curves bend with the market; a value, once its bar has closed, does not change.
It is not the regression channel drawing, which is one straight fit over a range chosen by hand, with straight parallel edges.
04Where it comes from
A regression channel is a least-squares line with parallel lines a set number of standard deviations either side. Gilbert Raff popularised one variant in the early 1990s (his channel uses the furthest excursion instead of the deviation).
05The formula
P̂ᵢ = a + b xᵢ, a, b chosen so that Σ[i=1..N] (Pᵢ − P̂ᵢ)² is smallest
σₜ = √(1/N Σ[i=1..N] (Pᵢ − P̂ᵢ)²)
Middleₜ = P̂_N, Upperₜ = P̂_N + k σₜ, Lowerₜ = P̂_N − k σₜ
On each bar, the line minimises over the last bars. The middle value of that bar is the line's value at the bar itself, and the upper and lower values are that value , where is the standard deviation of the window's misses (divided by ).
06A worked example
Take the last five closes of the sample, 22, 24, 25, 24, 26, and a period of 5. Number the bars 0 to 4.
The least-squares line through them has a slope of 0.80 per bar and passes through 22.60 at bar 0: line = 22.60 + 0.80 × bar.
At the newest bar the line reads 22.60 + 0.80 × 4 = 25.80. The closes miss the line by -0.60, 0.60, 0.80, -1.00, 0.20; the standard deviation of those misses is 0.69.
With 2 deviations the channel at the newest bar runs from 24.41 to 27.19.
07Built in Assay
The same study written in Assay, Bentrix’s script language, and drawn by Bentrix itself as the script’s graph: each block is one step of the formula. On the ladder the steps stand in the script’s order, one a row; on the board each wire carries a value from the block that gives it to the block that reads it, left to right. The script computes exactly what the study computes — Bentrix checks the two against each other, candle by candle.
//@version=6 indicator("Linear Regression Channel", overlay = true) length = input.int(100, "Length") deviations = input.float(2.0, "Deviations") // x counts the window's bars from the oldest (0) to the newest (length - 1). sumX = length * (length - 1) / 2 sumXX = (length - 1) * length * (2 * length - 1) / 6 float sumY = 0.0 float sumXY = 0.0 for k = 0 to length - 1 y = close[length - 1 - k] sumY += y sumXY += k * y // The least-squares straight line through the window's closes. slope = (length * sumXY - sumX * sumY) / (length * sumXX - sumX * sumX) intercept = (sumY - slope * sumX) / length // How far the closes sit from that line: the standard deviation of the residuals. float squares = 0.0 for k = 0 to length - 1 r = close[length - 1 - k] - (intercept + slope * k) squares += r * r spread = math.sqrt(squares / length) fit = bar_index >= length - 1 ? intercept + slope * (length - 1) : na plot(fit, "Fit") plot(fit + deviations * spread, "Upper") plot(fit - deviations * spread, "Lower")
Paste it into the Assay IDE to put it on a chart, or to change it. Looking at the graph is free in every package; editing it as blocks is Plus.
08Readings — what traders look for
The line's slope is read as the window's average rate of change; price at a channel edge is read as far from the fitted line relative to the window's scatter.
How a touch of the edge fails. An edge is where a close two deviations from the window's fitted trend would be. A bar that closes far from the line raises the deviation of its own window, so the edge moves away from the very close that approaches it; and in a steady trend price runs along one edge for many bars.
How the slope fails. The slope describes the window's net drift; a window that contains a reversal has a slope near zero and a very wide channel.
09In different markets and timeframes
The channel is narrow where the last closes lay close to a straight line — a steady trend or a tight range — and wide where they did not: at a reversal inside the window, or in disorderly trading. In a steady trend the middle curve runs through the bars and price stays near one edge; at a turn the fit still carries the old direction, the middle curve overshoots for a few bars and the channel widens. With the default 100 bars it describes about a hundred minutes on M1 and five months on D1.
10With other studies
Its middle curve is the Linear Regression study of the same period, and the Linear Regression Slope is the slope of the same fits. Read beside Bollinger Bands of the same period: those measure the closes' spread around their average, these around their fitted trend, so in a steady trend this channel is the narrower of the two.
11What it does not tell you
A straight line fitted to the past is a description of the past window; extending it is an assumption.
12Inputs and defaults
- 1Deviations — 2How many standard deviations of the misses each edge stands from the line.
- 2Period — 100How many bars each bar's line is fitted to. Longer: the curves are smoother and further behind price.
- 3Deviations below — 2The deviations of the lower line, where they differ from those of the upper one. Left alone, both use the same number.
- 4Applied price — CloseAny of the seven prices, and several at once, each its own line with its own look.
- 5Timeframe — ChartThe chart's own by default; any higher one, read on the last closed candle. A finer one is never offered.
- 6Wait for the candle to close — OnThe value of a higher timeframe is taken only from a candle that has finished.
What each input changes
- Deviations belowThe deviations of the lower line alone. Left as it is, both lines stand the same distance from the fitted line.
- In use100 bars and 2 deviations by default.
13Limits and common misreadings
Each bar has its own line. The curve is not one straight channel; joining two of its points does not give the line either bar was fitted with.
A straight line is an assumption. Markets curve; the wider the channel, the worse the fit.
14Conditions an alert or a strategy can watch
an event happens on one bar a state holds on every bar while it lasts
These are the conditions the study itself declares — the same rules the alert editor and the strategy engine read, and the ones the figure's chips show.
15Practise it in the laboratory
Put LR Channel 100 and the regression channel drawing over the same 100 bars. The drawing's edges are straight; the study's curve meets the drawing's line only at the last bar, where both are the end of the same fit.
Open the laboratory17In Bentrix
- From the menu: a chart's Indicators button › Trend & channels › LR Channel, or type LR Channel in its search.
- Its settings: the settings card opens when it is added; its legend's name opens it again.
18From an agent or a program
Two tools reach it. study_values computes it over a workbench’s candles up to the clock — no chart needed — and study_attach puts it on a chart, where it is drawn and saved with the chart ({"chart": "<chart uri>", "kind": "linreg_channel"}).
The study, as a chart files it
This is a new LR Channel’s entry — its kind, its calculation, the price it reads and its settings. Change a setting here to read it with other inputs.
{
"applied": "close",
"convention": "custom",
"kind": "linreg_channel",
"settings": {
"dev": 2.0,
"period": 100,
"shape": "period_dev"
}
}An agent
An agent calls the MCP tool with it:
{
"name": "study_values",
"arguments": {
"bench": "bentrix://lab/\u2026/bench/\u2026",
"symbol": "EURUSD",
"timeframe": "H1",
"limit": 5,
"study": {
"applied": "close",
"convention": "custom",
"kind": "linreg_channel",
"settings": {
"dev": 2.0,
"period": 100,
"shape": "period_dev"
}
}
}
}A program
A program does the same in its language — bench and market as in the built-in indicators guide:
Python
values = client.study.values(bench, market, "H1", {"applied": "close", "convention": "custom", "kind": "linreg_channel", "settings": {"dev": 2.0, "period": 100, "shape": "period_dev"}}, limit=5)
print("times:", values["times"])
for line in values["lines"]:
print("line:", line["line"])
print(" newest values:", line["values"])JavaScript
const values = await client.study.values({ bench, symbol: market, timeframe: "H1", study: { "applied": "close", "convention": "custom", "kind": "linreg_channel", "settings": { "dev": 2.0, "period": 100, "shape": "period_dev" } }, limit: 5 });
console.log("times:", values.times);
for (const line of values.lines) {
console.log("line:", line.line);
console.log(" newest values:", line.values);
}C#
var values = await client.Study.Values(bench, market, "H1", new Dictionary<string, object?> { ["applied"] = "close", ["convention"] = "custom", ["kind"] = "linreg_channel", ["settings"] = new Dictionary<string, object?> { ["dev"] = 2.0, ["period"] = 100, ["shape"] = "period_dev" } }, limit: 5);
Console.WriteLine($"times: {values!["times"]!}");
foreach (var line in values!["lines"]!.AsArray())
{
Console.WriteLine($"line: {line!["line"]!}");
Console.WriteLine($" newest values: {line!["values"]!}");
}Go
values := must(client.Study.Values(ctx, mcp.StudyValuesArgs{Bench: bench, Symbol: market, Timeframe: "H1", Study: map[string]any{"applied": "close", "convention": "custom", "kind": "linreg_channel", "settings": map[string]any{"dev": 2.0, "period": 100, "shape": "period_dev"}}, Limit: mcp.Ptr[int64](5)}))
fmt.Println("times:", at(values, "times"))
for _, line := range at(values, "lines").([]any) {
fmt.Println("line:", at(line, "line"))
fmt.Println(" newest values:", at(line, "values"))
}Java
Object values = client.study.values(new Bentrix.StudyApi.ValuesArgs(bench, market, "H1", obj("applied", "close", "convention", "custom", "kind", "linreg_channel", "settings", obj("dev", 2.0, "period", 100, "shape", "period_dev"))).limit(5L));
System.out.println("times:" + " " + at(values, "times"));
for (Object line : (List<Object>) at(values, "lines")) {
System.out.println("line:" + " " + at(line, "line"));
System.out.println(" newest values:" + " " + at(line, "values"));
}C++
auto values = client.study.values_(StudyApi::ValuesArgs(bench, market, "H1", Json::Object{{"applied", "close"}, {"convention", "custom"}, {"kind", "linreg_channel"}, {"settings", Json::Object{{"dev", 2.0}, {"period", 100}, {"shape", "period_dev"}}}}).limit(5));
std::cout << "times:" << " " << values["times"].dump() << std::endl;
for (const Json &line : values["lines"].arr()) {
std::cout << "line:" << " " << line["line"].dump() << std::endl;
std::cout << " newest values:" << " " << line["values"].dump() << std::endl;
}Julia
values = client.study.values(bench, market, "H1", Dict{String,Any}("applied" => "close", "convention" => "custom", "kind" => "linreg_channel", "settings" => Dict{String,Any}("dev" => 2.0, "period" => 100, "shape" => "period_dev")); limit = 5)
println("times:", " ", values["times"])
for line in values["lines"]
println("line:", " ", line["line"])
println(" newest values:", " ", line["values"])
endR
values <- client$study$values(bench, market, "H1", list(applied = "close", convention = "custom", kind = "linreg_channel", settings = list(dev = 2.0, period = 100, shape = "period_dev")), limit = 5)
cat("times:", format(values$times), "\n")
for (line in values$lines) {
cat("line:", format(line$line), "\n")
cat(" newest values:", format(line$values), "\n")
}Rust
let values = client.study().values(mcp::StudyValuesArgs::new(bench.clone(), market.clone(), "H1", serde_json::json!({"applied": "close", "convention": "custom", "kind": "linreg_channel", "settings": {"dev": 2.0, "period": 100, "shape": "period_dev"}})).limit(5))?;
println!("times: {}", values["times"]);
for line in values["lines"].as_array().into_iter().flatten() {
println!("line: {}", line["line"]);
println!(" newest values: {}", line["values"]);
}Reading the answer
times— the candles’ open times, in milliseconds since 1970 (UTC), oldest first.lines— one entry per line, in this order, each with itslinename and itsvalues;values[i]belongs to the candle attimes[i].- The last value is the candle at the clock’s, which may still be forming: it changes until that candle closes, as on the chart. Nothing after the clock is ever computed.
nullis a candle with no value yet — the warm-up, about 1 × the period at the start of the history.
line | What it is |
|---|---|
Main | line |
BandEdge | band |
BandEdge | band |
In a strategy
Filed under a key of your choice in a strategy document’s studies — here linreg_channel: {"linreg_channel": {"applied": "close", "convention": "custom", "kind": "linreg_channel", "settings": {"dev": 2.0, "period": 100, "shape": "period_dev"}}} — its rules can name:
| Write | What it is |
|---|---|
linreg_channel | its main line, as a value in a compare |
{"cond": "linreg_channel:price.cross_up"} | a condition it declares itself |
{"cond": "linreg_channel:price.cross_down"} | a condition it declares itself |
{"cond": "linreg_channel:price.above"} | a condition it declares itself |
{"cond": "linreg_channel:price.below"} | a condition it declares itself |
{"cond": "linreg_channel:band.cross_above_upper"} | a condition it declares itself |
{"cond": "linreg_channel:band.cross_below_lower"} | a condition it declares itself |
{"cond": "linreg_channel:band.back_inside"} | a condition it declares itself |
Its lines named band_edge are more than one line of that name, so a strategy reaches them through the conditions above rather than by name.
19Sources
- Colby, Robert W. The Encyclopedia of Technical Market Indicators, 2nd ed. McGraw-Hill, 2003, "Linear Regression".
Bentrix 0.1.382Every number, name and default on these pages is read from the application itself.What is comingWhat changed