Indicator · Pine Script v5 · On the chart

HMA-Kahlman Trend & Trendlines

by techteam92· code credited to capissimo

HMA-Kahlman Trend & Trendlines plots a smoothed directional trend ribbon directly on the price chart by combining Hull Moving Average calculations with an optional Kalman filter.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code115
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago20 Nov 2024

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

115 lines of Pine Script v5 from scripts/128-HMA-Kahlman-Trend-&-Trendlines-(v.2-2).pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

128-HMA-Kahlman-Trend-&-Trendlines-(v.2-2).pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=5
indicator('HMA-Kahlman Trend & Trendlines (v.2-2)', '', true, precision=2)

// This is an upgrade to HMA-Kahlman Trend & Trendlines script (https://www.tradingview.com/script/Pi7EVefr-hma-kahlman-trend-trendlines/). 
// This gives more flexibility because you can play around with 2 parameters to Kalman function (Sharpness and K (aka. step size)).

//== HMA-Kahlman Trend Module

//-- Inputs

base   = input.source(close, 'Dataset')
lag    = input.int   (14,    'Lookback', 2)
nrep   = input.bool  (false, 'Non-Repainting', inline='b')
labels = input.bool  (true,  'Labels',         inline='b')
k      = input.bool  (true,  'Kalman',         inline='b')

//-- Constants

var buy = '🡅' , var sell = '🡇'

//-- Variables

var int state = 0

//-- Functions 

cGreen(g) => g>9 ? #006400 : g>8 ? #1A741A : g>7 ? #338333 : g>6 ? #4D934D : g>5 ? #66A266 : g>4 ? #80B280 : g>3 ? #99C199 : g>2 ? #B3D1B3 : g>1?  #CCE0CC : #E6F0E6
cRed(g)   => g>9 ? #E00000 : g>8 ? #E31A1A : g>7 ? #E63333 : g>6 ? #E94D4D : g>5 ? #EC6666 : g>4 ? #F08080 : g>3 ? #F39999 : g>2 ? #F6B3B3 : g>1?  #F9CCCC : #FCE6E6
cAqua(g)  => g>9 ? #0080FFff : g>8 ? #0080FFe5 : g>7 ? #0080FFcc : g>6 ? #0080FFb2 : g>5 ? #0080FF99 : g>4 ? #0080FF7f : g>3 ? #0080FF66 : g>2 ? #0080FF4c : g>1 ? #0080FF33 : #00C0FF19
cPink(g)  => g>9 ? #FF0080ff : g>8 ? #FF0080e5 : g>7 ? #FF0080cc : g>6 ? #FF0080b2 : g>5 ? #FF008099 : g>4 ? #FF00807f : g>3 ? #FF008066 : g>2 ? #FF00804c : g>1 ? #FF008033 : #FF008019

hma3() => p = lag/2, ta.wma(ta.wma(close, p/3)*3 - ta.wma(close, p/2) - ta.wma(close, p), p)

klmf(x) =>
    sharpness = input.float(0.5, 'Sharpness', step=.05)  
    k         = input.float(10.0, 'K',        step=.05) //-- step size
    var float velocity = 0.0
    var float kf = 0.0
    float distance = x - nz(kf[1], x)
    float error = nz(kf[1], x) + distance * math.sqrt(sharpness*k/100)
    velocity := nz(velocity[1], 0) + distance*k/100
    kf := error + velocity

//-- Logic

float ds  = request.security('', '', base)[nrep?1:0]

float a   = k ? klmf(ds)     : ta.hma(ds, lag)
float b   = k ? klmf(hma3()) : hma3()
float avg = math.avg(a,b)
color c   = avg>avg[1] ? color.lime : color.red

bool crossdn = c==color.red    //a > b and a[1] < b[1]
bool crossup = c==color.lime   //b > a and b[1] < a[1]
state := crossup ? 1 : crossdn ? -1 : nz(state[1])

//-- Visuals

