Indicator · Pine Script v4 · On the chart

Adaptive MA Slope

by capissimo

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.

View on GitHub

GitHub stars114on the repository
Pine versionv4older, still runs
Lines of code163
Settings6inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 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

163 lines of Pine Script v4 from scripts/118-Adaptive-MA-Slope.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

118-Adaptive-MA-Slope.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=4
study('Adaptive MA Slope', '', true)

// Adaptive MA Slope

// Description:

// This script generates a long entry signal when the slope of the Adaptive 
// Moving Average is positive, and/or generates a short entry signal when the 
// slope of the Adaptive Moving Average is negative.

// The Moving Average Adaptive (Kaufman) belongs to the family of 
// moving averages, which aid in smoothing or eliminating fluctuations in data. 
// Moving averages    emphasize the direction of a trend, confirm trend reversals 
// and smooth out price and volume fluctuations or 'noise' that can confuse 
// interpretation of the market. The KAMA adjusts to market volatility by 
// lengthening when the market is moving sideways and trading in a choppy 
// fashion (making it less responsive) and shortening when the market is 
// trending (making it more responsive).

//-------------------- Inputs

ptype  = input('OHL3',       'Price Type',             options=['Open','High','Low','Close','HL2','OC2','OHL3','HLC3','OHLC4'])
lag    = input(20,           'Indicator Lag |2..n|',   minval=2)
lkb    = input(6,            'Lookback Period |1..n|', minval=1)
ftype  = input('Both',       'Filter Signals by',      options=['Volatility','Volume','Both','None'])

//-------------------- System Variables

var int BUY  =  1
var int SELL = -1
var int HOLD =  0

//-------------------- Series

var bool  long   = 0.0
var bool  short  = 0.0
var int   signal = HOLD
var float result = ohlc4

//-------------------- Custom Functions

kama(ds, p) => // Kaufman adaptive MA
    fSC = 0.6666666666666667//2 / (input(2,   "KAMA: Fast Alpha", minval=1) + 1)
    sSC = 0.0645161290322581//2 / (input(30,  "KAMA: Slow Alpha", minval=1) + 1)
    kamaFinal         = 0.0
    l                 = na(ds[p]) ? bar_index : p
    change            = nz(abs(ds - ds[p]), abs(ds - ds[l]))
    volatility        = nz(sum(abs(ds - ds[1]), p), cum(abs(ds - ds[1])))
    efficiencyRatio   = change / volatility
    smoothingConstant = pow((efficiencyRatio * (fSC - sSC) + sSC), 2)
    kamaFinal        := nz(kamaFinal[1], ds) + nz(smoothingConstant) * nz((ds - kamaFinal[1]))

volumeBreak(thres) =>  
    rsivol   = rsi(volume, 14)  
    osc      = hma(rsivol, 10)  
    osc > thres                     

volatilityBreak(volmin, volmax) => atr(volmin) > atr(volmax)

//-------------------- Logic

tbase   = (time - time[1]) / 1000
tcurr   = (timenow - time_close[1]) / 1000
barlife = tcurr / tbase

base =  ptype=='Open'  ? open 
      : ptype=='High'  ? high
      : ptype=='Low'   ? low
      : ptype=='Close' ? close
      : ptype=='OC2'   ? (open+close)/2 
      : ptype=='HL2'   ? hl2 
      : ptype=='OHL3'  ? (open+high+low)/3 
      : ptype=='HLC3'  ? hlc3 
      :                  ohlc4

filter =   ftype=='Volatility' ? volatilityBreak(1, 10) 
         : ftype=='Volume'     ? volumeBreak(49) 
         : ftype=='Both'       ? volatilityBreak(1, 10) and volumeBreak(49)
         :                       true

ma = kama(base, lag)

signal := ma > ma[lkb] and filter ? BUY : ma < ma[lkb] and filter ? SELL : nz(signal[1])

result := (ma > ma[lkb] and filter) ? low : (ma < ma[lkb] and filter) ? high : nz(result[1])

changed = change(signal)

startLongTrade  = changed and signal==BUY
startShortTrade = changed and signal==SELL
endLongTrade    = changed and signal==SELL
endShortTrade   = changed and signal==BUY

//-------------------- Visualization

plot(result, '', color.olive, 2, plot.style_linebr)

plotshape(startLongTrade  ? low   : na, 'Buy',  shape.labelup,   location.absolute, color.blue, text='b', size=size.tiny) 
plotshape(startShortTrade ? high  : na, 'Sell', shape.labeldown, location.absolute, color.red,  text='s', size=size.tiny) 
plot(endLongTrade         ? ohlc4 : na, 'StopBuy',  color.blue, 2, plot.style_cross)
plot(endShortTrade        ? ohlc4 : na, 'StopSell', color.red,  2, plot.style_cross)

//-------------------- Notification

if changed and signal==BUY 
    alert('Buy Alert', alert.freq_once_per_bar)  // alert.freq_once_per_bar_close
if changed and signal==SELL 
    alert('Sell Alert', alert.freq_once_per_bar)
    
alertcondition(startLongTrade,  'Buy Alert',  'Go Long!')
alertcondition(startShortTrade, 'Sell Alert', 'Go Short!')

//-------------------- Backtest

show_info = input(false, '===Information===')
lot_size  = input(0.01,  'Lot Size', options=[0.01,0.1,0.2,0.3,0.5,1,2,3,5,10,20,30,50,100,1000]) 

bidask = open //-- (open+high+low)/3 is a more restrained estimate

var float start_long_trade  = bidask  
var float long_trades       = 0.
var float start_short_trade = bidask  
var float short_trades      = 0.
var int   wins              = 0
var int   trade_count       = 0

if startLongTrade 
    start_long_trade := bidask 
if endLongTrade
    ldiff         = (bidask - start_long_trade)
    wins         := ldiff > 0 ? 1 : 0
    long_trades  := ldiff * lot_size   
    trade_count  := 1
if startShortTrade 
    start_short_trade := bidask
if endShortTrade
    sdiff         = (start_short_trade - bidask)
    wins         := sdiff > 0 ? 1 : 0
    short_trades := sdiff * lot_size 
    trade_count  := 1
    
cumreturn   = cum(long_trades) + cum(short_trades)  //-- cumulative return 
totaltrades = cum(trade_count)
totalwins   = cum(wins)  
totallosses = totaltrades - totalwins == 0 ? 1 : totaltrades - totalwins

//------------------- Information

var label lbl = na

info =  ptype
      + '\nCR='        + tostring(cumreturn,             '#.#') 
      + '\nWinrate: '  + tostring(totalwins/totaltrades, '#.#%')       
      + '\nBar Time: ' + tostring(barlife,               '#.#%')

if show_info and barstate.islast  
    lbl := label.new(bar_index, ohlc4, info, xloc.bar_index, yloc.price, 
                     color.new(color.blue, 100), label.style_label_left, color.black, size.small, text.align_left)
    label.delete(lbl[1])

Overview

Signals can be filtered by short-term volatility expansion using ATR comparisons, volume momentum via a Hull Moving Average of volume RSI, or both. It plots directly on the price chart and identifies transitions between bullish and bearish market states. As an indicator, it does not include execution logic or risk management rules.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Moving averages, Trend, Volatility & bands, Volume

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
Price TypestringOHL3ptype
Indicator Lag |2..n|int20lag
Lookback Period |1..n|int6lkb
Filter Signals bystringBothftype
===Information===boolfalseshow_info
Lot Sizefloat0.01lot_size
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

9 stars

This indicator plots a volume-weighted moving average as a central trend baseline and surrounds it with ATR-based volatility bands. It colors the trend and optional price bars according to whether price is on the bullish or bearish side of those bands. Users c

Indicator v6 TrendMoving averages
Updated 4 months ago · MIT GitHub repository of Volume Weighted Trend [QuantAlgo]

EMA System

by eddiebelaval
7 stars

EMA System plots four exponential moving averages on the price chart and marks a long-only pullback setup. It treats price above the 200 EMA and the 21 EMA above the 50 EMA as a valid trend, then flags a buy when price is near the 21 EMA, volume is below its s

Indicator v6 TrendMoving averages
Updated 3 months ago · None stated GitHub repository of EMA System

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

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