MPF EMA Cross Strategy (8~13~21) by Market Pip Factory
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Market-Pip-Factory
//@version=4

study("MPF EMA Cross Strategy (8~13~21) by Market Pip Factory", shorttitle = "MPF EMA Cross Strategy", overlay=true)
// Draw 3x EMAs
// Provide editable parameters
ema1 = input(8)
ema2 = input(13)
ema3 = input(21)

// Set EMA type
ema1_ = ema(close, ema1)
ema2_ = ema(close, ema2)
ema3_ = ema(close, ema3)

// Draw EMAs on chart
plot(ema1_, color=color.red, linewidth=2, title="EMA 1")
plot(ema2_, color=color.blue, linewidth=2, title="EMA 2")
plot(ema3_, color=color.orange, linewidth=2, title="EMA 3")

// Set Parameters for Alerts and Draw Bullish & Bearish Shapes
Bullish = crossover(ema1_,ema3_)
plotshape(Bullish, style=shape.triangleup, color=color.green, location=location.belowbar, size=size.small, text="EMA\n CROSS", title="Bullish Trend EMA Cross")
Bearish = crossunder(ema1_,ema3_)
plotshape(Bearish, style=shape.triangledown, color=color.red, location=location.abovebar, size=size.small, text="EMA\n CROSS", title="Bearish Trend EMA Cross")

// ema color
ema0_ = ema1_ > ema3_ ? color.new(color.green,0) : color.new(color.red,0)

// Color Asignment for Trends
colorTrend = ema1_ > ema3_ ? color.new(color.green,0) : ema1_ < ema3_ ? color.new(color.red,0) : color.new(color.gray,0)

// Trend Calc
trendCalcBull = ema1_ > ema3_
trendCalcBear = ema3_ > ema1_

//Bullish Trend = EMA8 > EMA21 = crossover
//Bearish Trend = EMA21 > EMA8 = crossunder
//Check on DAILY and 4HOURLY for confirmations
PrepCandleL = ema1_ > ema3_
PrepCandleS = ema3_ > ema1_

//-------------------------------------------------------------------------------------
// Market Session Parameters (Set for ICT London ~ New York ONLY)
// Comment out if you want 24 hours active
// Get user input
session = input(title="Time session", type=input.session, defval="0930-2330")
// Create function for detecting if current bar falls within specified time period
InSession(sess) => na(time(timeframe.period, sess)) == false
// Check if the current bar falls within pre-determined market session
isInSession = InSession(session)
// Change bar color if bar falls within after hours time
barcolor(isInSession ? color.orange : na)
// Trigger alert only if bar is outside of after hours time
alertTrigger = close >= open
alertcondition(alertTrigger and isInSession, title="Alert title", message="Alert message")
//-------------------------------------------------------------------------------------

// Strategy notes for feature additions:
// SHORTS
// If PrepCandle = EMA21 > EMA8 and CandlePrice > EMA8 then draw red X (Preparatory Candle)
//plotshape(PrepCandleS, style=shape.xcross, color=color.red, location=location.abovebar, size=size.tiny, text="SHORT-PREP", title="Short Preparatory Candle")

// LONGS
// If PrepCandle = EMA8 > EMA21 and CandlePrice < EMA8 then draw green x (Preparatory Candle)
//plotshape(PrepCandleL, style=shape.xcross, color=color.green, location=location.belowbar, size=size.tiny, text="LONG-PREP", title="Long Preparatory Candle")

//-------------------------------------------------------------------------------------
// FOREX STUFF
// Trancate Math Function
truncate(_number, _decimalPlaces) =>
    _factor = pow(10, _decimalPlaces)
    int(_number * _factor) / _factor

// Forex ONLY converter from pips into whole numbers math
atr = atr(14)
toWhole(number) =>
    if syminfo.type == "forex" // ONLY for forex
        return = atr < 1.0 ? (number / syminfo.mintick) / 10 : number
        return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return * 100 : return
    else
        number
//-------------------------------------------------------------------------------------

