Correct use of StaticVarAdd

Since wrong codes with StaticVarAdd are posted all the time, here is short summary on how to use it correctly:

Correct use of StaticVarAdd is explained in the manual
http://www.amibroker.com/guide/afl/staticvaradd.html

The example shows clearly the code:

// this code is intended to be run ON MULTIPLE SYMBOLS (e.g. watch list)
// and only once to create composite / static var
if( status("stocknum") == 0 )
{
     // remove any earier composite values
   StaticVarRemove("~Composite");
}

// creation of static var WITHOUT Foreign and 
// OUTSIDE if(status("stocknum") == 0) statement
StaticVarAdd( "~Composite", MACD() > Signal() );
Buy = 0;

Note that this formula does NOT use Foreign/SetForeign calls.

This formula is intended to be run on a watch list or other filter consisting of multiple symbols.

StaticVarAdd is intended as alternative to AddToComposite
http://www.amibroker.com/guide/a_addtocomposite.html

and general workflow is the same:

  1. static vars holding composites should be created ONCE (in pre-scan)
  2. after they are created they should ONLY be read, not recreated with every analysis run
  3. you must NOT use Foreign/SetForeign within if( status("stocknum") part - the code for first symbol should only REMOVE static vars, not create them.
  4. creation of static vars should be done normally, utilizing multithreading when scan automatically goes thru symbol and NOT using SetForeign with loops.

If you want to automate things you can use #pragma sequence introduced in 6.40.4 and use "Run sequence"

#pragma sequence(scan,exploration)

Version(6.40);

if( Status("action") == actionScan )
{
	// CREATE composite ONLY IN SCAN
	// this code is intended to be run ON MULTIPLE SYMBOLS (e.g. watch list)
	// and only once to create composite / static var
	if( status("stocknum") == 0 )
	{
		 // remove any earier composite values
	   StaticVarRemove("~Composite");
	}

	// creation of static var WITHOUT Foreign and OUTSIDE if() statement
	StaticVarAdd( "~Composite", MACD() > Signal() );
	Buy = 0;
}

Filter = 1;
AddColumn( StaticVarGet("~Composite"), "CompositeValues" );
12 Likes

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.