
#property description "The algorithm was taken from the book "
#property description "\"Cybernetics Analysis for Stock and Futures\" "
#property description "by John F. Ehlers"
#property strict

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 clrRed
//#property indicator_color2 clrBlue

#property indicator_level1 0

double Cycle[];
double Trigger[];
double Smooth[];

input double mult=1.00;
input double Alpha = 0.07;

int buffers = 0;
int drawBegin = 64;

int init() {
    IndicatorBuffers(3);
    initBuffer(Cycle, "Cycle", DRAW_LINE);
    initBuffer(Trigger, "Trigger", DRAW_LINE);
    initBuffer(Smooth);
    IndicatorShortName("HAC");
    return (0);
}
  
int start() {
    if (Bars <= drawBegin) return (0);
    int countedBars = IndicatorCounted();
    if (countedBars < 0) return (-1);
    if (countedBars > 0) countedBars--;
    int s, limit = MathMin(Bars - countedBars - 1, Bars - drawBegin);
    for (s = limit; s >= 0; s--) {
        Smooth[s] = (P(s) + 2.0 * P(s + 1) + 2.0 * P(s + 2) + P(s + 3)) / 6.0;
        double period = mult*iCustom(NULL, 0, "CyclePeriod", Alpha, 0, s);
        double alpha1 = 2.0 / (period + 1.0);
        int fullPeriod = (int)MathRound(period);
        Cycle[s] =  (iMA(NULL,0,fullPeriod,fullPeriod/2,0,0,s)+iMA(NULL,0,fullPeriod*2,fullPeriod,0,0,s)
      +iMA(NULL,0,fullPeriod/2,fullPeriod/4,0,0,s)+iMA(NULL,0,fullPeriod/3,fullPeriod/3,0,0,s))/4;          
        if (s > Bars - 8) {
            Cycle[s] = (P(s) - 2.0 * P(s + 1) + P(s + 2)) / 4.0;
        }
        Trigger[s] = Cycle[s + 1];
    }
    return (0);
}

double P(int index) {
    if (index >= Bars) {
        return ((High[Bars - 1] + Low[Bars - 1]) / 2.0);
    }
    return ((High[index] + Low[index]) / 2.0);
}

void initBuffer(double& array[], string label = "", int type = DRAW_NONE, int arrow = 0, int style = EMPTY, int width = EMPTY, color clr = CLR_NONE) {
    SetIndexBuffer(buffers, array);
    SetIndexLabel(buffers, label);
    SetIndexEmptyValue(buffers, EMPTY_VALUE);
    SetIndexDrawBegin(buffers, drawBegin);
    SetIndexShift(buffers, 0);
    SetIndexStyle(buffers, type, style, width);
    SetIndexArrow(buffers, arrow);
    buffers++;
}