#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 Aqua
#property indicator_color2 Red
#property indicator_width2 2
extern int MAPeriod = 20;
extern int MAGainLimit = 50;
double EMABuffer[];
double ECBuffer[];
double gdAlpha = 0;
int init()
{
SetIndexStyle(0, DRAW_LINE);
SetIndexBuffer(0, EMABuffer);
SetIndexStyle(1, DRAW_LINE);
SetIndexBuffer(1, ECBuffer);
IndicatorShortName("ZeroLagMA("+MAPeriod+")");
SetIndexLabel(0, "EMA");
SetIndexLabel(1, "EC");
gdAlpha = 2.0 / (MAPeriod + 1.0);
return(0);
}
int start()
{
int i, j, iCounted, iLimit;
double dGain, dBestGain, dError, dLeastError, dEC;
iCounted = IndicatorCounted();
if(iCounted > 0)
iCounted--;
iLimit = Bars - iCounted;
for(i = iLimit-1; i >= 0; i--)
{
EMABuffer[i] = gdAlpha * Close[i] + (1 - gdAlpha) * EMABuffer[i+1];
dLeastError = 1000000;
for(j = -MAGainLimit; j <= MAGainLimit; j++)
{
dGain = j / 10;
dEC = gdAlpha * (EMABuffer[i] + dGain*(Close[i] - ECBuffer[i+1])) + (1 - gdAlpha) * ECBuffer[i+1];
dError = Close[i] - dEC;
if(MathAbs(dError) < dLeastError)
{
dLeastError = MathAbs(dError);
dBestGain = dGain;
}
}
ECBuffer[i] = gdAlpha * (EMABuffer[i] + dBestGain * (Close[i] - ECBuffer[i+1])) + (1 - gdAlpha) * ECBuffer[i+1];
}
return(0);
}
Comments