The Extern function makes it easy to refer to data for a symbol other than the current one, or to access the stats of a different strategy (or the combined stats) within a test.
The syntax is: Extern(item, expression)
By default, the context of any expression is the current stock and the current strategy. This function simply creates a temporary context with a different symbol or strategy and evaluates your expression using that temporary context.
The syntax for an external symbol reference is: $symbol, e.g. $MSFT.
If a data file is currently loaded in memory while the script is being edited, then the editor’s auto-completion mechanism will present a list of possible symbols as soon as you type the $.
The syntax for an external strategy reference is: @strategy_name, e.g. @mr_Long
The special name @combined can be used to refer to the combined stats of all strategies.
Since this is a common requirement, an alternative and slightly shorter way to do this is to use the Combined(expression) function, which is equivalent to Extern(@combined, expression).
Once a script has been parsed at least once, the list of strategies that it contains are available for auto-completion after typing the @ sign.
Besides accessing the data of an external symbol or the stats of an external strategy, the Extern function is also useful within a multi-strategy system to access overall current position information.
The simplest example of when you'd use Extern is the specific symbol reference. For instance, to use an index ETF relative to its moving average as part of your EntrySetup rule, you'd say something like this:
Actually, to avoid needlessly re-calculating the SPY 200-day average for every symbol every day, I'd implement this as follows:
The script mr_sample_hedged.rts in the example scripts directory shows a sophisticated example of how to use external strategy references to build a dynamic SPY hedge for a long/short system:
While this looks complex, all it's doing is:
•calculate the difference between the number of positions in the other two strategies for today vs. yesterday
•if that difference has changed, then exit the former hedge and enter a new hedge based on the new difference
This implementation takes advantage of the following features of RealTest strategies:
•By default a position is only entered when there is currently no position in that symbol for that strategy, which is why EntrySetup needs no logic other than that the current symbol is SPY
•If the Side of a strategy is not specified, it is inferred from the sign of the Quantity calculation result.
Admittedly, in real trading you would not exit the entire hedge and re-enter at the new size, you'd just buy or sell the net change in shares required. But for backtesting purposes this works fine.