{"id":1223,"date":"2015-10-06T07:03:47","date_gmt":"2015-10-06T12:03:47","guid":{"rendered":"http:\/\/www.amibroker.com\/kb\/?p=1223"},"modified":"2015-10-06T07:22:55","modified_gmt":"2015-10-06T12:22:55","slug":"how-to-run-certain-piece-of-code-only-once","status":"publish","type":"post","link":"https:\/\/www.amibroker.com\/wordpress\/kb\/2015\/10\/06\/how-to-run-certain-piece-of-code-only-once\/","title":{"rendered":"How to run certain piece of code only once"},"content":{"rendered":"
There are situations where we may need to run certain code components just once, e.g. to initialize some static variables before auto-trading execution or perform some tasks (such as ranking) at the very beginning of backtest or exploration. The following techniques may be useful in such cases:<\/p>
When we want to execute certain part of code just once after starting AmiBroker, we may use a flag written to a static variable that would indicate if our initialization has been triggered or not.<\/p> If we want to run certain part of code at the beginning of the test run in Analysis window, we can use:<\/p> When Status(“stocknum”) is detected in the code, then execution is performed in a single thread for the very first symbol. Only after processing of this first symbol has finished the other threads will start.<\/p> A practical example showing use of this feature is presented in the following tutorial:<\/p><\/span>if( <\/span>Nz<\/span>( <\/span>StaticVarGet<\/span>(<\/span>"InitializationDone"<\/span>) ) == <\/span>0 <\/span>)
{
<\/span>StaticVarSet<\/span>(<\/span>"InitializationDone"<\/span>, <\/span>1<\/span>);
<\/span>\/\/ code for first execution
<\/span><\/code><\/span>if ( <\/span>Status<\/span>(<\/span>"stocknum"<\/span>) == <\/span>0 <\/span>)
{
<\/span>\/\/ our code here
<\/span><\/code>