Indicator · Pine Script v6 · On the chart

Recursive Least Squares Adaptive Filter (RLS)

by mihakralj

This indicator applies a recursive least squares adaptive FIR filter to a chosen price source and plots the resulting smoothed series on the price chart.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code96
Settings3inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

96 lines of Pine Script v6 from lib/filters/rls/rls.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

rls.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Recursive Least Squares Adaptive Filter (RLS)", "RLS", overlay=true)

//@function Applies RLS adaptive FIR filter to input series
//@param src Input series to filter
//@param order Number of FIR filter taps (adaptive weights)
//@param lambda Forgetting factor (0 < lambda <= 1). Controls memory horizon.
//@returns Adaptively filtered series
//@optimized Uses inverse correlation matrix for O(order²) convergence per bar,
//           faster convergence than LMS at higher computational cost
rls(series float src, simple int order, simple float lambda) =>
    if order < 2
        runtime.error("Filter order must be >= 2")
    if lambda <= 0.0 or lambda > 1.0
        runtime.error("Forgetting factor lambda must be in (0, 1]")

    // weight vector w[order]
    var array<float> w = array.new_float(order, 0.0)

    // inverse correlation matrix P[order x order], stored row-major
    // initialized to delta * I (large diagonal = high initial uncertainty)
    var float delta = 100.0
    var array<float> P = array.new_float(order * order, 0.0)
    var bool initialized = false
    if not initialized
        for i = 0 to order - 1
            array.set(P, i * order + i, delta)
        initialized := true

    // build input vector x = [src[1], src[2], ..., src[order]]
    array<float> x = array.new_float(order, 0.0)
    for i = 0 to order - 1
        array.set(x, i, nz(src[i + 1], 0.0))

    // --- Step 1: prediction ---
    // y = w^T * x
    float y = 0.0
    for i = 0 to order - 1
        y += array.get(w, i) * array.get(x, i)

    // --- Step 2: a priori error ---
    float e = nz(src, 0.0) - y

    // --- Step 3: gain vector k = P*x / (lambda + x^T*P*x) ---
    // compute Px = P * x
    array<float> Px = array.new_float(order, 0.0)
    for i = 0 to order - 1
        float row_sum = 0.0
        for j = 0 to order - 1
            row_sum += array.get(P, i * order + j) * array.get(x, j)
        array.set(Px, i, row_sum)

    // compute denom = lambda + x^T * Px
    float denom = lambda
    for i = 0 to order - 1
        denom += array.get(x, i) * array.get(Px, i)

    // k = Px / denom
    array<float> k = array.new_float(order, 0.0)
    float inv_denom = denom > 1e-30 ? 1.0 / denom : 0.0
    for i = 0 to order - 1
        array.set(k, i, array.get(Px, i) * inv_denom)

    // --- Step 4: weight update ---
    // w = w + k * e
    for i = 0 to order - 1
        array.set(w, i, array.get(w, i) + array.get(k, i) * e)

    // --- Step 5: P update ---
    // P = (1/lambda) * (P - k * x^T * P)
    // equivalently: P = (1/lambda) * (P - k * Px^T)
    // since Px = P*x, then k*x^T*P = k*(Px)^T  (row-by-row outer product)
    float inv_lambda = 1.0 / lambda
    for i = 0 to order - 1
        float ki = array.get(k, i)
        for j = 0 to order - 1
            float old_pij = array.get(P, i * order + j)
            float new_pij = inv_lambda * (old_pij - ki * array.get(Px, j))
            array.set(P, i * order + j, new_pij)

    y

// ---------- Main loop ----------

// Inputs
i_order  = input.int(16, "Filter Order (taps)", minval=2, maxval=64)
i_lambda = input.float(0.99, "Forgetting Factor (λ)", minval=0.9, maxval=1.0, step=0.005)
i_source = input.source(close, "Source")

// Calculation
rls_val = rls(i_source, i_order, i_lambda)

// Plot
plot(rls_val, "RLS", color=color.orange, linewidth=2)

Overview

Each bar it predicts from past source values, updates a weight vector from the prediction error, and refreshes an inverse correlation matrix. Filter order sets the number of taps, and the forgetting factor sets how quickly older samples lose influence. It does not generate entries, exits, or stop levels.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Filter Order (taps)int16i_order
Forgetting Factor (λ)float0.99i_lambda
Sourcesourceclosei_source
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

948 stars

The Adaptive Laguerre Filter calculates a smoothed, dynamically adjusted trendline plotted directly on the main price chart. It dynamically adjusts its damping factor (alpha) based on recent price range variations and median percentile calculations over a spec

Indicator v4 TrendMoving averages
Updated 10 days ago · GPL-3.0 GitHub repository of Adaptive Laguerre Filter
575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener
330 stars

This script plots three moving averages on the price chart: a fast EMA or SMA with 10 periods, a slow EMA or SMA with 20 periods, and a trend EMA or SMA with 100 periods. It signals trend changes by drawing a white cross when the fast moving average crosses ab

Indicator v4 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of 3 EMA/SMA + Cross [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

All Candlestick Patterns

by shunjizhan
292 stars

All Candlestick Patterns detects and highlights a wide range of bullish, bearish, and neutral candlestick patterns directly on the price chart. It features optional trend filtering using either a 50-period simple moving average or a combination of 50-period an

Indicator v4 Candlestick patternsTrend
Updated 3 years ago · None stated GitHub repository of All Candlestick Patterns

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers