MAMA (Ehlers) MESA Adaptive Moving Average
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dongyun

//@version=4
strategy("自适应移动平均的MESA系统", overlay=true)

fastlimit = input(0.5,'')
slowlimit = input(0.05,'')

smooth = 0.0
detrender = 0.0
I1 = 0.0
Q1 = 0.0
JI = 0.0
JQ = 0.0
I2 = 0.0
Q2 = 0.0
Re = 0.0
Im = 0.0
period = 0.0
smoothperiod = 0.0
phase = 0.0
deltaphase = 0.0
alpha = 0.0
MAMA = 0.0
FAMA = 0.0
price = 0.0

price := (high + low)/2
PI = 2 * asin(1)

if (bar_index > 5)
	smooth := (4*price + 3*price[1] + 2*price[2] + price[3])/10
	detrender := (.0962*smooth + .5769*nz(smooth[2]) - .5769*nz(smooth[4]) - .0962*nz(smooth[6]))*(.075*nz(period[1]) + .54)

	// compute InPhase and Quadrature components
	Q1 := (.0962*detrender + .5769*nz(detrender[2]) - .5769*nz(detrender[4]) - .0962*nz(detrender[6]))*(.075*nz(period[1]) + .54)

	I1 := nz(detrender[3])

	// advance the pulse of i1 and q1 by 90 degrees
	JI := (.0962*I1 + .5769*nz(I1[2]) - .5769*nz(I1[4]) - .0962*nz(I1[6]))*(.075*nz(period[1]) + .54)
	JQ := (.0962*Q1 + .5769*nz(Q1[2]) - .5769*nz(Q1[4]) - .0962*nz(Q1[6]))*(.075*nz(period[1]) + .54)

	//phase addition for 3-bar averaging 
	I2 := I1 - JQ
	Q2 := Q1 + JI

	//smooth the i and q components before applying
	I2 := .2*I2 + .8*nz(I2[1])
	Q2 := .2*Q2 + .8*nz(Q2[1])

	// hymodyne discriminator
	Re := I2*I2[1] + Q2*nz(Q2[1])
	Im := I2*Q2[1] + Q2*nz(I2[1])
	Re := .2*Re + .8*nz(Re[1])
	Im := .2*Im + .8*nz(Im[1])

	if (Im != 0 and Re != 0)
		period := 2 * PI/atan(Im/Re)

	if (period > 1.5 * nz(period[1]))
		period := 1.5*nz(period[1])

	if (period < .67*nz(period[1]))
		period := .67*nz(period[1])

	if (period < 6)
		period := 6

	if (period > 50)
		period := 50

	period := .2*period + .8*nz(period[1])
	smoothperiod := .33*period + .67*nz(smoothperiod[1])

	if (I1 != 0)
		phase := (180/PI) * atan(Q1/I1)

	deltaphase := nz(phase[1]) - phase

	if (deltaphase < 1)
		deltaphase := 1

	alpha := fastlimit/deltaphase
	if(alpha < slowlimit)
		alpha := slowlimit

	MAMA := alpha*price + (1 - alpha)*nz(MAMA[1])
	FAMA := .5*alpha*MAMA + (1 - .5*alpha)*nz(FAMA[1])

	if (FAMA < MAMA)
		strategy.entry("Long", strategy.long)
	else
		if (FAMA > MAMA)
			strategy.entry("Short", strategy.short)
