Alert per bar not tick

 

Total newbie here, I'm teaching myself to program using the MQL4 book.

I've coded the following to give alerts when stochastics cross back from overbought/oversold levels.

How can I adjust the program to only get an alert at the end of the bar and not per tick? Any help will be appreciated.

#property indicator_chart_window

extern int Kperiod = 11;
extern int Dperiod = 3;
extern int Slowing = 3;
extern int TopLevel = 80;
extern int BottomLevel = 20;

int start()
{

double Level0, Level1;

Level0 = iStochastic(NULL,0,Kperiod,Dperiod,Slowing,MODE_SMA,0,MODE_MAIN,0);
Level1 = iStochastic(NULL,0,Kperiod,Dperiod,Slowing,MODE_SMA,0,MODE_MAIN,1);

if (Level0 < TopLevel && Level1 > TopLevel)
Alert("Stochastic "+Symbol()+ " crossing under "+TopLevel);

if (Level0 > BottomLevel && Level1 < BottomLevel)
Alert("Stochastic "+Symbol()+ " crossing over "+BottomLevel);

return(0);
}

 
if (NewBar () && Level0 < TopLevel && Level1 > TopLevel)
Alert("Stochastic "+Symbol()+ " crossing under "+TopLevel);

if (NewBar () && Level0 > BottomLevel && Level1 < BottomLevel)
Alert("Stochastic "+Symbol()+ " crossing over "+BottomLevel);



return(0);
}

bool NewBar () 
   {
   static datetime LastTime = 0;

   if (Time[0] != LastTime) 
      {
      LastTime = Time[0];     
      return (true);
      }
   else
      return (false);
   }

 

Thanks so much for the help.

Am i correct that this will only send the alert for the first tick in a bar where the conditions are met? Is there a way to only check the last tick of a bar?

 

See my current code below, I am not getting any alerts at the moment, any help will be appreciated:

extern int Kperiod = 11;
extern int Dperiod = 3;
extern int Slowing = 3;
extern int TopLevel = 80;
extern int BottomLevel = 20;


int start()
  {
  
  double Level0, Level1;
  
  Level0 = iStochastic(NULL,0,Kperiod,Dperiod,Slowing,MODE_SMA,0,MODE_MAIN,0);
  Level1 = iStochastic(NULL,0,Kperiod,Dperiod,Slowing,MODE_SMA,0,MODE_MAIN,1);
  
  Alert(Level0);
  
  
  if (NewBar() && Level0 < TopLevel && Level1 > TopLevel)
     Alert("Stochastic "+Symbol()+ " crossing under "+TopLevel);
     
  if (NewBar() && Level0 > BottomLevel && Level1 < BottomLevel)
     Alert("Stochastic "+Symbol()+ " crossing over "+BottomLevel);

return(0);
}

bool NewBar()
{
    static datetime LastTime = 0;
    
    if (Time[0] != LastTime)
    {
       LastTime = Time[0];
       return(true);
    }
    else
       return(false);
}   
 

Think I have figured out the main problems.

1. The NewBar function should only run once per tick, I now find the NewBar value before running the two IF statements.

2. I changed the periods of the stochastics from 0 and 1 to 1 and 2. It now alerts on the first tick of the new bar if the cross occured on the previous bar, I'm not sure if there is any other way?