Bentrix Docs
HomePricingDashboard

Linear Regression

Statisticoverlayone linein every package

The endpoint value of a least-squares straight line fitted through the last N values.

It measures the level the recent trend line has reached, which lags less than an SMA because a fitted line follows a ramp exactly where an average trails it. Read as a low-lag centre; the same fit's slope and angle are separate indicators here.

01The study, live

Live figureScroll to zoom, drag the bars to pan.
bar —O — H — L — C —Linear Regression —first value at —
Show where:

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. Linear Regression has no value on the first 13 — the bars it needs before it can answer — and its first value stands on bar 14. Of the 287 bars that have a value, the close is above the line on 134 and below it on 153. Counting the conditions the study declares on these bars: price crosses above the line 32 times; price crosses below the line 33 times. Press a condition under the figure to see each place marked. As states rather than moments: price is above the line on 134 bars; price is below the line on 153 bars.

02Its parts, named

Warm-upno value on the first 13 bars: thestudy needs them before it cananswerThe linethe study's value, one for each barThe bars it readseach bar's close, unless you chooseanother price
Computed by Bentrix’s own code over the sample bars. It is drawn on once, as you reach the figure.

03What you see

At each bar a straight line is fitted to the last N prices, and the study plots the line's end value — where the fitted line stands on the newest bar.

04Where it comes from

Least-squares fitting goes back to Legendre (1805) and Gauss. As a moving line on a chart — the end point of a regression refitted on every bar — it is a staple of TA-Lib and of statistical trading texts.

05The formula

Least squares over the window, x=0…N−1:

b=N∑xP−∑x∑PN∑x2−(∑x)2,a=∑P−b∑xN
Pthe applied price of each bar in the window — the close by default
xeach bar's number in the window, 0 for the oldest
Nthe period, in bars
a, bthe fitted line's value at the oldest bar and its change per bar

The Linear Regression value is a+b(N−1).

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.

The value plotted on the newest bar is the line's end point: 22.60 + 0.80 × 4 = 25.80.

The simple average of the same five closes is 24.20 — the line's middle. The regression value is above it because the closes have been rising: the end of a rising line is higher than its centre. That is the whole difference between this study and an SMA.

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.

THE SCRIPT’S GRAPH
//@version=6
indicator("Linear Regression", overlay = true)
length = input.int(14, "Length")
// 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
// ...read at the newest bar.
linreg = bar_index >= length - 1 ? intercept + slope * (length - 1) : na
plot(linreg, "Linear regression")

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 linear regression line is read as a smooth, low-lag average: price against it, and its direction.

How its closeness to price fails. The line hugs price more closely than an average of the same period and turns sooner. It also overshoots at turns: the end of a fitted line keeps extending the old slope for some bars after price has turned.

09In different markets and timeframes

The regression line follows price closely in steady trends and overshoots at turns. It is refitted on every bar, so each point is the end of a different line.

In a steady trend it runs through the middle of the bars and stays closer to price than a moving average of the same length; in a range it weaves through it with small overshoots at each end. At a sharp reversal it carries the old direction past the turn for a few bars. With 14 bars it describes the last quarter of an hour on M1 and the last three weeks on D1. Gaps pull the fitted line at once, since every bar in the window has equal weight in the fit.

10With other studies

Read beside its own slope study and the regression channel.

11What it does not tell you

!

The fitted line describes the last N prices as if they lay on a straight line. It says nothing about whether the next price continues that line, and where prices curved or reversed inside the window the fit is poor and its end point with it.

12Inputs and defaults

Linear Regression (14, Close)settings card
1Period14
2Applied priceClose
3TimeframeChart
4Wait for the candle to closeOn
  1. 1
    Period — 14How many bars the line is fitted to. Longer: smoother; but unlike an average, the end point of a long fit can still swing when the window's shape changes.
  2. 2
    Applied price — CloseAny of the seven prices, and several at once, each its own line with its own look.
  3. 3
    Timeframe — ChartThe chart's own by default; any higher one, read on the last closed candle. A finer one is never offered.
  4. 4
    Wait for the candle to close — OnThe value of a higher timeframe is taken only from a candle that has finished.