// MultiTimeframes Section
// Set Timeframe Parameters
res_d = input(title="EMA Cross Daily TF", type=input.resolution, defval="1440")
res_4h = input(title="EMA Cross 4H TF", type=input.resolution, defval="240")
res_1h = input(title="EMA Cross 1H TF", type=input.resolution, defval="60")
//smooth = input(title="Smooth", type=input.bool, defval=true)

// MultiTimeFrame Data
ema_d_smooth_l = security(syminfo.tickerid, res_d, trendCalcBull, barmerge.gaps_off, barmerge.lookahead_off)
ema_4h_smooth_l = security(syminfo.tickerid, res_4h, trendCalcBull, barmerge.gaps_off, barmerge.lookahead_off)
ema_1h_smooth_l = security(syminfo.tickerid, res_1h, trendCalcBull, barmerge.gaps_on, barmerge.lookahead_off)
ema_d_smooth_s = security(syminfo.tickerid, res_d, trendCalcBear, barmerge.gaps_off, barmerge.lookahead_off)
ema_4h_smooth_s = security(syminfo.tickerid, res_4h, trendCalcBear, barmerge.gaps_off, barmerge.lookahead_off)
ema_1h_smooth_s = security(syminfo.tickerid, res_1h, trendCalcBear, barmerge.gaps_on, barmerge.lookahead_off)

candleOnEma_1h_l = 0
candleOnEma_1h_s = 1
setup_prep_l = ema_d_smooth_l and ema_4h_smooth_l and ema_1h_smooth_l
setup_prep_s = ema_d_smooth_s and ema_4h_smooth_s and ema_1h_smooth_s
setup_l = setup_prep_l and candleOnEma_1h_l
setup_s = setup_prep_s and candleOnEma_1h_s
priceOn21ema = 3

// Color Data
color_filter_daily = ema_d_smooth_l ? color.new(color.green,0) : ema_d_smooth_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_4h = ema_4h_smooth_l ? color.new(color.green,0) : ema_4h_smooth_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_1h = ema_1h_smooth_l ? color.new(color.green,0) : ema_1h_smooth_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_overall = ema_d_smooth_l and ema_4h_smooth_l and ema_1h_smooth_l ? color.new(color.green,0) : ema_d_smooth_s and ema_4h_smooth_s and ema_1h_smooth_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_candleOnEma = candleOnEma_1h_l ? color.new(color.green,0) : candleOnEma_1h_s ? color.new(color.red,0) : color.new(color.gray,0)
color_filter_setup = setup_l ? color.new(color.orange,0) : setup_s ? color.new(color.blue,0) : color.new(color.gray,0)

// Long & Short Labels
trendLabel_d = ema_d_smooth_l ? "LONG" : ema_d_smooth_s ? "SHORT" : "WAITING"
trendLabel_4h = ema_4h_smooth_l ? "LONG" : ema_4h_smooth_s ? "SHORT" : "WAITING"
trendLabel_1h = ema_1h_smooth_l ? "LONG" : ema_1h_smooth_s ? "SHORT" : "WAITING"
candleOnEmaLabel_1h = candleOnEma_1h_l ? "LONG SETUP" : candleOnEma_1h_s ? "SHORT SETUP" : "NO SETUP"
setupLabel_1h = setup_l ? "LONG ACTIVATED" : setup_s ? "SHORT ACTIVATED" : "NO SETUP"

// Trend Confirmation x3 Charts
trendConfirm = ema_d_smooth_l and ema_4h_smooth_l and ema_1h_smooth_l ? "LONG TREND CONFIRMED" : ema_d_smooth_s and ema_4h_smooth_s and ema_1h_smooth_s ? "SHORT TREND CONFIRMED" : "UNCONFIRMED"
trendAlarmConfirm_Bull = ema_d_smooth_l and ema_4h_smooth_l and ema_1h_smooth_l
trendAlarmConfirm_Bear = ema_d_smooth_s and ema_4h_smooth_s and ema_1h_smooth_s

