Strategy · Pine Script v5 · On the chart

Triple EMA vs 55 EMA

by PipC· code credited to philchan2008

The Triple EMA vs 55 EMA strategy plots three exponential moving averages (lengths 8, 13, 21), a 65-period exponential moving average, a 200-period simple moving average, and Hull moving averages of length 55 on high and low.

View on GitHub

GitHub stars8on the repository
Pine versionv5runs as is
Lines of code328
Settings31inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago20 Aug 2022

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 strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

328 lines of Pine Script v5 from TradingView/Triple EMA vs 55 EMA.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Triple EMA vs 55 EMA.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © philchan2008

//@version=5
strategy("Triple EMA vs 55 EMA", shorttitle="3vs65EMA", overlay=true, margin_long=100, margin_short=100)

stopLossPrecent=input.float(title="Stop Loss Precentage %", step=0.5, defval=8)
stopBelowHMA55=input.bool(title="Stop Below HMA55", defval=true)
tradeMaxAmount = input.int(title="Trading Amount", step=1000, defval=10000)

lenA = input(8, title="EMA #A")
srcA = input(close, title="EMA Source #A")
outA = ta.ema(srcA, lenA)
plot(outA, title="EMA #A", color=close >= outA ? color.yellow : color.yellow, linewidth = 1)

lenB = input(13, title="EMA #B")
srcB = input(close, title="EMA Source #B")
outB = ta.ema(srcB, lenB)
plot(outB, title="EMA #B", color=close >= outB ? color.orange : color.orange, linewidth = 1)

lenC = input(21, title="EMA #C")
srcC = input(close, title="EMA Source #C")
outC = ta.ema(srcC, lenC)
plot(outC, title="EMA #C", color=close >= outC ? color.red : color.red, linewidth = 1)

lenD = input(65, title="EMA #D")
srcD = input(close, title="EMA Source #D")
outD = ta.ema(srcD, lenD)
plot(outD, title="EMA #D", color=close >= outD ? color.fuchsia : color.fuchsia, linewidth = 2)

lenE = input(200, title="SMA #E")
srcE = input(close, title="SMA Source #E")
outE = ta.sma(srcE, lenE)
plot(outE, title="SMA #E", color=close >= outE ? color.maroon : color.maroon, linewidth = 3)


lenH55H = input(55, title="HMA #H55H")
srcH55H = input(high, title="HMA Source #H55H")
outH55H = ta.hma(srcH55H, lenH55H)
plot55H=plot(stopBelowHMA55 ? outH55H : na, title="SMA #H55H", color=color.new(high >= outH55H ? ( outH55H > outH55H[1] ? color.lime : (high > outH55H ? color.white : color.silver) ) :  color.gray, 50), linewidth = 2, style=plot.style_circles)

lenH55L = input(55, title="HMA #H55L")
srcH55L = input(low)
outH55L = ta.hma(srcH55L, lenH55L)
plot55L=plot(stopBelowHMA55 ? outH55L : na, title="SMA #H55L", color=color.new(low >= outH55L ? ( outH55L > outH55L[1] ? color.lime : (low > outH55L ? color.white : color.silver) ) :  color.gray, 50), linewidth = 1, style=plot.style_circles)

outH55M=(outH55L+outH55H)/2
fill(plot55L, plot55H, color=color.new(close >=  outH55M ? ( outH55M > outH55M[1] ? color.lime : (close > outH55M ? color.white : color.silver) ) :  color.gray, 90), title='HMA 55 High-Low Fill')



STBuySignal = outA > outD and outB > outD and outC > outD
STSellSignal = outA < outD and outB < outD and outC < outD

//plotshape( STBuySignal  ? low: na, title="UpTrend Begins",   location=location.absolute, style=shape.triangleup,   size=size.tiny, color=color.green)
//plotshape( STSellSignal ? high : na, title="DownTrend Begins", location=location.absolute, style=shape.triangledown, size=size.tiny, color=color.red)


//bgColor = (trend_1 > 0 and trend_2 > 0 and trend_3 > 0)  and close > outE and close > ((trend_1 > 0 and trend_2 > 0 and trend_3 > 0)?outH55H:outH55L) ? color.new(color.lime,95) : color.new(color.red,95)
//bgcolor(bgColor)


