Combination strategiesWhile single strategy backtest reports errors in the debug window, Combination Strategy does not proceed with the testing.
The design is abort strategy processing when an error is detected. Fix the error or wrap the original strategy code in a try/catch block.Is child strategy equity being constantly readjusted on a day-to-day basis with regard to the "Percent of Starting Equity" allocation?
No. "Percent of Starting
Equity" is used to allocate the specified amount of starting
equity, and afterwards each strategy is confined to its individual allocation.
Rule-based strategiesThe condition list for Date/Time only includes conditions for dates. How do I include a "time of the day" rule?
Currently, it's not an option. See a tip in the WealthScript
section below.After generating strategy code with "View Strategy Code", there are strings like "Group1" and "Group1|". What do they mean?
This is a string used to match up entries with exits. From the technical standpoint, the String.Contains(string) method
does the job here.Is it possible to add an ATR-based Trailing stop in Rule-based Strategy?
Presently, the Rule-based Wizard lacks ATR Trailing stops. Nonetheless, this is pretty easy to do in code-based Strategy: just follow the QuickRef entry for HighestHighAsOfBar
as an example.How to create a pullback setup in Rule-based Strategy?Problem:
You want to be able to create a Pullback in an Uptrend
entry. For instance, in an established uptrend, wait for a three bar pullback and
enter at stop $0.10 above prior bar high. However, the Rule Wizard doesn't seem to have "Buy at Stop" rule desired. Solution:
You can get pretty close by starting with these rules:
- Moving Average is trending up (Moving Average group)
- Price decreases a consecutive number of bars (Price (or Volume) group)
..and add an exit (if you only want a screen, see Techniques > Creating a Screener
in the WealthScript Programming Guide),
After that, you'll need to "Open Code in new Strategy Window" and make the following edit:
BuyAtLimit(bar + 1, High[bar], "");
How to create a stop-and-reverse system in a Rule-based Strategy?Problem:
// CHANGE TO:
BuyAtStop(bar + 1, High[bar] + 0.10, "");
Is it possible to create a stop-and-reverse system in the Rule Wizard?Solution:
The Stop-And-Reverse option which existed in legacy versions of Wealth-Lab was removed for the purpose of simplification. However, there is a workaround: selecting "Multiple open positions allowed"
will let you switch from long to short position on the same bar. Limitation
: this trick won't work when adding multiple conditions, only for a single symmetric condition.
The solution is to create a SAR system manually:
WealthScript Techniques | Creating a Stop-And-Reverse (SAR) system
IndicatorsI get a difference between the ATR calculation of Wealth-Lab and my own calculation.
Most likely, your calculation is treating ATR
as an arithmetic average. It's not
: the ATR formula uses Wilder's smoothing method (WMA
). Check out the proper ATR
formula in this Wiki.How do I create MACD indicator with custom parameters?
Why in many channel-breakout codes is it correct to shift the series forward by one bar (i.e. >>1) ?
See Help > WealthScript Programming Guide > Indicators > Custom Indicators > "How to: Create a MACD with Custom Periods".
- As a full-blown indicator, accessible by rule-based strategies:
Install the Community.Indicators library which includes MACD with custom parameters.
The reason to shift (delay) the series like this...
DataSeries s = Lowest.Series(Close, period) >> 1
...is that on the chart, it's visually pleasing to see prices "crossing over/under" a plotted line.
Is it possible to plot several drag & drop indicators in one shot?
No. There hardly is any advantage to showing a new dialog with a large list of indicators that still must be configured individually. Instead, drag and drop indicators until you feel satisified and then save the "strategy" which can in future be reopened to modify any of these indicators by double clicking. On the other hand, creating a code-based strategy will work just fine for this task.
Rotation strategiesA Rotation strategy isn't working like it should.Symptoms:
Trades are taken multiple times: the same stock can be purchased 3 or 4 times. There are 1000's of trades reported missing from the simulation etc.Solution:
Read the Strategy description. Follow the usage notes precisely. Select only 1 symbol in the DataSet. This strategy should not be run in Multi-Symbol Backtest mode. Otherwise you'll be running the script once for each symbol, and it's not designed for that.My code with DataSetSymbols runs incorrectly or can't run on more than a few symbols.
Check that you're not
running it on the DataSet. You should never run a strategy with a DataSetSymbols loop on the entire DataSet - it just doesn't make sense to do that. You'll end up running the same code DataSetSymbols * DataSetSymbols
times! Run such code for just one symbol in the DataSet.Why there are different results depending on the clicked symbol?
The only way the results will be the same is if all the data are synchronized natively. Every symbol must have bar data for exactly (and all) the same dates, otherwise Wealth-Lab has to synchronize the data by adding or deleting bars of the secondary symbols.Is it possible to pyramid in rotational strategies?
Yes, see this forum thread
for a code example.I need other rotation rule other than the built-in RSI.
- To substitute the RSI indicator with another data series, modify this line:
holder.rsi = RSI.Series(Bars.Close, Period)[bar];
- To modify the sorting order (i.e. keep ones with the highest RSI), do this:
// CHANGE TO:
OptimizationCan't optimize a Strategy. What am I missing?
Optimizer is not available for:
- Chart-only windows
- When using Streaming data
- If you've hidden the Strategy Window's Status bar:
To see the Optimize label in a Strategy Window, show the Status bar and turn off Streaming.
Why Sharpe ratio is not provided in Optimization Results?
Switch to one of the Portfolio Simulation options from the Position Sizing dialog. Before runnning an optimization, switch to a Scorecard with Sharpe ratio: Extended or MS123 Scorecard.
In Raw Profit mode, there is no starting capital by definition and consequently, no Sharpe, no Max Drawdown % or Exposure.
See FAQ > Miscellaneous > Position sizing
Strategy In GeneralWhy is main (trading) loop required in live trading?
Strategies are run bar-by-bar, always processing the most recent one and determining if an action is required. Actions that occurred on previous bars create Positions. In order to determine the current positions, you need to loop through previous bars to determine if the strategy had generated a trade, and now the current bar can be used to exit from it. Not having the main (trading) loop turns your strategy into a scan
because it no longer has "memory" required to keep the trade history.What is optimal for my trading, Strategy Monitor or Strategy window?
If you're a user of Fidelity Wealth-Lab Pro 6.3 trading less than 12-15 symbols, we suggest using Streaming strategies
. Streaming Strategy windows execute immediately at the end of the bar w/o delay, unlike Strategy Monitor (see Help - User Guide > Strategy Monitor > Employment Notes). Streaming Strategies are not recommended for intraday pair trading (workaround: use Strategy Monitor or add a delay before setting context):
protected override void Execute()
Bars b = GetExternalSymbol("AA", true);
For more instruments, consider using the Strategy Monitor
. Wealth-Lab Pro users should know that it makes requests for Fidelity data in sets of 10-symbols, so to minimize data request delays, break up your DataSets in groups of 10 symbols and add a Strategy Monitor item for each one. The Strategy Monitor is recommended for pair trading Strategies. Starting from WLP version 6.4, new "Streaming bars" feature brings big performance improvement to the Strategy Monitor (applies to Fidelity data).
Can't execute a Strategy - I run it but nothing comes up. What am I missing?
When you make changes in the Editor, you must click the "Compile" button in the Editor toolbar, or click "Run the Strategy", which compiles and runs.Why all my backtest trades are negative?
You have applied a (very small) position size like 1 Share and haven't disabled the default commission plan ("Fidelity") in Wealth-Lab's Preferences.Is there a way to make WL6 specify the line in the strategy where the error occurs?
No. They're displayed for compilation errors, but not runtime errors. Strategies in Version 6 run from compiled code, so line numbers in the editor aren't known directly. If the contents of the error doesn't give you a good clue, you can use the debug techniques
.Is there a way to reuse a function in Strategies? Is it possible to create a library of reusable functions?
It's not possible to call a method from a Strategy saved in an XML file. You need to code your functions and methods in a .NET language of your choice, build a .NET assembly, and place it in Wealth-Lab's main directory under Program Files with the rest of dynamically linked libraries (DLLs). Then reference it in your Strategy by using References in the Editor and/or with a "using" directive.Every time I run a Strategy I get a different result. What am I missing?Symptoms:
You're running a Strategy in Multi-Symbol Backtest mode (MSB) using Portfolio Simulation mode (in other words, not
Raw Profit) and every time it runs you get a different result. In addition, your entry has no position priority assigned.Solution:
Solution: assign position priority. Everything is explained in the Wealth-Lab User Guide, so we are not going to duplicate its contents here. You're welcome to take a look in the Wealth-Lab User Guide, Strategy Window > Backtesting Strategies > How Trades Are Chosen
. Another resource is the QuickRef entry for Position.Priority
Strategy runs slow.Symptoms:
It takes much time for a typical strategy to run, for example, making it impossible to work in the Strategy Monitor.Solution:
Out of memory problems.Symptoms:
- Check if you're requesting on-demand updates during market hours. Turn off on-demand updates.
- In Preferences, disable unneeded performance visualizers and reopen the Strategy window for the changes to apply.
- (Windows XP only) In case of unexplainable, partial slowdown of the application, reinstall .NET framework.
Wealth-Lab generates an out-of-memory exception message when you try to perform a Multi-Symbol Backtest on a big amount of high frequency data (e.g. a big DataSet of 1-minute symbols, an ASCII file with long second-based history).Reason:
By design, Wealth-Lab 6 requires the data to remain in memory to be available in PosSizer calculations (position sizing scripts) and visualize all Performance Visualizers.
Wealth-Lab 6 requires twice as much memory as WL4 because now double precision is used, taking 8 bytes in memory for each data element. You can realistically estimate memory consumption by using the following simple math:
Required RAM = Number of stocks * number of bars * number of data series (typically 6: DateTime + OHLCV) * 8 bytesSolutions:
I want to test a strategy that buys and sells with stop/limit orders on the same bar.
- Break up the Multi-Symbol Backtest. If you're trading 1-minute bars, it's unlikely that your time horizon is on the order of months and years.
- Turn off some extra Performance Visualizers (Preferences - Performance Visualizers - uncheck).
- Call Bars.Cache.Clear at the end of your strategy to explicitly clear the internal cache that stores DataSeries and free memory.
- Install the x64 version of Wealth-Lab Developer/Pro if your operating system supports it.
- Install more RAM for 64-bit Wealth-Lab to consume.
You can't realistically backtest with stop and limit orders on the same bar. What is reliably known is that the open occurred before all the other prices and that the close occurred the last. The intra-bar price dynamics is unknown.
To avoid inadvertent peeking into the future (and inflated backtest results) when dealing with stop/limit signals on the same bar, apply a workaround:
How to keep Strategy from executing when I drag a Strategy parameter slider?
This convenient feature is by design and applies to single-symbol backtests only. Consequently, if you click on DataSet title to switch to multi-symbol mode before changing a parameter, the strategy will not re-execute.Why am I unable to "Reset" and "Save parameters"
Because the default setting of the parameter value(s) may have been altered by "Save Parameters". In this case, the saved setting overrides the default value in the Editor. To set a new default parameter value, change a slider and Save.Alerts are not triggered.Symptoms:
You get a Buy/Sell signal but do not get an Alert.Answer:
Here's a quick list of things to check:
How to display portfolio equity (exposure, drawdown etc.) series and/or access them in scripts?
As the WealthScript Programming Guide suggests (Programming Trading Strategies > Strategy Code Limitations
), it's not possible to create trading strategies that enter or exit trades as a function of portfolio equity. The natural way is to create a PosSizer. However, workarounds exist on how to access the portfolio equity DataSeries in Strategies:
WealthScriptHow do I start with C# ?
If you want to learn programming, then you can take a C# class, buy a book, or use any number of the hundreds of free sources on the web. Typically, any beginner book picked from the bookshelf would do the job because you don't have to be a programmer to become proficient with WealthScript - like "Microsoft C# Programming for the Absolute Beginner"
. To create strategies from scratch, you need to have the basic knowledge of such language concepts as: language syntax, data types, operators and statements, loops, classes, Date/Time and String classes.
If you're starting out, a very good, simple and comprehensible free e-book is C# Yellow Book 2010 by Rob Miles
(PDF, direct download link
There are great many free .NET and C# resources on the web as well. Use a search phrase like "Free online C Sharp Books"
when googling, or here's just a handful assorted links:
In addition, don't forget that Microsoft Visual C# 2010 Express
IDEs are free.
Finally, the WealthScript Guide and the QuickRef concentrate on giving concrete examples of programs that almost everyone is likely to write. After studying the basics of C#, working with examples is a great way to learn how to program.I'm a Wealth-Lab 3/4 user, how to learn C# ?
Both Delphi/Pascal and C# are modern object-oriented languages, so once you make this pretty easy transition to C#, you will never look back. Here are some tips
to help you along the way:
TrendlineValue can't be accessed.Symptoms:
- Although there's some learning curve in gaining basic knowledge of what .NET has to offer to streamline your coding, WealthScript hasn't changed conceptually. For example, the "using" statements in C# are similar to $Includes. Another change worth mentioning is that some of the old functions now have gone for good because they're already available as a part of the Microsoft .NET framework (see An equivalent WealthScript function can't be found).
- Start by looking at the prepackaged strategies. Concentrate on the Execute() method, ignoring the other stuff at first.
- Use the WealthScript Translator tool to convert your Wealth-Lab 4 strategies to run in Wealth-Lab 6 (Direct download link). Compare the code with its WLD3/4 origin.
- Start using the Strategy Builder (aka New Strategy from Rules). Create a strategy, then use the "Open code in new window" function. Examining the code is very helpful.
- Keep WealthScript Programming Guide open: along with the QuickRef tool, it's your source for many examples of no-nonsense, illustrative code samples for real life tasks.
In a Strategy that loops through DataSet symbols using SetContext, TrendlineValue is not working. If you click on the symbol with the trendline, TrendlineValue code is executed whereas when you click on another symbol to start the Strategy, TrendlineValue returns zero.Answer:
By design, it's not possible to access a Trendline Value for other symbols through SetContext since the TrendLine(s) don't exist in the current chart.How to reduce the number of decimal places for display/debug?Question:
Is it possible for values of type double
to have just two digits after the decimal? I don't need the full precision.Answer:
There are at least two ways:
- Use the Bars.FormatValue method will formats the specified value into a string, using the current number of decimals.
- Or use a custom format string like this:
More on topic:
MSDN: Custom Numeric Format Strings
String Format for Double
Is there ChangeBar method in WL6?
WL6 doesn't contain a ChangeBar lookalike, but it's easy to modify values of the Bars object:
protected override void Execute()
DateTime dt = new DateTime(2008,01,23);
for(int bar = 20; bar < Bars.Count; bar++)
//Date[bar] = dt;
Open[bar] = SMA.Series( Open, 20 )[bar];
High[bar] = SMA.Series( High, 20 )[bar];
Low[bar] = SMA.Series( Low, 20 )[bar];
Close[bar] = SMA.Series( Close, 20 )[bar];
Since the Date collection is read-only, it is not possible to change the bar's date. See what happens if you uncomment the Date[bar] = dt line.
I want to chart an indicator, but without the stock price. Can I hide the PricePane?
Short answer: It's not possible to hide the PricePane completely
, but a workaround is available.
The chart is the primary data and neither it makes sense to remove it nor there is an associated WealthScript command to do it. Nonetheless, if you set the height of your ChartPane to the maximum possible value - that is Int32.MaxValue
- it will make the PricePane shrink to hairwidth:
protected override void Execute()
ChartPane GiantPane = CreatePane(Int32.MaxValue,false,false);
PlotSeries( GiantPane, RSI.Series( Close,14 ), Color.Blue, LineStyle.Solid, 2 );
How to program MetaStock's PREV function in Wealth-Lab?
There is a function in MetaStock formula language called PREV
that slows down processing dramatically, but is quite helpful.
A common mistake when translating a MetaStock formula with PREV statement is confusing it with the series value on the previous bar. However, MetaStock does
have a way to reference previous bar value which is "Ref": e.g. "Ref(c,-1)". PREV is a statement-oriented
self-referencing directive that references its own value on the previous bar.
If a bar loop is being used, simply reference the variable like shown below to create a PREV equivalent:
protected override void Execute()
for(int bar = 20; bar < Bars.Count; bar++)
/* In MetaStock:
a11 = ( a10+a11*( a5-1 ) )/ a5;
How do I code a rule for time of the day?
Use the Hour⁄Minute
properties of the standard .NET DateTime
structure. Here's a helpful wrapper function that makes coding a little more straightforward:
Is there a way to see the trades on secondary symbols?
Yes. To enter trades on secondary symbols, use the SetContext
method call. To visualize the trade arrows on a secondary symbol pane, you can plot them artificially - here's an illustration:
protected override void Execute()
int bar = Bars.Count-1;
string UpArrowGreen = Convert.ToChar(0xe9).ToString();
string UpTriangleGreen = Convert.ToChar('\u25b2').ToString();
Is there a workaround for Market on Close orders?
AnnotateBar( UpArrowGreen, bar, true, Color.Green, Color.Transparent, new Font( "Wingdings", 10, FontStyle.Bold ) );
AnnotateBar( UpTriangleGreen, bar-1, true, Color.Green, Color.Transparent, new Font( "Times New Roman", 10, FontStyle.Bold ) );
Auto-trading MOC orders with Fidelity is impossible. As a workaround, you can use a market order on the 15:59 bar using the logic outlined in the WealthScript Programming Guide: Programming Trading Strategies > Alerts > How to: Alert for AtClose Signals
.Is there a way to detect within my Strategy if it is executed in Multi-Symbol Backtest mode?
Yes. You can find the necessary code here
.Is it possible to tell in a Strategy if it is executed in Raw Profit mode or in Portfolio Simulation mode?
Yes. Install the Community Components library
from our site and then use this function in your Strategy: IsRawProfitMode
.I'm trying to divide two numbers and the result is zero.Symptoms:
You're trying to divide two apparently double
numbers and get 0 e.g.
double d = 123 / 456;Answer:
In C#, this is considered to be an integer division i.e. "123" and/or "456" are integer
numbers, therefore you get 0.
You have to perform an implicit cast to double
or specify the divisor as a double
double d1 = 123 / 456d;
double d2 = 123 / (double)456;
double d3 = 123 / 456.0;
PrintDebug(d1 , d2 , d3 );Can I detect divergences using Wealth-Lab?
Sure. First, there's a built-in indicator: Divergence
. Next, there are existing strategies illustrating various techniques of divergence detection: Leader of the MACD
, Asymmetric RSI
, Smooted RSI Inverse Fisher
. Finally, we've got a DivergencePlotter
routine helping to detect and plot divergences between two DataSeries.Is there a way to read/write values to an open Excel sheet?
Yes, basically there are two approaches:
1. Using COM wrapper:
Prerequisite: install Visual Studio Tools for Office
2. Read and write Excel sheet names and cell values using database technology:Note:
To work with XLSX files, installing Microsoft Access Database Engine 2007/2010 redistributable is a prerequisite - just as it is when working with both XLS or XLSX files on 64-bit Windows. Moreover you need to adjust the connection string respectively.I'm using Wealth-Lab 6.4 but can't use C# 3.0/4.0 language features such as LINQ, Tasks etc. What's wrong?
Unfortunately, the built-in Strategy Editor in version 6.4 does not support the new language features. Support for them may be added starting from version 6.5. Workarounds:
- Strategy libraries: It's possible to use all language features in compiled Strategy libraries (How to create a Strategy Library. Example: Strategies.ActiveTrader).
- Strategy Editor: In Editor, click "References" and add a reference to required assembly from the GAC with respect to the "bitness". Example: to utilize LINQ, add a reference to C:\Windows\Microsoft.NET\Framework (or Framework64)\v4.0.30319\System.Core.dll.