ta.linreg in MQL5: least-squares line endpoint with offset

Short answer

MQL5 has no function for it. Fit a least-squares line over the last length values and return intercept + slope * (len - 1 - offset); with offset 0 that is the LSMA. It takes five running sums and two divisions per bar.

ta.linreg(source, length, offset) fits a straight line by least squares to the last length values and returns the line's value offset bars back from its newest point. With offset = 0 that is the endpoint, which is what traders call the least squares moving average (LSMA). MQL5 has no function for it: the regression channel is a chart object, not an indicator, and iMA has no regression mode. The equivalent is five running sums and two divisions per bar.

What ta.linreg computes

Number the window's bars x = 0 for the oldest and x = length - 1 for the current bar, with y the source value at each. The ordinary least-squares fit gives:

slope     = (n * sum(x*y) - sum(x) * sum(y)) / (n * sum(x*x) - sum(x)^2)
intercept = (sum(y) - slope * sum(x)) / n
linreg    = intercept + slope * (length - 1 - offset)

So offset = 0 evaluates the line on the current bar, offset = 1 one bar earlier, and a negative offset extrapolates forward. The result is na until length bars exist; length must be at least 2 or the denominator is zero. The fit is redone from scratch on every bar: nothing carries over, so history depth does not change the values, and the realtime bar moves with each tick because its y is the current close. Because x is just a bar count, sum(x) and sum(x*x) are constants for a fixed length; only the sums involving y change per bar.

The MQL5 equivalent

//@version=6
indicator("LSMA", overlay = true)
len    = input.int(25, "Length")
offset = input.int(0, "Offset")
plot(ta.linreg(close, len, offset), "LSMA")

A complete MQL5 indicator. The arrays are oldest-first, so the bar with x = 0 is close[i - (InpLength - 1)] and the current bar is close[i]:

//+------------------------------------------------------------------+
//| ta.linreg(source, length, offset): value of the least-squares    |
//| line fitted to the last `length` values, read `offset` bars back |
//| from its endpoint                                                |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "LSMA (ta.linreg)"

input int InpLength = 25;   // length
input int InpOffset = 0;    // offset

double LinregBuffer[];

int OnInit()
{
   SetIndexBuffer(0, LinregBuffer, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength - 1);
   return InpLength >= 2 ? INIT_SUCCEEDED : INIT_PARAMETERS_INCORRECT;
}

int OnCalculate(const int rates_total, const int prev_calculated,
                const datetime &time[], const double &open[],
                const double &high[], const double &low[],
                const double &close[], const long &tick_volume[],
                const long &volume[], const int &spread[])
{
   const double n = InpLength;
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i < InpLength - 1)
        {
         LinregBuffer[i] = EMPTY_VALUE;
         continue;
        }
      // x = 0 for the oldest bar of the window, length - 1 for the current bar
      double sx = 0.0, sy = 0.0, sxy = 0.0, sxx = 0.0;
      for(int x = 0; x < InpLength; x++)
        {
         const double y = close[i - (InpLength - 1 - x)];
         sx += x; sy += y; sxy += x * y; sxx += (double)x * x;
        }
      const double slope     = (n * sxy - sx * sy) / (n * sxx - sx * sx);
      const double intercept = (sy - slope * sx) / n;
      LinregBuffer[i] = intercept + slope * (n - 1 - InpOffset);
     }
   return rates_total;
}

If you need the slope itself (for a trend-direction filter, or to reproduce a Pine script that uses ta.linreg(src, len, 0) - ta.linreg(src, len, 1)), expose it from the same loop; that difference is exactly slope, so one fit answers both.

Where the two differ

TopicPine ScriptMQL5
Native supportta.linregNone; the regression channel object does not expose values to code
x directionOldest bar is x = 0Same if you index close[i - (len - 1 - x)]; counting from the current bar works too if the offset sign is adjusted
Offsetoffset bars back from the current bar; negative projects forwardSame formula: intercept + slope * (len - 1 - offset)
length < 2No line through one point; the Stratlate runtime answers naDivision by zero; reject in OnInit
First barsna for length - 1 barsEMPTY_VALUE written by you
PrecisionFloatsDoubles; cast x * x to double for large lengths so the int product does not overflow

What the Stratlate converter emits

The engine maps ta.linreg to pine_linreg(close, __pineBar, (int)(len), (int)(offset)), with the offset defaulting to 0 when a script omits it. The runtime fits the same least-squares line from five sums, counting x from the current bar backwards and returning intercept + slope * offset, which is algebraically the same endpoint formula with the axis reversed; it returns na for length < 2, before length bars exist, or when any value in the window is na. A computed source without a named array is recorded into a per-call-site window array and fitted through pine_linreg_step. The call is reported as exact, and the script above converts CLEAN. Compile and backtest the result and compare recent bars against TradingView.

Pitfalls

  • Wrong offset sign. If x counts from the current bar, the line's value offset bars back is intercept + slope * offset; mixing that with the oldest-first formula moves the whole line by length - 1 bars.
  • Plotting the intercept. With oldest-first x, the intercept is the line's value at the oldest bar of the window, not the current one. The symptom is a line lagging by exactly length - 1 bars.
  • Dividing by zero for length 1. n * sxx - sx * sx is 0. Reject it.
  • Integer sums. Accumulating sx and sxx in ints is fine for small lengths; keep them doubles anyway so the division is not truncated.
  • Treating the LSMA as an average that needs warm-up beyond the window. It does not; a difference from TradingView that does not fade with more bars is a formula or data problem.

FAQ

Is ta.linreg the same as the LSMA?

Yes, with offset 0. The least squares moving average is the endpoint of the regression line fitted over the last length bars. Other offsets read earlier points on the same line, and negative offsets project it forward.

Can I use the Linear Regression Channel object in MQL5 to get the value?

Not conveniently. The object is drawn by the terminal and its fitted values are not exposed through a function; you would have to read anchor points and recompute. The loop above is shorter and runs inside the indicator.

How do I get the slope of the regression in Pine and in MQL5?

In Pine, ta.linreg(src, len, 0) - ta.linreg(src, len, 1) is the slope per bar. In MQL5 the slope is already computed in the loop, so store it in a second buffer instead of calling the fit twice.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related