- an "atomic" addition for static variables

Miscellaneous functions
(AmiBroker 6.10)

SYNTAX StaticVarAdd( "name", value, keepAll = True, persistent = False )
FUNCTION StaticVarAdd implements an atomic addition (interlocked read-add-write) operation for static variables.

It is multithreading safe addition for static variables that are shared by multiple threads. This function is atomic with respect to calls to other static variable functions.

KeepAll flag when it is set to true emulates the behavior of AddToComposite. It keeps all values that are already present, so if data holes exists in current symbol,the bars that are present in static variable but not present in current symbol remain untouched. When KeepAll is set to false then only bars that are present in current symbol are kept. Any other bars that were present in static variable but not present in currently processed symbols are removed. That is what normally happens with StaticVarSet(). In fact when KeepAll is set to False, StaticVarAdd can be seen as the following pseudo code:

x = Nz( StaticVarGet( "name" ) ); // read exisiting value (and convert Nulls to zero)
x += Nz( value ); // add value to existing
StaticVarSet( "name", x ); // store updated value

The function can be used to create composites like shown in the example below.


  • StaticVarAdd automatically converts all Nulls to zeros (as AddToComposite does).
  • If you want to replace AddToComposite with StaticVarAdd, keep in mind that by default AddToComposite skips symbols in group 253. This is done so composite symbols are not added to themselves. If you have composite symbols in your database and want to skip symbols in group 253 you can use
    if( GroupID() != 253 ) StaticVarAdd("~Composite", values );
  • Thanks to extensive code tuning, StaticVarAdd generally offers better performance than AddToComposite which was already blazing fast. Single threaded StaticVarAdd may be twice as fast as ATC. With 8 threads running StaticVarAdd may be 4x as fast (it does not scale as much as naive person may think, because critical section limits performance due to lock contention). To illustrate the amount of fine tuning applied it can be said that first 'straightforward' version of StaticVarAdd was actually 20 times slower than ATC.
  • Be careful when using "quickafl" as StaticVarAdd would not increase 'required bars' (as ATC does), so if you want to actually add all bars and quick afl is turned on in analysis, it is better to add
    SetBarsRequired(sbrAll, sbrAll)
EXAMPLE if( status("stocknum") == 0 )
     // remove any earier composite values

StaticVarAdd( "~Composite", MACD() > Signal() );
Buy = 0;
SEE ALSO StaticVarSet() function , StaticVarGet() function , StaticVarCompareExchange() function


The StaticVarAdd function is used in the following formulas in AFL on-line library:

More information:

See updated/extended version on-line.