trying to code a script to draw a line on MACD crossover. Skipping crossovers.

 

I'm just learning to code.  I'm just trying to write a script right now.  I want to draw a blue vertical line whenever the MACD line crosses up over the signal line and draw a red vertical line when it crosses down.  It seemed to work except that it skips some of the crossovers.  Plus there are some lines drawn in where I don't see any crossovers. Any thoughts?

void OnStart()
{
   
   for(int i = 0; i<100; i++)
   {
    
      double MACD = iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,i);
      double signalLine = iMACD(NULL,0,12,26,9,PRICE_CLOSE,1,i);
      
      double MACDLast = iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,i+1);
      double signalLineLast = iMACD(NULL,0,12,26,9,PRICE_CLOSE,1,i+1);      
      
         if(MACD>signalLine && MACDLast<signalLine)
         {
         ObjectCreate("Line" + Time[i],OBJ_VLINE,0,Time[i],0);    //(name, type, window, anchor point)
         ObjectSet("Line" + Time[i],OBJPROP_COLOR,clrBlue);
         ObjectSet("Line" + Time[i],OBJPROP_STYLE,STYLE_DOT);
         }
         
         if(MACD<signalLine && MACDLast>signalLine)
         {
         ObjectCreate("Line" + Time[i],OBJ_VLINE,0,Time[i],0);    //(name, type, window, anchor point)
         ObjectSet("Line" + Time[i],OBJPROP_COLOR,clrRed);
         ObjectSet("Line" + Time[i],OBJPROP_STYLE,STYLE_DOT);
         }
         
         
   }
}


 
dasilvja: It seemed to work except that it skips some of the crossovers.  Plus there are some lines drawn in where I don't see any crossovers. Any thoughts?
      double signalLineLast = iMACD(NULL,0,12,26,9,PRICE_CLOSE,1,i+1);      
       if(MACD>signalLine && MACDLast<signalLine      )

Why don't you compare last to last?

 
William Roeder:

Why don't you compare last to last?

Omg... I didn't even realize it was like that! I'm such a goof. Thanks. It works now. lol