// Downloaded From https://www.WiseStockTrader.com
SetBarsRequired(100000,100000); 
pi=4*atan(1);
RTD=180/pi;
DTR=pi/180;
SetOption( "initialequity", 50000 ); /* starting capital */
//PositionSize = -10; /* trade size will be 10% of available equty */


function CyclePeriod(array, alpha)
// Figure 9.4 on p. 111
{
  smooth = (array + 2*Ref(array, -1) + 2*Ref(array, -2) + Ref(array, -3))/6;

  for(i = 0; i < 7; i++) {
	cycle[i]=array[i]; // Initialize early values and as array
  	InstPeriod[i] = 0; // Initialize early values and as array
	DeltaPhase[i] = 0;
   cycle[i]=0;
   Period[i]=0;
  }

  for(i = 6; i < BarCount; i++)
  {
     cycle[i] = (1 - .5*alpha)*(1 - .5*alpha)*(smooth[i] - 2*smooth[i-1] + smooth[i-2]) + 2*(1 - alpha)*cycle[i-1] - (1 - alpha)*(1 - alpha)*cycle[i-2];
     Q1[i] = (.0962*cycle[i] + .5769*cycle[i-2] -.5769*cycle[i-4] - .0962*cycle[i-6])*(.5 + .08*InstPeriod[i-1]);
     I1[i] = cycle[i-3];

     if(Q1[i] != 0 AND Q1[i-1] != 0) 
        DeltaPhase[i] = (I1[i]/Q1[i] - I1[i-1]/Q1[i-1])/(1 + I1[i]*I1[i-1]/(Q1[i]*Q1[i-1]));
     if(DeltaPhase[i] < 0.1) DeltaPhase[i] = 0.1;
     if(DeltaPhase[i] > 1.1) DeltaPhase[i] = 1.1;

     //----- Speed up the median calculation by placing it inline
     mlen = 5;
     for(k = mlen - 1; k >= 0; k--) {temparray[k] = DeltaPhase[i + k - (mlen - 1)];}
     temp=0;
     for(k = mlen - 1; k > 0; k--)
     {for (j = mlen - 1; j > 0; j--)
       {if (temparray[j-1] > temparray[j])
         {
           temp = temparray[j-1];
           temparray[j-1] = temparray[j];
           temparray[j] = temp;
         }
       }
     }
     MedianDelta[i] = temparray[mlen - 1 - (mlen / 2)];
     if(MedianDelta[i] == 0) DC[i] = 15; 
     else DC[i] = 6.28318/MedianDelta[i] + .5;

     InstPeriod[i] = .33*DC[i] + .67*InstPeriod[i-1];
     Period[i] = .15*InstPeriod[i] + .85*Period[i-1];

	//Compute Dominant Cycle Phase
	DCPeriod[i] = int(Period[i]);
	RealPart[i] = 0; ImagPart[i] = 0;

	for (Count1=0; Count1 < DCPeriod[i] ;Count1++) {
		if ((i-Count1) > 0) {
			RealPart[i] = RealPart[I] + sin(360*DTR*Count1/DCPeriod[i]) * Cycle[i-Count1];
			ImagPart[i] = ImagPart[i] + cos(360*DTR*Count1/DCPeriod[i]) * Cycle[i-Count1];
		}
	}

	if (abs(ImagPart[i]) > 0.001) {
		DCPhase[i] = atan(RealPart[i]/ImagPart[i])*RTD;
	};	

	if (abs(ImagPart[i]) <= 0.001) {
		DCPhase[i] = 90*sign(RealPart[i]);
	};

	DCPhase[i] = DCPhase[i] + 90;
	if (ImagPart[i] < 0) DCPhase[i] = DCPhase[i] + 180;
	if (DCPhase[i] > 315) DCPhase[i] = DCPhase[i] - 360;
  }
  	return DCPhase;
}


Med = (H+L)/2;

// CyclePeriod
CP = CyclePeriod(Med, .07);
SineWave = sin(CP*DTR);
LeadSine = sin((CP+45)*DTR);


Buy =Cross(Sinewave,LeadSine);
Sell =Cross(LeadSine, Sinewave);

Plot(SineWave , "SineWave ", colorBlue, styleLine);
Plot(LeadSine , "LeadSine ", colorRed, styleLine);