Indicator · Pine Script v4 · On the chart

22-MA Strategy

by capissimo

22-MA Strategy plots a selectable center moving average on the price chart and marks upper and lower levels a fixed pip distance from that average.

View on GitHub

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

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

099-22-MA-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("22-MA Strategy", overlay=true, precision=4)

// This is the extension of my previous script Pip Collector Mod.
// See https://www.tradingview.com/script/FNViwnJO-Pip-collector-Mod/
// In addition to the previous functionality it features 22 Moving 
// Average functions.

// Enjoy!

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

base      = input(close, 'Dataset')
atype     = input('WildMA','Moving Average Type',   
                  options=['SMA','WMA','EMA','HMA','HMA3','RMA','ALMA','VWMA','SWMA','VWAP','WildMA','REMA',
                           'LowPass','LowPass6','HighPass','SineMA','ShmMa','TMA','JMA','SSmthr','KLMF','Kahlman'])
p         = input(50,    'Center MA Length |1..n|', minval=1, maxval=2160)
length    = input(20,    'Upper/Lower Distance from Center (PIPs) |-n..n|')
fltr      = input(true,  'Filter Signals Out By Volatility?')
holding_p = input(5,     'Holding Period |1..n|',    minval=1, maxval=240)
show_info = input(true,  'Display information?')

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

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

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

var int   signal     = HOLD
var int   hp_counter = 0
var label lbl        = na

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

klmf(x) =>  // Kalman filter
    var value1 = swma(x-x[1])
    value1 := 0.1*(x-x[1]) + 0.9*nz(value1[1])
    var value2 = swma(tr)
    value2 := 0.1*(tr) + 0.9*nz(value2[1])
    lambda = abs(value1/value2)
    alpha = (-lambda*lambda + sqrt(lambda*lambda*lambda*lambda + 16*lambda*lambda))/8
    var klmf = 0.
    klmf := alpha*x + (1-alpha)*nz(klmf[1])

kahlman(x, g) => 
    kf = 0.0
    dk = x - nz(kf[1], x)
    smooth = nz(kf[1],x)+dk*sqrt(g*2)
    velo = 0.0
    velo := nz(velo[1],0) + (g*dk)
    kf := smooth+velo
     
wildma(x, p) =>    
    k = 1 / p
    wldma = 0.0
    wldma := x * k + nz(wldma[1]) * (1-k)
    wldma

hma3(x, p) =>
    len = p/2
    wma(wma(x,len/3)*3 - wma(x,len/2) - wma(x,len),len)

rema(x, p) => // regularized ma
    rm = 0.0, lambda = .5, a = 2 / (p + 1)
    rm := (nz(rm[1]) + a * (x - nz(rm[1])) + lambda * (2 * nz(rm[1]) - nz(rm[2]))) / (lambda + 1)
    rm

lowPass(x, p)=>
    LP = x
    sr = x
    a = 2.0 / (1.0 + p)
    LP := (a - 0.25 * a * a) * sr + 0.5 * a * a * nz(sr[1]) - (a - 0.75 * a * a) * nz(sr[2]) + 2.0 * (1.0 - a) * nz(LP[1]) - (1.0 - a) * (1.0 - a) * nz(LP[2])
    LP   

sinewma(x, p) =>
    PI = 2 * asin(1)
    sum = 0.0
    weightSum = 0.0
    for i = 0 to p-1
        weight = sin(i * PI / (p + 1))
        sum := sum + nz(x[i]) * weight
        weightSum := weightSum + weight
    sum/weightSum

tma(x, p) =>
    half = (p+1.0)/2.0
    summ = x, sumw = 1, weight = 0
    for k=1 to p
        weight := (weight > half) ? p : 1
        sumw := sumw + weight
        summ := summ + weight*x[k]  
    summ/sumw

