Indicator · Pine Script v6 · On the chart

Kalman Flow

by vedkanani123· code credited to LyroRS

An overlay indicator that runs price through a Kalman filter and builds adaptive noise bands from the tracking error around the estimate.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code156
Settings12inputs
LicenceNone statedfile: MPL-2.0
Last update2 months ago23 Aug 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

156 lines of Pine Script v6 from indicator/olg_7_6_26/LyroRS/3.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

3.txt
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LyroRS

//@version=6
indicator("Kalman Flow | Lyro RS", overlay=true)

// ╔══════════════════════════════════════════════════╗
// ║                INPUT GROUPS                      ║
// ╚══════════════════════════════════════════════════╝
settings_g = '𝗦𝗘𝗧𝗧𝗜𝗡𝗚𝗦'
features_g = '𝗙𝗘𝗔𝗧𝗨𝗥𝗘𝗦'
color_g    = '𝗖𝗢𝗟𝗢𝗥'

// ╔══════════════════════════════════════════════════╗
// ║               CORE SETTINGS                      ║
// ╚══════════════════════════════════════════════════╝
src         = input.source(close, "𝗦𝗼𝘂𝗿𝗰𝗲", group=settings_g, tooltip="The price series fed into the Kalman filter. Close is the default and recommended source.")

sensitivity = input.float(4,
 "𝗦𝗲𝗻𝘀𝗶𝘁𝗶𝘃𝗶𝘁𝘆",
 step=0.5, minval=1, maxval=10,
 group=settings_g,
 tooltip="Controls how quickly the Kalman filter reacts to new price information. Higher values track price closely and flip faster, lower values produce a smoother line with fewer, more selective signals.")

mad_multp   = input.float(1.65, "+ 𝗠𝘂𝗹𝘁𝗶𝗽𝗹𝗶𝗲𝗿", step=0.1, minval=0.5, maxval=5, group=settings_g, tooltip="A multiplier applied to the tracking-error distance from the Kalman estimate to create the upper band. Price must close above it — with positive velocity — to flip bullish.")
mad_multn   = input.float(1, "- 𝗠𝘂𝗹𝘁𝗶𝗽𝗹𝗶𝗲𝗿", step=0.1, minval=0.5, maxval=5, group=settings_g, tooltip="A multiplier applied to the tracking-error distance from the Kalman estimate to create the lower band. Price must close below it — with negative velocity — to flip bearish.")

volLen      = input.int(50, "𝗡𝗼𝗶𝘀𝗲 𝗟𝗲𝗻𝗴𝘁𝗵", minval=5, maxval=500, group=settings_g, tooltip="Lookback used to measure how noisy price has been around the Kalman estimate. This tracking error is what scales the bands, so they automatically widen in choppy markets and tighten in clean trends.")

// ╔══════════════════════════════════════════════════╗
// ║                 FEATURES                         ║
// ╚══════════════════════════════════════════════════╝
showSignals = input.bool(true, "𝗦𝗵𝗼𝘄 𝗦𝗶𝗴𝗻𝗮𝗹𝘀", group=features_g, tooltip="Displays Long and Short labels on the chart whenever the trend engine flips direction.")
showBands   = input.bool(true, "𝗦𝗵𝗼𝘄 𝗕𝗮𝗻𝗱𝘀", group=features_g, tooltip="Displays the adaptive noise bands around the Kalman baseline. These are the levels price must break — with velocity agreement — to flip the trend.")
candleColor = input.bool(true, "𝗖𝗮𝗻𝗱𝗹𝗲 𝗖𝗼𝗹𝗼𝗿𝗶𝗻𝗴", group=features_g, tooltip="Colors the chart candles according to the current trend state.")

// ╔══════════════════════════════════════════════════╗
// ║                   COLOR                          ║
// ╚══════════════════════════════════════════════════╝
ColMode = input.string("Mystic", "Custom Color Palette", inline="drop", options=["Classic", "Mystic", "Accented", "Royal"], display=display.none, group=color_g, tooltip="Choose a predefined color scheme for indicator visualization.")

