//@version=2
//==@version=5
strategy("EMA-BB", overlay=true)
length = input(title="Length of EMA", type=integer, defval=20)
ema = ema(close, length)
upper = bollinger(close, length, 2)
lower = bollinger(close, length, -2)
// enter long trade when the price cross above EMA
// and is within the upper Bollinger Band
enterLong = crossover(close, ema) and close < upper
// enter short trade when the price cross below EMA
// and is within the lower Bollinger Band
enterShort = crossunder(close, ema) and close > lower
// exit long trades when price cross below EMA
exitLong = crossunder(close, ema)
// exit short trades when price cross above EMA
exitShort = crossover(close, ema)
// plot EMA and Bands
plot(ema, title="EMA", color=blue)
plot(upper, title="Upper Band", color=red)
plot(lower, title="Lower Band", color=green)
// enter and exit trades
if (enterLong)
strategy.entry("long", strategy.long)
if (enterShort)
strategy.entry("short", strategy.short)
if (exitLong)
strategy.close("long")
if (exitShort)
strategy.close("short")