jma(x, p) =>
    beta = 0.45*(p-1)/(0.45*(p-1)+2)
    alpha = beta
    L0=0.0, L1=0.0, L2=0.0, L3=0.0, L4=0.0
    L0 := (1-alpha)*x + alpha*nz(L0[1])
    L1 := (x - L0[0])*(1-beta) + beta*nz(L1[1])
    L2 := L0[0] + L1[0]
    L3 := (L2[0] - nz(L4[1]))*((1-alpha)*(1-alpha)) + (alpha*alpha)*nz(L3[1])
    L4 := nz(L4[1]) + L3[0]
    L4

lowpass6Order(x, p) => // Butterworth 6th order low pass filter with a cut off frequency of 0.05 * sample rate
    GAIN = 1.165969038e+05
    dest = 0.0
    xv0  = 0.0, xv1 = 0.0, xv2 = 0.0, xv3 = 0.0, xv4 = 0.0, xv5 = 0.0, xv6 = 0.0
    yv0  = 0.0, yv1 = 0.0, yv2 = 0.0, yv3 = 0.0, yv4 = 0.0, yv5 = 0.0, yv6 = 0.0
 
    for i=0 to p-1
        xv0 := xv1, xv1 := xv2, xv2 := xv3, xv3 := xv4, xv4 := xv5, xv5 := xv6
        xv6 := x[i] / GAIN
        yv0 := yv1, yv1 := yv2, yv2 := yv3, yv3 := yv4, yv4 := yv5,yv5 := yv6
        yv6 := (xv0 + xv6) + 6.0 * (xv1 + xv5) + 15.0 * (xv2 + xv4) + 20.0 * xv3 + ( -0.2951724313 * yv0) + (  2.1290387500 * yv1) + ( -6.4411118810 * yv2) + (  10.4690788930 * yv3) + ( -9.6495177287 * yv4) + (  4.7871354989 * yv5)
        dest := yv6
    dest

supersmoother(x, p) =>
    pi      = 2 * asin(1)
    s_a1    = exp(-sqrt(2) * pi / p)
    s_b1    = 2 * s_a1 * cos(sqrt(2) * pi / p)
    s_c3    = -pow(s_a1, 2)
    s_c2    = s_b1
    s_c1    = 1 - s_c2 - s_c3
    ss      = 0.0
    ss     := s_c1 * x + s_c2 * nz(ss[1], x[1]) + s_c3 * nz(ss[2], x[2])

shmma(src, len) =>
    factor = 0.0, slope = 0.0

    for i = 1 to len
        factor := 1 + 2 * (i - 1)
        slope := slope + (src[i - 1]) * (len - factor) / 2

    sma(src, len) + (6 * slope) / ((len + 1) * len)

highpass(src, len) =>
    a = (0.707 * 2 * 3.14159) / len
    alpha1 = 1.0  + (sin(a) - 1.0) / cos(a)
    b = 1.0 - alpha1 / 2.0
    c = 1.0 - alpha1
    hp = 0.0
    hp := b * b * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * c * nz(hp[1]) - c * c * nz(hp[2])
    src - hp

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

pip   = syminfo.mintick 

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

ma =   atype=='SMA'        ? sma(base, p) 
     : atype=='WMA'        ? wma(base, p) 
     : atype=='EMA'        ? ema(base, p) 
     : atype=='HMA'        ? hma(base, p) 
     : atype=='HMA3'       ? hma3(base, p) 
     : atype=='RMA'        ? rma(base, p) 
     : atype=='ALMA'       ? alma(base, p, 0.35, 6) 
     : atype=='VWMA'       ? vwma(base, p) 
     : atype=='SWMA'       ? swma(base) 
     : atype=='VWAP'       ? vwap(base) 
     : atype=='REMA'       ? rema(base, p) 
     : atype=='WildMA'     ? wildma(base, p) 
     : atype=='LowPass'    ? lowPass(base, p) 
     : atype=='HighPass'   ? highpass(base, p) 
     : atype=='SineMA'     ? sinewma(base, p) 
     : atype=='ShmMa'      ? shmma(base, p) 
     : atype=='JMA'        ? jma(base, p) 
     : atype=='TMA'        ? tma(base, p) 
     : atype=='SSmthr'     ? supersmoother(base, p) 
     : atype=='KLMF'       ? klmf(base) 
     : atype=='Kahlman'    ? kahlman(base, .001) 
     :                       lowpass6Order(base, p) 

upper = ma + length * pip
lower = ma - length * pip

filter  = fltr ? atr(1) > atr(10) : true   //-- filter out by volatility
signal := close > lower and filter ? BUY : close < upper 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    = (signal==BUY  and hp_counter==holding_p and not changed) //-- TOADD: stop by trade duration
endShortTrade   = (signal==SELL and hp_counter==holding_p and not changed) 

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

plot(ma,    'Center EMA', color.blue,  2)
plot(lower, 'Lower',      color.red,   2)
plot(upper, 'Upper',      color.green, 2)

plotshape(startLongTrade  ? low   : na, 'Buy',  shape.labelup,   location.absolute, cGreen(7), size=size.small)
plotshape(startShortTrade ? high  : na, 'Sell', shape.labeldown, location.absolute, cRed(7),   size=size.small)
plot(endLongTrade         ? ohlc4 : na, 'StopBuy',  cGreen(6), 2, plot.style_cross)
plot(endShortTrade        ? ohlc4 : na, 'StopSell', cRed(6),   2, plot.style_cross)

//-------------------- Alerting

alertcondition(startLongTrade,  'Buy',  'Go long!')
alertcondition(startShortTrade, 'Sell', 'Go short!') 
alertcondition(startLongTrade or startShortTrade, 'General Alert', 'Deal Time!')

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

// countdown in %
tbase = (time - time[1]) / 1000
tcurr = (timenow - time_close[1]) / 1000

info = 'Bar Time: ' + tostring(tcurr / tbase, '#.#%')

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

22-MA Strategy supports twenty-two average types, from SMA, EMA, and HMA variants through filters such as Kalman and JMA-style smoothers. Optional volatility filtering and a holding-period setting shape buy, sell, and hold signals, with labels available for display. An information panel can be toggled. This overlay indicator does not place orders or define exits.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Moving averages, Volatility & bands

Markets

Forex

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
Moving Average TypestringWildMAatype
Center MA Length |1..n|int50p
Upper/Lower Distance from Center (PIPs) |-n..n|int20length
Filter Signals Out By Volatility?booltruefltr
Holding Period |1..n|int5holding_p
Display information?booltrueshow_info
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

Hampel Filter

by everget
948 stars

The Hampel Filter indicator identifies and filters out price outliers to smooth price data directly on the main chart. It calculates the rolling median and Median Absolute Deviation (MAD) of the chosen source series over a specified length. When a data point e

Indicator v4 Moving averagesVolatility & bands
Updated 10 days ago · GPL-3.0 GitHub repository of Hampel Filter

This overlay indicator plots a Supertrend from an ATR length and factor, four exponential moving averages, and a selectable VWAP or TWAP taken from a chosen timeframe on the price chart. It also shows MACD and stochastic with adjustable lengths, smoothing, ver

Indicator v5 Oscillators & momentumMoving averages
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup: Vijay Thakare Option Buying Scalping Setup

This indicator plots trade entry and exit signals on the price chart by combining Bollinger Bands with optional filter conditions. It calculates standard Bollinger Bands along with RSI, Aroon, and moving average filters. Reversal signals trigger when price bre

Indicator v4 Volatility & bandsOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner IND [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

Algo AVT

by ricardosantos79
261 stars

This indicator calculates an outlier-filtered moving average based on statistical filtering concepts. It stores close prices in a rolling array over a user-defined length, calculates the mean and standard deviation, and excludes values falling within a specifi

Indicator v4 Moving averagesVolatility & bands
Updated 4 years ago · None stated GitHub repository of Algo AVT

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