McGinley Dynamic Indicator 
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LucasZancheta

//@version=4
strategy(shorttitle="Maguila", title="McGinley Dynamic Indicator", overlay=true)

//Médias móveis
MA1Period=input(21, title="MA1")
MA2Period=input(42, title="MA2")

MA1 = ema(close, MA1Period)
MA2 = ema(close, MA2Period)

aboveAverage = MA1 >= MA2
hunderAverage = MA2 >= MA1

//Período do backtest
startDate = input(title="Start Date", type=input.integer, defval=28, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer, defval=5, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer, defval=2019, minval=1800, maxval=2100)

endDate = input(title="End Date", type=input.integer, defval=28, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer, defval=5, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer, defval=2020, minval=1800, maxval=2100)

//Verifica se o candle está dentro do período do backtest
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))

//Número de periodos da média móvel
period  = input(title="Períodos", type=input.integer, defval=20)
//Constante K (0.6)
k = input(title="Constante K", type=input.float, defval=0.6)
//Preço de fechamento 
closePrice = input(title="Preço", type=input.source, defval=close)

mdi = 0.0

//Fórmula de McGinley
mdi := na(mdi[1]) ? closePrice : mdi[1] + (closePrice - mdi[1]) / max((k * period * pow(closePrice / mdi[1], 4)), 1)

//Regra de coloração 
mdiColor = closePrice > mdi ? color.green : closePrice < mdi ? color.red : color.black

//Inserindo as informações no gráfico    
plot(MA1, color=color.blue, linewidth=2)
plot(MA2, color=color.purple, linewidth=2)

barcolor(mdiColor)

//Estratégia
buySignal = aboveAverage and closePrice > mdi and crossunder(low, MA1) and close > MA1  
buyLoss = closePrice < mdi and close < MA1 and close < MA2

if (inDateRange)
    strategy.entry("Compra", strategy.long, qty=1, when= buySignal)
    strategy.exit("Gain da compra", "Compra", qty=1, profit=20)
    strategy.close("Compra", qty=1, when= buyLoss, comment="Loss na operação")

sellSignal = hunderAverage and closePrice < mdi and crossover(high, MA1) and close < MA1
sellLoss = closePrice > mdi and close > MA1 and close > MA2

if (inDateRange)
    strategy.entry("Venda", strategy.short, qty=1, when= sellSignal)
    strategy.exit("Gain da venda", "Venda", qty=1, profit=20)
    strategy.close("Venda", qty=1, when= sellLoss, comment="Loss na operação")

if (not inDateRange)
    strategy.close_all()


