Indicator · Pine Script v4 · On the chart

EMA Strategy

by capissimo

Calculates a central Exponential Moving Average with upper and lower channel bands offset by a fixed pip distance, inspired by LazyBear's Pip Collector script.

View on GitHub

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

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

098-EMA-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("EMA Strategy", '', true, precision=4)

// EMA Strategy aka Pip Collector Mod

// This script was inspired by LazyBear's popular script
// called Pip collector. It features custom signal generation
// and information section displaying elapsed bar time useful 
// for timing trades.

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

ds           = input(close, 'Dataset')
lengthCenter = input(50,    'Center EMA Length |1..n|', minval=1, maxval=2160)
length       = input(20,    'Upper/Lower Distance from Center (PIPs) |-n..n|')
fltr         = input(true,  'Filter Out Signals 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
             
//-------------------- Logic

pip     = syminfo.mintick 

ma    = ema(ds, lengthCenter)
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

Generates buy and sell signals when price interacts with the envelope bands, with an optional ATR volatility filter. Positions automatically exit after a user-defined holding period counted in bars. Plots the EMA, envelope bounds, trade signals, and exit points directly on the price chart alongside a real-time bar completion label.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Trend, 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
Datasetsourcecloseds
Center EMA Length |1..n|int50lengthCenter
Upper/Lower Distance from Center (PIPs) |-n..n|int20length
Filter Out Signals 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

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