Indicator · Pine Script v5 · On the chart

Kaufman's Adaptive Moving Average (KAMA)

by kevinhhl· code credited to DojiEmoji

Calculates Kaufman's Adaptive Moving Average (KAMA) based on Kaufman's Efficiency Ratio to adjust smoothing dynamically according to market volatility and efficiency.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code65
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago6 Oct 2023

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

65 lines of Pine Script v5 from Scripts/KAMA.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

KAMA.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DojiEmoji

//@version=5

indicator(title="Kaufman's Adaptive Moving Average (KAMA)", shorttitle="KAMA", overlay=true, timeframe="", timeframe_gaps=false)

var int period = input.int(10, title="Lookback period", minval=2)

// Implementation of Kaufman's Efficiency Ratio ("ER"):
// (Previous script: https://www.tradingview.com/script/j9hCD2lP-Kaufman-s-Efficiency-Ratio-Indicator/)
// @function er(source, length) returns float efficiency ratio.
er(src, len) =>
    float total_abs_chng = 0
    for i = 1 to len by 1
        total_abs_chng += math.abs(src[i - 1] - src[i])
    (src - src[len]) / total_abs_chng                       // Return: net change / total absolute change

// Kaufman's Adaptive Moving Average ("KAMA")
// (Source: Chapter 17, "Trading System and Methods - 6th edition" by Perry J. Kaufman)
// {
// KAMA_t = KAMA_t-1 + sc_t * (p_t - KAMA_t-1)
// where:
//   p_t = current closing price
//   sc_t = smoothing constant, based on Kaufman's Eff. Ratio ("ER")
//
//   where: sc_t = (ER_t x (_FAST - _SLOW) + _SLOW) ^2
//          _FAST = 2 / (fast MA period + 1)
//          _SLOW = 2 / (slow MA period + 1)
//          Fast and slow periods are 2, and 30 (respectively)
// }

var float _FAST = 0.666666666666667
var float _SLOW = 0.0645161290322581
abs_er = math.abs(er(close, period))
sc_t = math.pow(abs_er * (_FAST-_SLOW) + _SLOW, 2)

float KAMA_t = 0
KAMA_t := nz(KAMA_t[1],close[1]) + sc_t * (close-nz(KAMA_t[1],close[1]))


//-----------------------
// Experimental features 
//-----------------------

var string GROUP_EXP = "Experimental"

// Background colors to visualize levels of market noise (experimental)
var bool bgcol_mode  = input.bool(false, title="Fill background: Low / High Noise", group=GROUP_EXP, inline="ln0",
 tooltip="To visualize market noise. Thresholds (min.) can be adjusted below.")
var color color_low  = input.color(color.new(color.green, 90),title="Low level of market noise", group=GROUP_EXP, inline="ln1")
var color color_high = input.color(color.new(color.red, 90),title="High level of market noise", group=GROUP_EXP, inline="ln1")
var float thres_low  = input.float(0.25, minval=0, maxval=0.5, step=0.01, title="Thresholds for Low / High Noise", inline="ln2", group=GROUP_EXP)
var float thres_high = input.float(0.5, minval=0.5, maxval=1, step=0.01, title="/", inline="ln2", group=GROUP_EXP)
bgcolor(bgcol_mode and abs_er < thres_low ? color_low : na)
bgcolor(bgcol_mode and abs_er > thres_high ? color_high : na)

// Smoothening
var bool use_linreg = input.bool(false, title="Smooth KAMA:", inline="ln3", group=GROUP_EXP, tooltip="Using the least squares method over the same window of lookback.")

//-----------------------
// Plot
//-----------------------
kama_plot = use_linreg ? ta.linreg(KAMA_t, period, 0) : KAMA_t
plot(kama_plot, title="KAMA")

Overview

Plotted directly on the price chart, it adapts faster during trending markets and slows down during consolidation. Optional settings allow smoothing the line using linear regression and highlighting background noise levels based on user-defined Efficiency Ratio thresholds.

Details

Published by

kevinhhl on GitHub

Code credit

DojiEmoji, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Moving averages, Trend, Volatility & bands

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
Lookback periodint10period
Fill background: Low / High Noiseboolfalsebgcol_mode
Low level of market noisecolorcolor.new(color.green, 90)color_low
High level of market noisecolorcolor.new(color.red, 90)color_high
Thresholds for Low / High Noisefloat0.25thres_low
/float0.5thres_high
Smooth KAMA:boolfalseuse_linreg
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

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

Bollinger Bands Force

by harryguiacorn
219 stars

This indicator modifies standard Bollinger Bands to measure directional trend force based on line alignment. It calculates a simple moving average basis along with upper and lower volatility bands. When all three lines move upward or downward simultaneously, i

Indicator v5 Volatility & bandsTrend
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Force

Adaptive MA Slope

by capissimo
114 stars

This indicator calculates Kaufman's Adaptive Moving Average (KAMA) on a chosen price source and determines trend direction based on the slope across a configurable lookback window. Signals can be filtered by short-term volatility expansion using ATR comparison

Indicator v4 Moving averagesTrend
Updated 1 year ago · None stated GitHub repository of Adaptive MA Slope

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