2 Ema Pullback Strategy
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Germangroa

//@version=5
indicator("2 Ema Pullback Strategy", overlay=true)



//============= Time Frame============
//startDate   = input.time(title="Start Date", defval=timestamp("01 Jan 2010 13:30 +0000"), group="Tme Frame", tooltip="Date & time to begin analysis")
//endDate     = input.time(title="End Date", defval=timestamp("1 Jan 2099 19:30 +0000"), group="Tme Frame", tooltip="Date & time to stop analysis")
//timeSession = input.session(title="Time Session To Analyze", defval="0600-0915", group="Tme Frame", tooltip="Time session to analyze volatility")
//colorBG     = input.bool(title="Color Background?", defval=true, group="Tme Frame", tooltip="Change the background color based on whether the current bar falls within the given session?")

// This function returns true if the current bar falls within the given time session (:1234567 is to include all weekdays)
//inSession(sess) => na(time(timeframe.period, sess + ":1234567")) == false and time >= startDate and time <= endDate
//bgcolor(inSession(timeSession) and colorBG ? color.rgb(158, 230, 245, 90) : na)

//=== Check if a new session has begun
//var withinSession = false
//if inSession(timeSession) and not inSession(timeSession)[1]
//    withinSession := true



//=======  User input  ========
//EMA 1
res1 = input.timeframe(title='EMA 1 Time Frame', defval='60', group="Long EMA")
len1 = input(title='EMA 1 Length', defval=26, group="Long EMA")
//col = input(title='Color', defval=true, group="Long EMA")
smooth1 = input(title='Smooth ?', defval=true, group="Long EMA")

//EMA 2
res2 = input.timeframe(title='EMA 2 Time Frame', defval='60', group="Short EMA")
len2 = input(title='EMA 2 Length', defval=12, group="Short EMA")
//col = input(title='Color', defval=true, group="Short EMA")
smooth2 = input(title='Smooth ?', defval=true, group="Short EMA")




//=======  Calculate EMAs  ========
//EMA 1
ema1 = ta.ema(close, len1)
emaSmooth1 = request.security(syminfo.tickerid, res1, ema1, barmerge.gaps_on, barmerge.lookahead_off)
emaStep1 = request.security(syminfo.tickerid, res1, ema1, barmerge.gaps_off, barmerge.lookahead_off)


//EMA 2
ema2 = ta.ema(close, len2)
emaSmooth2 = request.security(syminfo.tickerid, res2, ema2, barmerge.gaps_on, barmerge.lookahead_off)
emaStep2 = request.security(syminfo.tickerid, res2, ema2, barmerge.gaps_off, barmerge.lookahead_off)

ematest1 = emaSmooth1
ematest2 = emaSmooth2
ematest1 := not na(emaSmooth1) ? emaSmooth1 : ematest1[1]
ematest2 := not na(emaSmooth2) ? emaSmooth2 : ematest2[1]


UPtrend = ematest2 > ematest1
DOWNtrend = ematest2 < ematest1






//Draw EMA
plot(smooth1 ? ematest1 : emaStep1, color=color.new(color.red, 40), linewidth=4, title='EMA 1', offset=15)
plot(smooth2 ? ematest2 : emaStep2, color=color.new(color.blue, 40), linewidth=2, title='EMA 2', offset=15)



//================ Stoch RSI ==================
smoothK = input.int(3, "K", minval=1)
smoothD = input.int(3, "D", minval=1)
lengthRSI = input.int(14, "RSI Length", minval=1)
lengthStoch = input.int(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)


LongStrength = k > d
ShortStrength = k < d


//=========== RSI =====================
ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "Bollinger Bands" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(14, title="MA Length", group="MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings")

