Once per bar alert

From MultiCharts
Jump to: navigation, search

With the Alert PowerLanguage keyword it's possible to trigger alerts every bar close or on every tick. But what if you want to trigger an alert once per bar?

Triggering an alert once per bar

The code example below will trigger an alert once per bar, even if the alert properties (in the Alert tab from the Format Indicator screen) are set to 'Alert Conditions Check - Every Tick'.

Variables:
	IntraBarPersist alertAlreadyGiven(False);	
 
if (CheckAlert = True) then begin
 
	// Trigger an alert if the price goes higher than
	//		the highest high of the previous 10 bars.
	if (alertAlreadyGiven = False) and (Close > Highest(High, 10)[1]) then begin
 
		Alert(Text("The price, ", NumToStr(Close, 2), ", has crossed the highest high (",
				NumToStr(Highest(High, 10)[1], 2), ") of the last 10 bars."));
 
		// Set the boolean to true to prevent another alert 
		//		on this bar.
		alertAlreadyGiven = True;
	end;
 
	// Reset the boolean variable so that an alert can
	//		be triggered during the next bar.
	if (BarStatus(1) = 2) then
		alertAlreadyGiven = False;
 
end;

Triggering an alert once per bar - simplified

To simplify the triggering of an alert once per bar, and not clutter your code with the code logic from the example above, consider making a function called AlertOncePerBar (Return type: Numeric, Function Storage: Simple), in which you'll place the following code:

{
	AlertOncePerBar function; will generate an alert once per bar.
}
 
Inputs:
	AlertText(StringSimple);
 
Variables:
	IntraBarPersist barNumOfAlert(0);
 
if (CurrentBar <> barNumOfAlert) then begin
 
	Alert(AlertText);
 
	barNumOfAlert = CurrentBar;
end;
 
AlertOncePerBar = 0; // dummy

Now, if you want to call an alert once per bar (for example, with an EMA crossover), you can call that with:

if (XAverage(Close, 5) crosses above XAverage(Close, 20)) then
     AlertOncePerBar("EMA cross alert");