Log in to see Cloud of Tags

Wealth-Lab Wiki

WealthScript Techniques | Executing some code only once

RSS

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 ) == DataSetSymbols[0] ) 
		PrintDebug( "First Run on " + Bars.Symbol );
				
	// And here we finish:
	if( (string)GetGlobal( strName ) == DataSetSymbols[DataSetSymbols.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 (DataSetSymbols[0] == Bars.Symbol)
		PrintDebug( "First run on: " + Bars.Symbol );
			
	if (DataSetSymbols[DataSetSymbols.Count -1] == Bars.Symbol)
		PrintDebug( "Last run on: " + Bars.Symbol );
}

Important Disclaimer: The information provided by Wealth-Lab is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security.  The owner of Wealth-Lab.com assumes no liability resulting from the use of the material contained herein for investment purposes. By using this web site, you agree to the terms of this disclaimer and our Terms of Use.


ScrewTurn Wiki. Some of the icons created by FamFamFam.