up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA = ma(rsi, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"

//==Fist Opction
//Xover = (ta.crossover(rsi, 30) and rsi[1] < rsi) or (ta.crossover(rsi, rsiMA)  and rsi[1] < rsi)
//Xunder = (ta.crossunder(rsi, 70) and rsi[1] > rsi) or (ta.crossunder(rsi, rsiMA) and rsi[1] > rsi)

//==2nd Option                    <--------   Evaluate
Xover = rsi < 50 and rsi[1] < rsi
Xunder = rsi > 50 and rsi[1] > rsi

//======  'Directional Movement Index + ADX   =======

adxlen = input(14, title='ADX Smoothing')
dilen = input(14, title='DI Length')
keyLevel = input(23, title='key level for ADX')
dirmov(len) =>
    Uppp = ta.change(high)
    Downnnn = -ta.change(low)
    truerange = ta.rma(ta.tr, len)
    plus = fixnan(100 * ta.rma(Uppp > Downnnn and Uppp > 0 ? Uppp : 0, len) / truerange)
    minus = fixnan(100 * ta.rma(Downnnn > Uppp and Downnnn > 0 ? Downnnn : 0, len) / truerange)
    [plus, minus]

adx(dilen, adxlen) =>
    [plus, minus] = dirmov(dilen)
    sum = plus + minus
    adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
    [adx, plus, minus]

[sig, Uppp, Downnnn] = adx(dilen, adxlen)

BuyerStrength = Uppp > Uppp[1] and Downnnn < Downnnn[1]
SellersStrength = Uppp < Uppp[1] and Downnnn > Downnnn[1]


//========== Volume from Waddah Attar Explosion V2 =======

sensitivity = 150
fastLength = 28
slowLength = 40
channelLength =20
mult = 2.0

DEAD_ZONE = nz(ta.rma(ta.tr(true), 100)) * 3.7

calc_macd(source, fastLength, slowLength) =>
    fastMA = ta.ema(source, fastLength)
    slowMA = ta.ema(source, slowLength)
    fastMA - slowMA

calc_BBUpper(source, length, mult) =>
    basis = ta.sma(source, length)
    dev = mult * ta.stdev(source, length)
    basis + dev

calc_BBLower(source, length, mult) =>
    basis = ta.sma(source, length)
    dev = mult * ta.stdev(source, length)
    basis - dev

t1 = (calc_macd(close, fastLength, slowLength) - calc_macd(close[1], fastLength, slowLength)) * sensitivity

e1 = calc_BBUpper(close, channelLength, mult) - calc_BBLower(close, channelLength, mult)

trendUp = t1 >= 0 ? t1 : 0
trendDown = t1 < 0 ? -1 * t1 : 0

HighVolume = trendUp > DEAD_ZONE or trendDown > DEAD_ZONE
HighVolume123 = HighVolume or HighVolume[1] or HighVolume[2] or HighVolume[3]


//======== Price above 2nd EMA =======
CandleUp = ta.highest(5) > emaSmooth2
CandleUp12345 = CandleUp or CandleUp[1] or CandleUp[2] or CandleUp[3] or CandleUp[4] or CandleUp[5]

//========== Plots & Entrys =========

lo = LongStrength and Xover and BuyerStrength and HighVolume123 
sh = ShortStrength and Xunder and SellersStrength and HighVolume123 //and CandleUp



Long = lo and UPtrend and (low < ematest2 or low < ematest2[1] or low < ematest2[2] or low < ematest2[3] or low < ematest2[4])
Short = sh and DOWNtrend and (high > ematest2 or high > ematest2[1] or high > ematest2[2] or high > ematest2[3] or high > ematest2[4])

plotshape(Long ? close : na, style=shape.triangleup, color=color.new(color.green, 0),
     location=location.belowbar, title='Bullish Signal', text="L", textcolor=color.new(color.white, 0))
plotshape(Short ? close : na, style=shape.triangledown, color=color.new(color.purple, 0),
     location=location.abovebar, title='Bearish Signal',  text='S', textcolor=color.new(color.white, 0))


