WealthScript Techniques | Executing some code only once

Modified on 2010/07/30 11:56 by Eugene — Categorized as: Knowledge Base

The problem

"How can I execute some code only once at the beginning or at the end of the process of backtesting on a dataset ? It could be useful for example to make an operation that must be done only once, like cleaning a database or opening a connection to a DB or calling an external process."



The approach

Since Strategy execution starts on the first symbol (in alphabetical order) of the DataSet, i.e. DataSetSymbols[0], and ends on the last, i.e. DataSetSymbols[DataSetSymbols.Count-1], we can easily track these moments and store the Strategy "execution state" in Wealth-Lab's global memory (GOP) - a very helpful instrument. Cycling through all of the DataSet's components, we save the current instrument's index globally and check it at run time. This way we can limit execution of some code to the first or the last symbol - which is, respectively, when Strategy starts and stops working.

protected override void Execute() { string strName = StrategyName; // Save current symbol in Wealth-Lab's global memory SetGlobal( strName, Bars.Symbol ); // Here we kick in: first symbol detected if( (string)GetGlobal( strName ) == DataSetSymbols0 ) PrintDebug( "First Run on " + Bars.Symbol ); // And here we finish: if( (string)GetGlobal( strName ) == DataSetSymbolsDataSetSymbols.Count-1 ) { PrintDebug( "Last Run on " + Bars.Symbol ); ClearGlobals(); } }

Note: A related solution to keep a specific Strategy from executing right after it is opened - the {$NO_AUTO_EXECUTE} analogue: WealthScript Techniques | Don't execute Strategy on open, which also uses the global memory pool.



A simpler approach

But wait, there's more. Our user ss161 suggested a more concise way of doing the same thing. All you have to do is to determine the first and the last symbols in a DataSet (DataSetSymbols[0] and DataSetSymbols[DataSetSymbols.Count-1] respectively):

protected override void Execute() { if (DataSetSymbols0 == Bars.Symbol) PrintDebug( "First run on: " + Bars.Symbol ); if (DataSetSymbolsDataSetSymbols.Count -1 == Bars.Symbol) PrintDebug( "Last run on: " + Bars.Symbol ); }