// Draw Tables for display top right hand side of chart/screen
var table outputTable = table.new(position.top_right, 5, 2, border_width=1)
if barstate.isconfirmed
    dailytxt = "DAILY TREND\n" + trendLabel_d
    fourhourtxt = "4H TREND\n" + trendLabel_4h
    onehourtxt = "1H TREND\n" + trendLabel_1h
    slval = "STOP LOSS\n"
    entryval = "ENTRY PRICE\n"
    candleHitEma = "Candle On 8EMA\n" + candleOnEmaLabel_1h
    setup = "SETUP\n" + setupLabel_1h
    trend = "OVERALL TREND\n" + trendConfirm
    table.cell(outputTable, 0, 0, text=dailytxt, bgcolor=color_filter_daily, text_color=color.white)
    table.cell(outputTable, 1, 0, text=fourhourtxt, bgcolor=color_filter_4h, text_color=color.white)
    table.cell(outputTable, 2, 0, text=onehourtxt, bgcolor=color_filter_1h, text_color=color.white)
    table.cell(outputTable, 3, 0, text=trend, bgcolor=color_filter_overall, text_color=color.white)
    table.cell(outputTable, 0, 1, text=entryval, bgcolor=color.black, text_color=color.white)
    table.cell(outputTable, 1, 1, text=slval, bgcolor=color.black, text_color=color.white)
    table.cell(outputTable, 2, 1, text=candleHitEma, bgcolor=color.black, text_color=color.white)
    table.cell(outputTable, 3, 1, text=setup, bgcolor=color.black, text_color=color.white)
plot(close)

// Set Alerts Bullish and Bearish Trends
alertcondition(trendAlarmConfirm_Bull, title='Bullish Trend Confirmation', message='Bullish Trend Alert')
alertcondition(trendAlarmConfirm_Bear, title='Bearish Trend Confirmation', message='Bearish Trend Alert')

//-------------------------------------------------------------------------------------
// Add strategy system to activate preparatory candle on first touch of 8EMA

// 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 colorGB ? color.rgb(0, 0, 255, 90) : na)

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

// Check if session has ended
//if not inSession(timeSession) and inSession(timeSession)[1]
//    withinSession := false
    // Analyse Movement
//    recentMovement := highestHigh - lowestLow
//    totalMovement := totalMovement + recentMovement
//    sessionsCounted := sessionsCounted + 1
    // Reset stored high/low
//    highestHigh := -1.0
//    lowestLow := MAXINT

// Get highest high and lowest low of current session
//if withinSession
//    if high > highestHigh
//        highestHigh := high
//    if low < lowestLow
//        lowestLow := low

//longCondition = crossover(sma(close, 14), sma(close, 28))
//if (longCondition)
//    strategy.entry("My Long Entry Id", strategy.long)
//shortCondition = crossunder(sma(close, 14), sma(close, 28))
//if (shortCondition)
//    strategy.entry("My Short Entry Id", strategy.short)

// ————— Method 1: wait until bar following order and use its open.
//var float entryPrice = na
//if longCondition[1] or shortCondition[1]
//    entryPrice := open
//plot(entryPrice, "Method 1", color.orange, 3, plot.style_circles)

// ————— Method 2: use built-in variable.
//plot(strategy.position_avg_price, "Method 2", color.gray, 1, plot.style_circles, transp = 0)

// Add strategy system to deactivate preparatory candle if price action touches 21EMA
// Add strategy system to activate trade (long and short) on preparatory candle rules confirmed
// Add strategy system to add trailing stop on 5th previous candle high/low +3 pips (pip value editable)
// Add strategy check to not enable more than one trade per pair at a time
// Add strategy check to not activate more than one trade per EMA cross

// Add strategy system to set stop loss at break even upon X number of pips (editable)
// Add strategy system to close trade upon opposite EMA cross
// Add strategy system to incorporate cipher twister into preparatory parameters prior to trade being executed (which will stop trades when market goes sideways)