cpyn   = input.bool(true, "Use Custom Palette", tooltip="Enable manual selection of custom colors for trend signals.", group=color_g, display=display.none)
cp_UpC = input.color(#00ff00, "Custom Up", inline="Custom Palette", tooltip="Set a custom color for bullish signals.", group=color_g, display=display.none)
cp_DnC = input.color(#ff0000, "Custom Down", inline="Custom Palette", tooltip="Set a custom color for bearish signals.", group=color_g, display=display.none)

color UpC = na
color DnC = na

switch ColMode
    "Classic" =>
        UpC := #00E676
        DnC := #880E4F
    "Mystic" =>
        UpC := #30FDCF
        DnC := #E117B7
    "Accented" =>
        UpC := #9618F7
        DnC := #FF0078
    "Royal" =>
        UpC := #FFC107
        DnC := #673AB7

if cpyn
    UpC := cp_UpC
    DnC := cp_DnC

// ╔══════════════════════════════════════════════════╗
// ║          KALMAN FILTER [LEVEL + VELOCITY]        ║
// ╚══════════════════════════════════════════════════╝
// Two-state constant-velocity Kalman filter.
// State 1 = price level, State 2 = velocity (drift per bar).
// Only the process-to-measurement noise ratio matters for the
// filter gain, so behaviour is scale-independent across assets.

kf_q = math.pow(10, sensitivity / 2 - 6)   // process noise
kf_r = 1.0                                 // measurement noise

var float kf_level = na
var float kf_veloc = 0.0
var float p11 = 1.0
var float p12 = 0.0
var float p21 = 0.0
var float p22 = 1.0

if na(kf_level)
    kf_level := src
else
    // ── Predict ──
    predLevel = kf_level + kf_veloc
    predVeloc = kf_veloc
    p11p = p11 + p12 + p21 + p22 + kf_q
    p12p = p12 + p22
    p21p = p21 + p22
    p22p = p22 + kf_q
    // ── Update ──
    s  = p11p + kf_r
    k1 = p11p / s
    k2 = p21p / s
    innov = src - predLevel
    kf_level := predLevel + k1 * innov
    kf_veloc := predVeloc + k2 * innov
    p11 := (1 - k1) * p11p
    p12 := (1 - k1) * p12p
    p21 := p21p - k2 * p11p
    p22 := p22p - k2 * p12p

// ╔══════════════════════════════════════════════════╗
// ║                 TREND ENGINE                     ║
// ╚══════════════════════════════════════════════════╝
// Tracking error = average absolute distance between price and
// the Kalman estimate. Bands scale with it, so flips require a
// move that is large relative to recent noise — not a fixed size.
trackErr = ta.sma(math.abs(src - kf_level), volLen)
upperBand = kf_level + mad_multp * trackErr
lowerBand = kf_level - mad_multn * trackErr

// A flip requires BOTH:
//  1. A close beyond the opposite noise band (displacement)
//  2. Kalman velocity agreeing with the new direction (drift)
// Anything less holds the current state — built-in hysteresis.
var int trend = 0
if close > upperBand and kf_veloc > 0
    trend := 1
else if close < lowerBand and kf_veloc < 0
    trend := -1

flipUp   = trend == 1  and trend[1] != 1
flipDown = trend == -1 and trend[1] != -1

// ╔══════════════════════════════════════════════════╗
// ║                   VISUALS                        ║
// ╚══════════════════════════════════════════════════╝
trendCol = trend == 1 ? UpC : trend == -1 ? DnC : color.gray

// Baseline with glow
plot(kf_level, "Kalman Baseline [Glow]", color=color.new(trendCol, 80), linewidth=6, editable=false)
plot(kf_level, "Kalman Baseline", color=trendCol, linewidth=2)

// Adaptive noise bands
pUp = plot(showBands ? upperBand : na, "Upper Band", color=color.new(trendCol, 70), linewidth=1)
pDn = plot(showBands ? lowerBand : na, "Lower Band", color=color.new(trendCol, 70), linewidth=1)
fill(pUp, pDn, color=showBands ? color.new(trendCol, 92) : na, title="Band Fill")

// Signals
plotshape(showSignals and flipUp, "Buy Signal", style=shape.labelup, location=location.belowbar, color=UpC, text="𝓛𝓸𝓷𝓰", textcolor=#000000, size=size.small)
plotshape(showSignals and flipDown, "Sell Signal", style=shape.labeldown, location=location.abovebar, color=DnC, text="𝓢𝓱𝓸𝓻𝓽", textcolor=#000000, size=size.small)

// Candle coloring
plotcandle(open, high, low, close, "Candle Plot", trendCol, trendCol, true, bordercolor = trendCol, display=display.pane, force_overlay=true)

// ╔══════════════════════════════════════════════════╗
// ║                    ALERTS                        ║
// ╚══════════════════════════════════════════════════╝
alertcondition(flipUp, "Bullish Trend Flip", "Kalman Flow | Lyro RS: Bullish trend flip on {{ticker}} ({{interval}})")
alertcondition(flipDown, "Bearish Trend Flip", "Kalman Flow | Lyro RS: Bearish trend flip on {{ticker}} ({{interval}})")
alertcondition(flipUp or flipDown, "Any Trend Flip", "Kalman Flow | Lyro RS: Trend flip on {{ticker}} ({{interval}})")

Overview

The trend flips bullish when price closes above the upper band with positive velocity, and bearish when it closes below the lower band with negative velocity. Sensitivity sets how fast the filter reacts, separate multipliers widen each band, and noise length controls the error lookback. Long and short labels, bands, candle coloring and palettes are optional.

Details

Published by

vedkanani123 on GitHub

Code credit

LyroRS, as written in the script's header

Draws

On the price chart

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.

Settings

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

SettingTypeDefaultVariable
𝗦𝗼𝘂𝗿𝗰𝗲sourceclosesrc
𝗦𝗲𝗻𝘀𝗶𝘁𝗶𝘃𝗶𝘁𝘆float4sensitivity
+ 𝗠𝘂𝗹𝘁𝗶𝗽𝗹𝗶𝗲𝗿float1.65mad_multp
- 𝗠𝘂𝗹𝘁𝗶𝗽𝗹𝗶𝗲𝗿float1mad_multn
𝗡𝗼𝗶𝘀𝗲 𝗟𝗲𝗻𝗴𝘁𝗵int50volLen
𝗦𝗵𝗼𝘄 𝗦𝗶𝗴𝗻𝗮𝗹𝘀booltrueshowSignals
𝗦𝗵𝗼𝘄 𝗕𝗮𝗻𝗱𝘀booltrueshowBands
𝗖𝗮𝗻𝗱𝗹𝗲 𝗖𝗼𝗹𝗼𝗿𝗶𝗻𝗴booltruecandleColor
Custom Color PalettestringMysticColMode
Use Custom Palettebooltruecpyn
Custom Upcolor#00ff00cp_UpC
Custom Downcolor#ff0000cp_DnC
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

Chandelier Exit

by everget
947 stars

This indicator plots an ATR-based Chandelier Exit trailing stop on the price chart. It tracks a long stop under recent highs and a short stop above recent lows, then switches direction when price crosses the opposite stop. Buy and sell labels mark those flips.

Indicator v6 Volatility & bandsTrend Repaints
Updated 12 days ago · GPL-3.0 GitHub repository of Chandelier Exit

The Momentum Setup is a multi-indicator visual tool designed for trend and momentum analysis directly on the price chart. It combines Relative Strength Index (RSI), Money Flow Index (MFI), Commodity Channel Index (CCI), Supertrend, and a 250-bar percentage cha

Indicator v5 Oscillators & momentumTrend
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - Ankush Bajaj Momentum Investing Setup
330 stars

Range Filter [Alorse] is a technical indicator overlay for TradingView designed to filter market volatility and identify price trends. It calculates a smoothed range based on historical volatility using a configurable sampling period and multiplier applied to

Indicator v5 TrendVolatility & bands
Updated 2 months ago · None stated GitHub repository of Range Filter [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

NVDA Trend Ribbon

by longsurf-ai
280 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated 3 days ago · MIT GitHub repository of NVDA Trend Ribbon

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers