Indicator · Pine Script v4 · On the chart

LAMA-based Strategy

by capissimo

This indicator calculates two Log-Normal Moving Averages (LAMA) based on John Ehlers' adaptive process and generates trend-following signals on the price chart.

View on GitHub

GitHub stars114on the repository
Pine versionv4older, still runs
Lines of code165
Settings9inputs
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

165 lines of Pine Script v4 from scripts/112-LAMA-based-Strategy.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

112-LAMA-based-Strategy.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("LAMA-based Strategy", '', true)

// Log-Normal Moving Average (LAMA)

// The Log-Normal Moving Average (LAMA) is the name given to 
// an Adaptive Moving Average that uses the adaptive process 
// developed by John F Ehlers for use in his FRAMA.  
// Stock prices are said to be Log-Normal so Ehlers used EXP 
// to relate his Volatility Index (The Fractal Dimension) to Alpha.  
// The LAMA is designed so that any VIX can easily be incorporated 
// as long as it shifts between a range of 1 – 0 where high readings 
// indicate high volatility.

// Formula:
// LAMA = LAMA(1) + New α * (Close – LAMA(1))
// where:
//    New α = 2 / (New N + 1)
//    New N = ((SC – FC) * ((N – 1) / (SC – 1))) + FC
//    SC = Your choice of a Slow moving average > FC
//    FC = Your choice of a Fast moving average < SC
//    N = (2 – α) / α
//    α = EXP(W * (1 – VIX))
//    W = LN(2 / (SC + 1))

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

ds        = input(close, 'Dataset')
prim      = input(3,     'Primary Lag |1..n|',    minval=1)
sec       = input(2,     'Secondary Lag |1..n|',  minval=1)
ftype     = input('Both','Filter Signals by',     options=['Volatility','Volume','Both','None'])
holding_p = input(1,     'Holding Period |1..n|', minval=1)
showma    = input(false, 'Show MAs?')

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

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

//--------------------  Dynamic Arrays

var int   signal     = HOLD
var float maf        = 0.0
var float mas        = 0.0
var int   hp_counter = 0

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

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

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

lama(ds, prim, sec) =>
    vix   = 100 * abs(high - low) / close  // volatility index
    W     = log(2 / (sec + 1))
    a     = exp(W * (1 - vix))
    N     = (2 - a) / a
    New_N = ((sec - prim) * ((N - 1) / (sec - 1))) + prim
    New_a = 2 / (New_N + 1)
    var float lama = 0.0
    lama := nz(lama[1]) + New_a * (ds - nz(lama[1]))

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

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

lama1 = lama(ds, prim, sec)
lama2 = lama(lama1, prim, prim+2)
    
// Generate signal

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

changed = change(signal)

hp_counter := changed ? 0 : hp_counter + 1

startLongTrade  = changed and signal==BUY    
startShortTrade = changed and signal==SELL   
endLongTrade    = (changed and signal==SELL) or (signal==BUY  and hp_counter==holding_p and not changed) 
endShortTrade   = (changed and signal==BUY)  or (signal==SELL and hp_counter==holding_p and not changed) 

//-------------------- Rendering

plot(showma ? lama1 : na, '', color.orange)
plot(showma ? lama2 : na, '', color.blue)

plotshape(startLongTrade  ? low  : na, 'Buy',  shape.labelup,   location.belowbar, color.blue, 30, size=size.tiny, text='lm', textcolor=color.white)
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, color.red,  30, size=size.tiny, text='lm', textcolor=color.white)
plot(endLongTrade         ? high : na, 'StopBuy',  color.blue, 2, plot.style_cross)
plot(endShortTrade        ? low  : 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!") 

//-------------------- Backtesting

show_info = input(true, '===Backtesting Results===')
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]) 
useopen   = input(true,  'Open Price=true, OHL3=false')

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

bidask  = useopen ? open : (open+high+low)/3

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 =  'CR='          + tostring(cumreturn,             '#.#') 
      + '\nTrades: '   + tostring(totaltrades,           '#')
      + '\nWin/Loss: ' + tostring(totalwins/totallosses, '#.##') 
      + '\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

Entry signals trigger when the fast LAMA crosses the slow LAMA, optionally filtered by ATR volatility breakouts, volume RSI momentum, or both. Exits occur upon an opposing crossover or after a user-defined holding period expires. Inputs allow adjustment of primary and secondary lag parameters, data source, filter types, and visibility of the moving average lines.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

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
Datasetsourcecloseds
Primary Lag |1..n|int3prim
Secondary Lag |1..n|int2sec
Filter Signals bystringBothftype
Holding Period |1..n|int1holding_p
Show MAs?boolfalseshowma
===Backtesting Results===booltrueshow_info
Lot Sizefloat0.01lot_size
Open Price=true, OHL3=falsebooltrueuseopen
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 Price Zone

by mihakralj
99 stars

The Adaptive Price Zone indicator calculates volatility bands around a double-smoothed exponential moving average baseline directly on the price chart. It calculates internal smoothing factors using the square root of the user-specified period, double-smoothin

Indicator v6 Volatility & bandsTrend
Updated 4 weeks ago · Apache-2.0 GitHub repository of Adaptive Price Zone

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