amibroker

HomeKnowledge Base

How to execute part of the formula only when new bar is added

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):

Intraday Settings

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 LastValueDateTime() );

// 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 NzStaticVarGetvarName ) );

// code runs conditionally only when new bar is detected
if( lastBarTime != recordedTimestamp )
{
    
// record new bar datetime
    
StaticVarSetvarNamelastBartime );

    
//////////////////////////////////////
    // main code here
    
PlaySound"c:\\windows\\media\\ding.wav" );
    
//////////////////////////////////////
}

// sample indicator code
PlotClose"Close"colorDefaultstyleBar )

Newer AmiBroker versions (>5.60) can use this for reading last bar timestamp (this is faster than using DateTime() function).
lastBartime Status("lastbarend")