if (STBuySignal) and (strategy.opentrades == 0) and (not stopBelowHMA55 or (stopBelowHMA55 and  close > outH55H ))
    //strategy.entry("B1", strategy.long, comment="B1", stop= high + syminfo.mintick, qty=tradeMaxAmount/high)
    strategy.entry("LE", direction=strategy.long, comment="LE", stop=high, qty=tradeMaxAmount/(high+syminfo.mintick)) //*(100-initStopLossPrecent)/100, qty=tradeMaxAmount/high)


if (STBuySignal) and (strategy.position_size > 0) //or (trend_1 > 0 and trend_2 > 0 and trend_3 > 0)
    strategy.order("LC", direction=strategy.short, qty=strategy.position_size, when=low < strategy.position_avg_price *(100-stopLossPrecent)/100)


if (STSellSignal) and (strategy.position_size > 0) // or ((recentHigh - close) / recentHigh) > longStopLossPrecent/100
    strategy.exit("XX", stop=low)

if stopBelowHMA55 and ( close < outH55L) and (strategy.position_size > 0) // or ((recentHigh - close) / recentHigh) > longStopLossPrecent/100
    strategy.exit("X55L", stop=outH55L)




if (ta.crossover(outC[1],outD[1]))
    var label _laBUY = na
    //label.delete(_laBUY)
    //if close > high[1]+syminfo.mintick
    _laBUY := label.new(x=time, y=outD, text=str.format("{1,number,#.#}%",outD,(1-outD/high)*100), xloc=xloc.bar_time, yloc=yloc.price, color=color.new(color.green,80), textcolor=color.green, size=size.small, style=label.style_label_upper_right)


if (ta.crossunder(outC[1],outD[1]))
    var label _laSELL = na
    //label.delete(_laSELL)
    if close < low[1]-syminfo.mintick
        _laSELL := label.new(x=time, y=outD, text=str.format("{1,number,#.#}%",outD,(1-outD/low)*100), xloc=xloc.bar_time, yloc=yloc.price, color=color.new(color.red,80), textcolor=color.red, size=size.small, style=label.style_label_lower_left)





///////////////////////////////////////////////////////////////////////////////////////////////////
//// INPUTS
///////////////////////////////////////////////////////////////////////////////////////////////////
vp_lookback   = input.int(defval = 200,
                     title   = "Volume Lookback Depth [10-1000]",
                     minval  = 10,
                     maxval  = 1000)

vp_max_bars   = input.int(defval = 500,
                     title   = "Number of Bars [10-500]",
                     minval  = 10,
                     maxval  = 500)

vp_bar_mult   = input.int(defval = 50,
                     title   = "Bar Length Multiplier [10-100]",
                     minval  = 10,
                     maxval  = 100)

vp_bar_offset = input.int(defval = 50,
                     title   = "Bar Horizontal Offset [0-100]",
                     minval  = 0,
                     maxval  = 100)

vp_bar_width  = input.int(defval = 2,
                     title   = "Bar Width [1-20]",
                     minval  = 1,
                     maxval  = 20)

// As suggested by @NXT2017
vp_delta_type = input.string(defval = "Both",
                     title   = "Delta Type",
                     options = ['Both', 'Bullish', 'Bearish'])

vp_poc_show   = input.bool(defval = true,
                     title   = "Show POC Line")

vp_bar_color  = input.color(defval = color.new(color.gray, 80) ,
                     title   = "Bar Color")

vp_poc_color  = input.color(defval = color.new(color.white, 30),
                     title   = "POC Color")


///////////////////////////////////////////////////////////////////////////////////////////////////
//// VARIABLES
///////////////////////////////////////////////////////////////////////////////////////////////////
float vp_Vmax = 0.0
int vp_VmaxId = 0
int vp_N_BARS = vp_max_bars

var int vp_first = time

vp_a_P = array.new_float((vp_N_BARS + 1), 0.0)
vp_a_V = array.new_float(vp_N_BARS, 0.0)
vp_a_D = array.new_float(vp_N_BARS, 0.0)
vp_a_W = array.new_int(vp_N_BARS, 0)

///////////////////////////////////////////////////////////////////////////////////////////////////
//// CALCULATIONS
///////////////////////////////////////////////////////////////////////////////////////////////////
float vp_HH = ta.highest(high, vp_lookback)
float vp_LL = ta.lowest(low, vp_lookback)