What each input changes

  • Applied priceWhich price of the bar is fitted.
  • In use14 by default; 20 to 100 for longer fits.

13Limits and common misreadings

Each point is a different line's end. The curve on the chart is not one fitted line; no single window's fit looks like it.

Overshoot at reversals. The fitted line carries the old direction past a turn for a few bars, so the study passes beyond price before it comes back.

14Conditions an alert or a strategy can watch

price crosses above the line eventprice crosses below the line eventprice is above the line stateprice is below the line state

Event: the bar it happens on an event happens on one barState: every bar while it holds 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 Linear Regression 14 and SMA 14 on one chart and replay a sharp reversal; note which line passes beyond price at the turn.

Open the laboratory

17On pages of their own

18In Bentrix

  • From the menu: a chart's Indicators button › Statistic › Linear Regression, or type Linear Regression in its search.
  • Its settings: the settings card opens when it is added; its legend's name opens it again.

19From 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"}).

The study, as a chart files it

This is a new Linear Regression’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": "talib",
  "kind": "linreg",
  "settings": {
    "period": 14,
    "shape": "period"
  }
}

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": "talib",
      "kind": "linreg",
      "settings": {
        "period": 14,
        "shape": "period"
      }
    }
  }
}

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": "talib", "kind": "linreg", "settings": {"period": 14, "shape": "period"}}, limit=5)
print("times:", values["times"])
for line in values["lines"]:
    print("line:", line["line"])
    print("  newest values:", line["values"])

JSJavaScript

const values = await client.study.values({ bench, symbol: market, timeframe: "H1", study: { "applied": "close", "convention": "talib", "kind": "linreg", "settings": { "period": 14, "shape": "period" } }, 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#C#

var values = await client.Study.Values(bench, market, "H1", new Dictionary<string, object?> { ["applied"] = "close", ["convention"] = "talib", ["kind"] = "linreg", ["settings"] = new Dictionary<string, object?> { ["period"] = 14, ["shape"] = "period" } }, 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"]!}");
}

GOGo

values := must(client.Study.Values(ctx, mcp.StudyValuesArgs{Bench: bench, Symbol: market, Timeframe: "H1", Study: map[string]any{"applied": "close", "convention": "talib", "kind": "linreg", "settings": map[string]any{"period": 14, "shape": "period"}}, 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", "talib", "kind", "linreg", "settings", obj("period", 14, "shape", "period"))).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++C++

auto values = client.study.values_(StudyApi::ValuesArgs(bench, market, "H1", Json::Object{{"applied", "close"}, {"convention", "talib"}, {"kind", "linreg"}, {"settings", Json::Object{{"period", 14}, {"shape", "period"}}}}).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" => "talib", "kind" => "linreg", "settings" => Dict{String,Any}("period" => 14, "shape" => "period")); limit = 5)
println("times:", " ", values["times"])
for line in values["lines"]
    println("line:", " ", line["line"])
    println("  newest values:", " ", line["values"])
end

RR

values <- client$study$values(bench, market, "H1", list(applied = "close", convention = "talib", kind = "linreg", settings = list(period = 14, shape = "period")), 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")
}

RRust

let values = client.study().values(mcp::StudyValuesArgs::new(bench.clone(), market.clone(), "H1", serde_json::json!({"applied": "close", "convention": "talib", "kind": "linreg", "settings": {"period": 14, "shape": "period"}})).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 its line name and its values; values[i] belongs to the candle at times[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.
  • null is a candle with no value yet — the warm-up, about 1 × the period at the start of the history.
lineWhat it is
Mainline

In a strategy

Filed under a key of your choice in a strategy document’s studies — here linreg: {"linreg": {"applied": "close", "convention": "talib", "kind": "linreg", "settings": {"period": 14, "shape": "period"}}} — its rules can name:

WriteWhat it is
linregits main line, as a value in a compare
{"cond": "linreg:price.cross_up"}a condition it declares itself
{"cond": "linreg:price.cross_down"}a condition it declares itself
{"cond": "linreg:price.above"}a condition it declares itself
{"cond": "linreg:price.below"}a condition it declares itself

20Sources

  1. 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