Indicator · Pine Script v6 · On the chart

Directional Kernel Filter [BackQuant]

by ZhijuCen· code credited to BackQuant

Calculates Gaussian kernel moving averages adjusted by directional price alignment and normalized by ATR.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code123
Settings13inputs
LicenceMIT
Last update2 weeks ago12 Oct 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

123 lines of Pine Script v6 from skills/mql5-from-pinescript/assets/pine-scripts/directional-kernel-filter.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

directional-kernel-filter.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BackQuant


//@version=6
indicator("Directional Kernel Filter [BackQuant]", shorttitle="Directional Kernel [BackQuant]", overlay=true)

// Constants
const string calc = "Core Calculation Settings"
const string ui   = "Plotting and Coloring"
const color GREEN = #00ff00
const color RED   = #ff0000

// Inputs
float src = input.source(close, "Source", group=calc)
int fastLen = input.int(18, "Fast Kernel Length", minval=3, group=calc, inline="LEN")
int slowLen = input.int(35, "Slow", minval=5, group=calc, inline="LEN")
float kernelWidth = input.float(0.35, "Kernel Width", minval=0.05, maxval=1.0, step=0.05, group=calc, tooltip="Controls the Gaussian kernel bandwidth relative to the filter length. Lower values concentrate weight near the current bar.")
float directionStrength = input.float(3.5, "Directional Weight", minval=0.0, maxval=5.0, step=0.1, group=calc, tooltip="Controls how strongly observations agreeing with the previously estimated direction are favored. 0 disables directional weighting.")
int normLen = input.int(14, "Normalization Length", minval=2, group=calc, tooltip="ATR length used to normalize directional price movement across assets and volatility regimes.")

color longCol = input.color(GREEN, "Long Color", group=ui, inline="COL")
color shortCol = input.color(RED, "Short Color", group=ui, inline="COL")
int lineW = input.int(3, "Line Width", minval=1, maxval=6, group=ui)
bool showRibbon = input.bool(true, "Show Trend Ribbon?", group=ui)
bool showBase = input.bool(false, "Show Base Kernel?", group=ui)
bool paintCandles = input.bool(false, "Paint Candles to Trend?", group=ui)
bool bgCol = input.bool(false, "Background Color?", group=ui)

// Directional Kernel Filter
directionalKernel(float source, simple int length, float width, float strength, float norm) =>
    float bandwidth = math.max(1.0, length * width)

    float baseWeighted = 0.0
    float baseWeights = 0.0

    for i = 0 to length - 1
        if not na(source[i])
            float distance = i / bandwidth
            float kernelWeight = math.exp(-0.5 * distance * distance)
            baseWeighted += source[i] * kernelWeight
            baseWeights += kernelWeight

    float base = baseWeights > 0.0 ? baseWeighted / baseWeights : na

    float priorDirection = nz(base[1] - base[2])
    float priorNorm = priorDirection / math.max(nz(norm[1], norm), syminfo.mintick)
    priorNorm := math.max(-1.0, math.min(1.0, priorNorm))

    float weightedPrice = 0.0
    float totalWeight = 0.0

    for i = 0 to length - 1
        if not na(source[i])
            float distance = i / bandwidth
            float kernelWeight = math.exp(-0.5 * distance * distance)

            float localMove = i < length - 1 ? source[i] - source[i + 1] : 0.0
            float localNorm = localMove / math.max(nz(norm[i], norm), syminfo.mintick)
            localNorm := math.max(-1.0, math.min(1.0, localNorm))

            float alignment = priorNorm * localNorm
            float exponent = math.max(-3.0, math.min(3.0, strength * alignment))
            float directionWeight = math.exp(exponent)

            float weight = kernelWeight * directionWeight

            weightedPrice += source[i] * weight
            totalWeight += weight

    float filtered = totalWeight > 0.0 ? weightedPrice / totalWeight : base

    [filtered, base, priorNorm]

// Normalization
float atr = ta.atr(normLen)