fill(plot(a,'', color.new(c,75), 1), plot(b,'',color.new(c,55),1), color.new(c, 55))
plot(avg, '', avg>avg[1]?cAqua(6):cPink(6), 1)

plotshape(labels and ta.change(state) and state==1  ? a : na, '', shape.labelup,   location.belowbar, na, 0, buy,  cAqua(10), size=size.small)
plotshape(labels and ta.change(state) and state==-1 ? a : na, '', shape.labeldown, location.abovebar, na, 0, sell, cPink(10), size=size.small)


//== Trendlines Module, see https://www.tradingview.com/script/mpeEgn5J-Trendlines-JD/

//-- Inputs

tlmod = input.bool(false, '===Trendlines Module===')
l1    = input.int (2,     'Pivots Lookback Window', 1)

//-- Functions

trendline(input_function, delay, only_up) => // Calculate line coordinates (Ax,Ay) - (Bx,By)
    var int Ax = 0, var int Bx = 0, var float By = 0.0, var float slope = 0.0
    Ay = fixnan(input_function)
    if ta.change(Ay)!=0
        Ax := time[delay], By:= Ay[1], Bx := Ax[1]
        slope := ((Ay-By)/(Ax-Bx))
    else
        Ax := Ax[1], Bx := Bx[1], By := By[1]

    var line trendline=na, var int Axbis=0, var float Aybis=0.0, var bool xtend=true
    extension_time = 0
    Axbis := Ax + extension_time
    Aybis := (Ay + extension_time*slope)
    if tlmod and ta.change(Ay)!=0
        line_color = slope*time<0?(only_up?na:color.red):(only_up?color.lime:na)
        if not na(line_color)
            trendline = line.new(Bx,By,Axbis, Aybis, xloc.bar_time, extend=xtend?extend.none:extend.none, color=line_color, style=line.style_dotted, width=1)
            line.delete(trendline[1])
    slope
    
pivot(len) =>    
    high_point = ta.pivothigh(high, len,len/2)
    low_point  = ta.pivotlow(low, len,len/2)
    slope_high = trendline(high_point, len/2,false)
    slope_low  = trendline(low_point, len/2,true)
    [high_point, low_point, slope_high, slope_low]

//-- Logic

[high_point1, low_point1, slope_high1, slope_low1] = pivot(l1) 

color_high1 = slope_high1 * time<0 ? color.red : na
color_low1  = slope_low1  * time>0 ? color.lime : na

//-- Visuals

plot(tlmod ? high_point1 : na, '', color_high1, 2, offset=-l1/2)
plot(tlmod ? low_point1  : na, '', color_low1,  2, offset=-l1/2)

Overview

HMA-Kahlman Trend & Trendlines evaluates two moving lines alongside their average, changing color to reflect bullish or bearish momentum. Directional arrow labels signal reversals whenever the slope of the average shifts. Users can adjust the lookback period, toggle a non-repainting offset, fine-tune Kalman sharpness and step size, or enable an optional pivot-based trendline module. Signals update dynamically on the open bar.

Details

Published by

techteam92 on GitHub

Code credit

capissimo, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages

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
Datasetsourceclosebase
Lookbackint14lag
Non-Repaintingboolfalsenrep
Labelsbooltruelabels
Kalmanbooltruek
Sharpnessfloat0.5sharpness
Kfloat10.0k
===Trendlines Module===boolfalsetlmod
Pivots Lookback Windowint2l1
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
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
277 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 yesterday · 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 6 weeks ago · None stated GitHub repository of Donald SPX - Options Trading

60K均線

by TaichiS
219 stars

This multi-timeframe indicator calculates and plots 20-period and 60-period simple moving averages from the 60-minute timeframe directly onto the price chart. The 20-period average displays as a green line, while the 60-period average appears in blue. It serve

Indicator v4 Moving averagesTrend Repaints
Updated 5 years ago · None stated GitHub repository of 60K均線

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