Parent: Object
The Backtester class executes WealthLab 9 backtests and provides access to the resulting positions, transactions, equity curves, performance metrics, and other simulation information. The Backtester instance for a running C# Strategy is available through the Backtester property of UserStrategyBase. The Backtester contains the underlying trading methods used by UserStrategyBase. Strategy code will normally call the equivalent UserStrategyBase methods directly.
Returns the Backtester containing the results of the benchmark Buy & Hold run. Returns null if a benchmark backtest has not been generated.
Returns a TimeSeries representing the simulated cash balance throughout the backtest.
Returns the total simulated interest earned on positive cash balances during the backtest.
Returns the closed-equity curve for the backtest. Closed equity reflects cash plus the cost basis of currently open positions rather than marking those positions to their current market value.
Returns the total simulated commissions paid during the backtest.
Returns the current simulated buying power. When margin is not being used, this is generally the current cash balance. When margin is enabled, WealthLab calculates available buying power using current equity, the configured margin factor, and the value of existing open positions.
Returns the current simulated cash balance. During Strategy execution, this represents cash at the current point in the simulation. After the backtest is complete, it represents the ending cash balance.
Returns the current simulated account equity, including cash and the current value of open positions. During Strategy execution, this represents equity at the current point in the simulation. After the backtest is complete, it represents ending equity.
Returns a TimeSeries containing percentage returns calculated from the equity curve on a daily basis.
Returns the total simulated dividends collected during the backtest when dividend collection is enabled in Backtest Settings.
Returns a TimeSeries representing the account's drawdown from its previous equity high. Drawdown is calculated from the simulated equity curve using closing values.
Returns a TimeSeries representing percentage drawdown from the account's previous equity high.
Returns the simulated equity curve. The curve reflects cash plus the current marked value of open positions.
Returns the total simulated margin interest paid during the backtest.
Returns a TimeSeries containing only negative monthly percentage returns. This series is used by calculations such as the Sortino Ratio.
Returns a TimeSeries containing monthly percentage returns calculated from the equity curve.
Returns the net profit of the backtest, calculated as CurrentEquity - StartingCapital.
Returns Net Profit expressed as a percentage of Starting Capital. If Starting Capital is zero, returns zero.
Returns the number of currently open, non-NSF Positions.
Returns a TimeSeries containing the number of open, non-NSF Positions over the course of the backtest.
Returns a copy of the equity curve before WealthLab removes the bars preceding the Strategy's StartIndex.
Returns a TimeSeries containing the amount of same-bar exposure during the backtest.
Returns a TimeSeries containing the number of trades entered during each simulation interval. This is not a cumulative trade count.
Returns a TimeSeries containing yearly percentage returns calculated from the equity curve.
Creates and executes a benchmark Buy & Hold Backtester using the supplied simulation settings. Most Strategy code will use RunBenchmarkBacktest rather than calling this static method directly.
Runs a Buy & Hold benchmark backtest using the supplied BarHistory. The resulting Backtester is assigned to BenchmarkBacktestResults and returned.
Contains the Exception associated with a failed backtest, when one was recorded. Returns null when no Backtest Exception was recorded.
Contains exception or error messages accumulated during the backtest.
Returns an open Position matching the symbol and PositionType, including Positions created using secondary-symbol BarHistory instances.
Returns an open Position matching the supplied criteria. The Transaction overload locates the Position associated with a Transaction. The BarHistory and PositionType overload optionally restricts the search using a Position Tag. The BarHistory and Position Tag overload locates a tagged Position. The symbol overload returns an open Position matching the specified symbol and PositionType.
Returns the total quantity of all open Positions matching the specified symbol and PositionType.
Returns the BacktestSettings used for the simulation. Backtester maintains its own cloned BacktestSettings instance.
Provides a general-purpose Dictionary associated with the Backtester. WealthLab uses this collection when information needs to persist across Strategy instances during operations such as optimization.
Returns the executable StrategyBase instance used to perform the backtest.
Returns the date currently being processed during backtest execution.
Returns the name of the DataSet used for the execution. Returns null when the execution is not associated with a DataSet.
Returns the context in which the Strategy is being executed.
Possible values are:
- Strategy
- Optimization
- StreamingChart
- StrategyMonitor
- Rankings
- Evolver
- SignalPublisher
Returns the current phase of Strategy execution.
Returns true when this Backtester represents a benchmark Buy & Hold run.
Returns the PositionSize configuration used by the backtest.
Returns the starting capital configured in PositionSize.
Returns the BarHistory instances that participated in the backtest.
Returns true when the current Backtest Settings cause WealthLab to use a lower intraday scale for granular processing of entry Signals.
Indicates whether the backtest was canceled before normal completion.
Returns the BrokerAccount supplied to the Backtester when WealthLab is running the Strategy using Live Positions. This allows Strategy code to examine the actual broker account rather than relying exclusively on simulated account values. Returns null when Live Positions are not being used.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Data; using WealthLab.Indicators; using System.Collections.Generic; namespace WealthScript123 { public class LiveAccountDemo : UserStrategyBase { public override void Initialize(BarHistory bars) { double curreq = CurrentEquity; string acctName = "Backtester"; if (Backtester.LiveAccount != null) { acctName = Backtester.LiveAccount.AccountID; curreq = Backtester.LiveAccount.AccountValue; DrawHeaderText($"{acctName}: {curreq:N2}", WLColor.NeonGreen, 14); foreach (BrokerPosition bp in Backtester.LiveAccount.Positions) DrawHeaderText($"{bp.Quantity} {bp.Symbol}", WLColor.NeonGreen, 10); } else DrawHeaderText($"{acctName}: {curreq:N2}", WLColor.Gold, 14); } public override void Execute(BarHistory bars, int idx) { } } }
Returns the Backtester's dynamic Performance Metrics collection. ScoreCards populate this object with named Metrics such as Metrics.NetProfit, Metrics.APR, and Metrics.SharpeRatio. Because Metrics is dynamic, installed ScoreCards can contribute additional named values. Performance Visualizers, Optimizers, and other extensions can access these values after the ScoreCards have calculated them.
Returns the risk-free rate used for Performance Metric calculations. If BacktestSettings.UseUSTRateAsInterest is false, this returns the configured CashInterestRate. If U.S. Treasury rates are enabled, WealthLab calculates an average one-year U.S. Treasury yield synchronized with the backtest's equity curve.
Returns all currently open Positions, combining the normal OpenPositions and NSFOpenPositions collections.
Returns a Backtester containing results derived from only the Long Positions in the backtest. The value is created on demand.
Returns the Positions whose Profit is less than or equal to zero. Consequently, break-even Positions are included in LosingPositions.
Returns the NSF Positions that remain open at the end of the backtest.
Returns Positions flagged as NSF (non-sufficient funds). An NSF Position represents a theoretical Strategy trade that WealthLab could not take because sufficient simulated capital or buying power was unavailable. NSF Positions can still be tracked so that Strategy logic and resulting exit Signals remain consistent.
Returns the Positions that remain open. After backtest post-processing, NSF open Positions are separated into NSFOpenPositions.
Returns the Positions included in the completed backtest results. NSF Positions are separated into the NSFPositions collection during post-processing and are not included in this collection.
Returns a Backtester containing results derived from only the Short Positions in the backtest. The value is created on demand.
Returns the Positions whose Profit is greater than zero. Positions with a Profit of exactly zero are not included.
Assign a value to CancelationCode before creating related orders to associate them with the same cancellation group. When one order in the group fills, other open orders with the same CancelationCode for that symbol are canceled. The same code can therefore be reused independently for different symbols.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Data; using WealthLab.Indicators; using System.Collections.Generic; namespace WealthScript123 { public class MyStrategy : UserStrategyBase { public MyStrategy() { _period = AddParameter("Period", ParameterType.Int32, 10, 5, 20, 1); } public override void Initialize(BarHistory bars) { _ma = SMA.Series(bars.Close, _period.AsInt); PlotIndicator(_ma); PlotStopsAndLimits(3); StartIndex = _period.AsInt; } public override void Execute(BarHistory bars, int idx) { if (!HasOpenPosition(bars, PositionType.Long)) { if (bars.Close.CrossesOver(_ma, idx)) { Transaction t = PlaceTrade(bars, TransactionType.Buy, OrderType.Market); } } else { Position p = LastPosition; Backtester.CancelationCode = 12; ClosePosition(p, OrderType.Stop, p.EntryPrice * 0.92, "8% S/L"); if (p.MFEPctAsOf(idx) >= 5) { Backtester.CancelationCode = 12; CloseAtTrailingStop(p, TrailingStopType.PercentC, 4.0, "Tstop"); } Backtester.CancelationCode = 12; ClosePosition(p, OrderType.Limit, p.EntryPrice * 1.10, "10% Tgt"); } } Parameter _period; SMA _ma; } }
Updates the Position's trailing stop according to the specified TrailingStopType and amount, then generates a Stop order at the resulting trailing stop price.
Creates an exit Transaction that closes the supplied Position. The appropriate Sell or Cover TransactionType is determined automatically from the Position's PositionType.
Creates a Transaction using the supplied order information, applies Position Sizing, and adds the resulting Transaction to the Backtester's Orders and TransactionLog collections. Returns the resulting Transaction.
Generates a Market Transaction, if necessary, to bring the Long Position in the supplied symbol toward the specified percentage of current equity. Returns null when no trade is required.
Returns the current collection of pending Transaction instances. At the end of a normal Strategy run, these typically represent Signals generated for the next market session.
Returns the set of Signals captured immediately before the final set of Signals. WealthLab uses this collection for processing such as at-close signaling in the Strategy Monitor.
Returns the Transaction instances generated during the backtest. Unlike the final Orders collection, TransactionLog retains Transactions generated throughout the simulation and can therefore be used to examine the Strategy's order activity.
Calculates the commission for the supplied Transaction using the Backtester's commission settings. The method also assigns the calculated commission to the Transaction and the appropriate entry or exit commission properties of the Position.
Calculates and assigns the quantity of the supplied Transaction using the Backtester's current Position Sizing configuration. Optionally supply currentEquity to perform the calculation using an equity value other than the Backtester's current equity.
Generates monthly percentage returns from the EquityCurve. Set includeLastPartialMonth to true to include the final incomplete month. Set negOnly to true to include only months with negative returns. The MonthlyReturns and MonthlyNegativeReturns properties use this method internally.
Returns the current execution index for the supplied BarHistory. This is useful when working with different BarHistory instances during synchronized Strategy processing.
Returns the Indicators plotted by the Strategy for the specified symbol.
Returns persisted descriptions of Indicators that were recorded for plotting. This information is used by WealthLab features that need to reconstruct Strategy Indicator plots.
Returns true when Futures Mode is enabled in Backtest Settings and the supplied BarHistory's SymbolInfo indicates that Futures Mode can be used.