// Fast + Slow Directional Kernels
[fastKernel, fastBase, fastDirection] = directionalKernel(src, fastLen, kernelWidth, directionStrength, atr)
[slowKernel, slowBase, slowDirection] = directionalKernel(src, slowLen, kernelWidth, directionStrength, atr)

// Trend State
bool bullish = fastKernel > slowKernel
bool bearish = fastKernel < slowKernel

var int trend = 0

if bullish
    trend := 1
else if bearish
    trend := -1

color col = trend == 1 ? longCol : shortCol

// Ribbon
pFast = plot(fastKernel, "Fast Directional Kernel", col, lineW)
pSlow = plot(showRibbon ? slowKernel : na, "Slow Directional Kernel", color.new(col, 60), 2)

fill(pFast, pSlow, showRibbon ? color.new(col, 82) : na, title="Directional Kernel Ribbon")

// Base Gaussian Kernel
plot(showBase ? fastBase : na, "Base Gaussian Kernel", color.new(chart.fg_color, 60), 1)

// Candles
plotcandle(open, high, low, close, "Trend Candles",
     col, col, true,
     bordercolor=col,
     display=paintCandles ? display.all : display.none)

bgcolor(bgCol ? color.new(col, 90) : na)

// Data Window
plot(fastDirection, "Fast Reference Direction", display=display.data_window)
plot(slowDirection, "Slow Reference Direction", display=display.data_window)
plot(fastKernel - fastBase, "Directional Adjustment", display=display.data_window)
plot(fastKernel - slowKernel, "Kernel Spread", display=display.data_window)

// Alerts
bool bullFlip = trend == 1 and trend[1] == -1
bool bearFlip = trend == -1 and trend[1] == 1

alertcondition(bullFlip, title="Directional Kernel Bullish", message="Directional Kernel Trend Filter turned bullish {{exchange}}:{{ticker}}")
alertcondition(bearFlip, title="Directional Kernel Bearish", message="Directional Kernel Trend Filter turned bearish {{exchange}}:{{ticker}}")

Overview

The indicator applies fast and slow smoothing lengths with custom kernel bandwidth and directional weighting settings to smooth price action while minimizing lag during trends. It plots directly on the price chart, offering visual options such as a trend ribbon, base kernel overlay, bar candle coloring, and trend background highlighting.

Details

Published by

ZhijuCen on GitHub

Code credit

BackQuant, 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
Sourcesourceclosesrc
Fast Kernel Lengthint18fastLen
Slowint35slowLen
Kernel Widthfloat0.35kernelWidth
Directional Weightfloat3.5directionStrength
Normalization Lengthint14normLen
Long ColorcolorGREENlongCol
Short ColorcolorREDshortCol
Line Widthint3lineW
Show Trend Ribbon?booltrueshowRibbon
Show Base Kernel?boolfalseshowBase
Paint Candles to Trend?boolfalsepaintCandles
Show all 13 settings
SettingTypeDefaultVariable
Background Color?boolfalsebgCol
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

947 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 12 days ago · GPL-3.0 GitHub repository of Adaptive Laguerre Filter
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 plots four customizable moving averages directly on the main price chart using default lengths of 3, 8, 21, and 50 periods. It fills the space between adjacent averages in green or maroon depending on trend alignment. Additionally, it computes B

Indicator v5 Moving averagesTrend
Updated 2 months ago · MIT GitHub repository of Multiple Moving Averages

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
257 stars

Donald SPX - Options Trading is an overlay indicator designed for intraday SPX analysis. It plots a 200-period Weighted Moving Average (WMA) on the price chart while evaluating multi-timeframe market structure across Daily, 15-minute, 5-minute, and 2-minute ba

Indicator v5 Moving averagesTrend Repaints
Updated 7 weeks ago · None stated GitHub repository of Donald SPX - Options Trading
228 stars

This indicator computes moving average and RSI bias signals across the current timeframe and four higher timeframes. It sums biases from the MA and RSI to derive an overall bullish or bearish signal. The results appear in a configurable table that displays eac

Indicator v6 TrendMoving averages
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe Analysis Template

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