November 29, 2015
In realtime conditions we may be interested in executing some parts of our formula only once per bar, when a new bar is created (e.g. for auto-trading purposes or just for notification). To do that – we would need to identify the very moment when new bar appears.
This can be done using static variables to record the timestamp of the most recent bar, then comparing current reading with the recorded value. Once the difference is detected – we can conditionally run our code and update the recorded time info.
Such an approach will work if we use timestamps that don’t change with each tick, so preferred option is to use Start Time of Interval for timestamp display (for daily and higher intervals we should unmark “override” box):
Then we can use the following code (this sample formula will just play a ding.wav system sound when the new bar is detected):
// read last bar date/time
lastBartime = LastValue( DateTime() );
// we use per-symbol variable
// you may consider to add GetChartID() key if you want
// to use the formula in multiple charts shown at the same time
varName = Name() + "_lastdt";
// read recorded date/time from last execution
recordedTimestamp = Nz( StaticVarGet( varName ) );
// code runs conditionally only when new bar is detected
if( lastBarTime != recordedTimestamp )
// record new bar datetime
StaticVarSet( varName, lastBartime );
// main code here
PlaySound( "c:\windows\media\ding.wav" );
// sample indicator code
Plot( Close, "Close", colorDefault, styleBar );
Newer AmiBroker versions (>5.60) can use this for reading last bar timestamp (this is faster than using DateTime() function).
lastBartime = Status("lastbarend");