if barstate.islast
    float vp_HL = (vp_HH - vp_LL) / vp_N_BARS
    for j = 1 to (vp_N_BARS + 1)
        array.set(vp_a_P, (j-1), (vp_LL + vp_HL * j))
    for i = 0 to (vp_lookback - 1)
        int Dc = 0
        array.fill(vp_a_D, 0.0)
        for j = 0 to (vp_N_BARS - 1)
            float Pj = array.get(vp_a_P, j)
            if low[i] < Pj and high[i] > Pj and (vp_delta_type == "Bullish" ?
             close[i] >= open[i] : (vp_delta_type == "Bearish" ? close[i] <= open[i] : true))
                float Dj = array.get(vp_a_D, j)
                float dDj = Dj + nz(volume[i])
                array.set(vp_a_D, j, dDj)
                Dc := Dc + 1
        for j = 0 to (vp_N_BARS - 1)
            float Vj = array.get(vp_a_V, j)
            float Dj = array.get(vp_a_D, j)
            float dVj = Vj + ((Dc > 0) ? (Dj / Dc) : 0.0)
            array.set(vp_a_V, j, dVj)
    vp_Vmax := array.max(vp_a_V)
    vp_VmaxId := array.indexof(vp_a_V, vp_Vmax)
    for j = 0 to (vp_N_BARS - 1)
        float Vj = array.get(vp_a_V, j)
        int Aj = math.round(vp_bar_mult * Vj / vp_Vmax)
        array.set(vp_a_W, j, Aj)

///////////////////////////////////////////////////////////////////////////////////////////////////
//// PLOTING
///////////////////////////////////////////////////////////////////////////////////////////////////
if barstate.isfirst
    vp_first := time
vp_change = ta.change(time)
vp_x_loc = timenow + math.round(vp_change * vp_bar_offset)

f_setup_bar(n) =>
    x1 = ((vp_VmaxId == n) and vp_poc_show) ? math.max(time[vp_lookback], vp_first) :
         (math.round(vp_change * (vp_bar_offset - array.get(vp_a_W, n))) + timenow)
    ys = array.get(vp_a_P, n)
    line.new(x1     = x1,
             y1     = ys,
             x2     = vp_x_loc,
             y2     = ys,
             xloc   = xloc.bar_time,
             extend = extend.none,
             color  = (vp_VmaxId == n ? vp_poc_color : vp_bar_color),
             style  = line.style_solid,
             width  = vp_bar_width)

if barstate.islast
    for i = 0 to (vp_N_BARS - 1) by 1
        f_setup_bar(i)

///////////////////////////////////////////////////////////////////////////////////////////////////
//// END
///////////////////////////////////////////////////////////////////////////////////////////////////


// User Options
vwapLookbackDays = input.int(title="VWAP Anchor Lookback (days)",  defval=55)

// Functions
var now = last_bar_time
getTotalLookbackDays(lookbackWeekdays) =>
    // Calculate actual lookback days from weekdays
    int lookbackDays = lookbackWeekdays
    int currentWeekday = dayofweek(now)-1
    if (lookbackWeekdays > currentWeekday)
        int weekdaysEachWeek = 5
        int weekendDaysEachWeek = 2
        int weekendsToOffset = math.ceil((lookbackWeekdays - currentWeekday) / weekdaysEachWeek)
        int offsetWeekendDays = weekendDaysEachWeek * weekendsToOffset
        lookbackDays := offsetWeekendDays + lookbackWeekdays
    lookbackDays
isNewPeriod(res) =>
    // Helper function for finding new bars/periods by resolution
    t = time(res)
    newbar = not na(t) and (na(t[1]) or t > t[1])

// Calculate beginning and ending range for VWAP
int lookback = getTotalLookbackDays(vwapLookbackDays)
milliseconds_in_lookback_days = 1000 * 60 * 60 * 24 * lookback
leftborder = now - time < milliseconds_in_lookback_days
rightborder = barstate.islast

// VWAP Variables
float cumulativePV = na
float cumulativeVOL = na
float multiDayVWAP = na
bool newDay = isNewPeriod("D")
var startedNewPeriod = false
bool insideLookbackRange = (leftborder and not rightborder) or rightborder

// Start plotting new VWAP period if it's a new day, inside our lookback range, and only if we haven't already started a new period
bool startNewPeriod = newDay and insideLookbackRange and not startedNewPeriod
if (startNewPeriod)
    startedNewPeriod := true

// Calculate cumulative totals & VWAP as documented below
// VWAP Docs: https://www.investopedia.com/terms/v/vwap.asp
cumulativePV := startNewPeriod ? (hlc3 * volume) : (cumulativePV[1] + hlc3 * volume)
cumulativeVOL := startNewPeriod ? volume : (cumulativeVOL[1] + volume)
multiDayVWAP := (cumulativePV / cumulativeVOL)

// Plots
plot(insideLookbackRange ? multiDayVWAP : na, title="VWAP (RM)", color=color.new(#ffffff,30), linewidth=1, style=plot.style_stepline)

var label _laVWAP = na
label.delete(_laVWAP)
_laVWAP := label.new(x=time+1, y=multiDayVWAP, text=str.format("{1,number,#.#}% VWAP ${0,number,#.##}",multiDayVWAP,(close-multiDayVWAP)/close*100), xloc=xloc.bar_time, yloc=yloc.price, color=color.new(color.white,80), textcolor=color.white, size=size.small, style=label.style_label_left)
label.set_x(_laVWAP, label.get_x(_laVWAP) + math.round(ta.change(time)*1.5))
label.delete(_laVWAP[1])



if (stopBelowHMA55)
    var label _la55STP = na
    label.delete(_la55STP)
    _la55STP := label.new(x=time+1, y=(STBuySignal?outH55L:outH55H), text=str.format("{1,number,#.#}% H55STP ${0,number,#.##}",(STBuySignal?outH55L:outH55H), 100*(1-(STBuySignal?outH55L:outH55H)/close)), xloc=xloc.bar_time, yloc=yloc.price, color=color.new(color.yellow, 20), textcolor=color.black, size=size.small, style=label.style_label_left)
    label.set_x(_la55STP, label.get_x(_la55STP) + math.round(ta.change(time)*2))
    label.delete(_la55STP[1])

var label _laSTP = na
label.delete(_laSTP)
_laSTP := label.new(x=time+1, y=close*(1-stopLossPrecent/100), text=str.format("{0,number,#.#}% STP ${1,number,#.##}",stopLossPrecent,close*(1-stopLossPrecent/100)), xloc=xloc.bar_time, yloc=yloc.price, color=color.new(color.fuchsia,30), textcolor=color.white, size=size.small, style=label.style_label_upper_left)
label.set_x(_laSTP, label.get_x(_laSTP) + math.round(ta.change(time)*2))
label.delete(_laSTP[1])



showTradingTable=input.bool(title="Show Trading Table", defval=true)
TradingTableLayout=input.string(title="Trading Table Layout", defval="2x3", options=["1x6","6x2","2x3"])
TradingTablePosition=input.string(title="Trading Table Position", defval=position.top_right, options=[position.bottom_center, position.bottom_left, position.bottom_right, position.middle_center, position.middle_left, position.middle_right, position.top_center, position.top_left, position.top_right])
TradingTableSize=input.string(title="Trading Table Size", defval=size.normal, options=[size.auto, size.huge, size.large, size.normal, size.small, size.tiny])
if showTradingTable
    var label _laTradeSize = na
    label.delete(_laTradeSize)
    var _orderPrice = close
    _orderPrice := close
    var _orderSize = math.round(tradeMaxAmount/_orderPrice,0)
    _orderSize := math.round(tradeMaxAmount/_orderPrice,0)
    //_laTradeSize := label.new(x=time+1, y=ta.highest(high,20), text=str.format("Order Size {0,number,#} | ${1,number,#.##} / ${2,number,#.##}", _orderSize, _orderSize*_orderPrice, _orderPrice), xloc=xloc.bar_time, yloc=yloc.price, color=color.white, textcolor=color.black, size=size.small, style=label.style_label_lower_left)
    //label.set_x(_laTradeSize, label.get_x(_laTradeSize) + math.round(ta.change(time)*1.5))
    //label.delete(_laTradeSize[1])
    if TradingTableLayout == "6x2"
        var tbl = table.new(position=TradingTablePosition, rows=6, columns=2, border_width = 1)
        table.cell(tbl, 0, 0, 'Entry Price', bgcolor=color.new(#cccccc, 20), text_size=TradingTableSize)
        table.cell(tbl, 1, 0, str.tostring(_orderPrice, "$#.##"), bgcolor=color.new(color.yellow, 20), text_size=TradingTableSize)
        table.cell(tbl, 0, 1, 'Total Cost', bgcolor=#cccccc, text_size=TradingTableSize)
        table.cell(tbl, 1, 1, str.tostring(_orderSize*_orderPrice, "$#.#"), bgcolor=color.new(color.yellow, 20), text_size=TradingTableSize)
        table.cell(tbl, 0, 2, 'Order Size', bgcolor=color.new(#cccccc, 20), text_size=TradingTableSize)
        table.cell(tbl, 1, 2, str.tostring(_orderSize, "#.#"), bgcolor=color.white, text_size=TradingTableSize)
    if TradingTableLayout == "1x6"
        var tbl = table.new(position=TradingTablePosition, rows=1, columns=6, border_width = 1)
        table.cell(tbl, 0, 0, 'Entry Price', bgcolor=color.new(#cccccc, 20), text_size=TradingTableSize)
        table.cell(tbl, 1, 0, str.tostring(_orderPrice, "$#.##"), bgcolor=color.new(color.yellow, 20), text_size=TradingTableSize)
        table.cell(tbl, 2, 0, 'Total Cost', bgcolor=#cccccc, text_size=TradingTableSize)
        table.cell(tbl, 3, 0, str.tostring(_orderSize*_orderPrice, "$#.#"), bgcolor=color.new(color.yellow, 20), text_size=TradingTableSize)
        table.cell(tbl, 4, 0, 'Order Size', bgcolor=color.new(#cccccc, 20), text_size=TradingTableSize)
        table.cell(tbl, 5, 0, str.tostring(_orderSize, "#.#"), bgcolor=color.white, text_size=TradingTableSize)
    if TradingTableLayout == "2x3"
        var tbl = table.new(position=TradingTablePosition, rows=2, columns=3, border_width = 1)
        table.cell(tbl, 0, 0, 'Entry Price', bgcolor=color.new(#cccccc, 20), text_size=TradingTableSize)
        table.cell(tbl, 0, 1, str.tostring(_orderPrice, "$#.##"), bgcolor=color.new(color.yellow, 20), text_size=TradingTableSize)
        table.cell(tbl, 1, 0, 'Total Cost', bgcolor=#cccccc, text_size=TradingTableSize)
        table.cell(tbl, 1, 1, str.tostring(_orderSize*_orderPrice, "$#.#"), bgcolor=color.new(color.yellow, 20), text_size=TradingTableSize)
        table.cell(tbl, 2, 0, 'Order Size', bgcolor=color.new(#cccccc, 20), text_size=TradingTableSize)
        table.cell(tbl, 2, 1, str.tostring(_orderSize, "#.#"), bgcolor=color.white, text_size=TradingTableSize)

Overview

Triple EMA vs 55 EMA fills the area between the HMA high and low lines on the price chart. Buy signals trigger when all three EMAs are above the 65 EMA, sell signals when below. The strategy enters long positions on buy signals with no open trades, using a stop loss at the current high price and fixed position size of 10000 units. Inputs control stop loss percentage, stop below HMA55 option, trading amount, and all EMA lengths. Plots appear directly on the price chart with no separate pane. No exit rules are defined beyond the buy signal logic.

Details

Published by

PipC on GitHub

Code credit

philchan2008, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Moving averages, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Stop Loss Precentage %float8stopLossPrecent
Stop Below HMA55booltruestopBelowHMA55
Trading Amountint10000tradeMaxAmount
EMA #Aint8lenA
EMA Source #AsourceclosesrcA
EMA #Bint13lenB
EMA Source #BsourceclosesrcB
EMA #Cint21lenC
EMA Source #CsourceclosesrcC
EMA #Dint65lenD
EMA Source #DsourceclosesrcD
SMA #Eint200lenE
Show all 31 settings
SettingTypeDefaultVariable
SMA Source #EsourceclosesrcE
HMA #H55Hint55lenH55H
HMA Source #H55HsourcehighsrcH55H
HMA #H55Lint55lenH55L
srcH55LsourcelowsrcH55L
Volume Lookback Depth [10-1000]int200vp_lookback
Number of Bars [10-500]int500vp_max_bars
Bar Length Multiplier [10-100]int50vp_bar_mult
Bar Horizontal Offset [0-100]int50vp_bar_offset
Bar Width [1-20]int2vp_bar_width
Delta TypestringBothvp_delta_type
Show POC Linebooltruevp_poc_show
Bar Colorcolorcolor.new(color.gray, 80)vp_bar_color
POC Colorcolorcolor.new(color.white, 30)vp_poc_color
VWAP Anchor Lookback (days)int55vwapLookbackDays
Show Trading TablebooltrueshowTradingTable
Trading Table Layoutstring2x3TradingTableLayout
Trading Table Positionstringposition.top_rightTradingTablePosition
Trading Table Sizestringsize.normalTradingTableSize
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

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated today · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers