Framework Reference
WEALTHLAB FRAMEWORK / CLASS REFERENCE

Backtester

API documentation, members, signatures, and C# examples.

Search the framework

Find classes, members, and documentation.

NamespaceWealthLab.Backtest
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.

Backtest Result Properties

24

BenchmarkBacktestResults

public Backtester BenchmarkBacktestResults

Returns the Backtester containing the results of the benchmark Buy & Hold run. Returns null if a benchmark backtest has not been generated.

CashCurve

public TimeSeries CashCurve

Returns a TimeSeries representing the simulated cash balance throughout the backtest.

CashInterestEarned

public double CashInterestEarned

Returns the total simulated interest earned on positive cash balances during the backtest.

ClosedEquity

public TimeSeries ClosedEquity

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.

CommissionsPaid

public double CommissionsPaid

Returns the total simulated commissions paid during the backtest.

CurrentBuyingPower

public double CurrentBuyingPower

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.

CurrentCash

public double CurrentCash

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.

CurrentEquity

public double CurrentEquity

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.

DailyReturns

public TimeSeries DailyReturns

Returns a TimeSeries containing percentage returns calculated from the equity curve on a daily basis.

DividendsPaid

public double DividendsPaid

Returns the total simulated dividends collected during the backtest when dividend collection is enabled in Backtest Settings.

DrawdownCurve

public TimeSeries DrawdownCurve

Returns a TimeSeries representing the account's drawdown from its previous equity high. Drawdown is calculated from the simulated equity curve using closing values.

DrawdownPctCurve

public TimeSeries DrawdownPctCurve

Returns a TimeSeries representing percentage drawdown from the account's previous equity high.

EquityCurve

public TimeSeries EquityCurve

Returns the simulated equity curve. The curve reflects cash plus the current marked value of open positions.

MarginInterestPaid

public double MarginInterestPaid

Returns the total simulated margin interest paid during the backtest.

MonthlyNegativeReturns

public TimeSeries MonthlyNegativeReturns

Returns a TimeSeries containing only negative monthly percentage returns. This series is used by calculations such as the Sortino Ratio.

MonthlyReturns

public TimeSeries MonthlyReturns

Returns a TimeSeries containing monthly percentage returns calculated from the equity curve.

NetProfit

public double NetProfit

Returns the net profit of the backtest, calculated as CurrentEquity - StartingCapital.

NetProfitPct

public double NetProfitPct

Returns Net Profit expressed as a percentage of Starting Capital. If Starting Capital is zero, returns zero.

OpenPositionCount

public int OpenPositionCount

Returns the number of currently open, non-NSF Positions.

OpenPositionCountHistory

public TimeSeries OpenPositionCountHistory

Returns a TimeSeries containing the number of open, non-NSF Positions over the course of the backtest.

PrePrunedEquityCurve

public TimeSeries PrePrunedEquityCurve

Returns a copy of the equity curve before WealthLab removes the bars preceding the Strategy's StartIndex.

SameBarExposure

public TimeSeries SameBarExposure

Returns a TimeSeries containing the amount of same-bar exposure during the backtest.

TradeCountHistory

public TimeSeries TradeCountHistory

Returns a TimeSeries containing the number of trades entered during each simulation interval. This is not a cumulative trade count.

YearlyReturns

public TimeSeries YearlyReturns

Returns a TimeSeries containing yearly percentage returns calculated from the equity curve.

Benchmark Methods

2

GetBenchmarkBacktester

public static Backtester GetBenchmarkBacktester(BarHistory bmData, TimeSeries prePruned, int startIndex, BacktestSettings bts, PositionSize posSize, StrategyExecutionMode execMode, Strategy strat, string execDS)

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.

RunBenchmarkBacktest

public Backtester RunBenchmarkBacktest(BarHistory benchmarkData)

Runs a Buy & Hold benchmark backtest using the supplied BarHistory. The resulting Backtester is assigned to BenchmarkBacktestResults and returned.

Exceptions

2

BacktestException

public Exception BacktestException

Contains the Exception associated with a failed backtest, when one was recorded. Returns null when no Backtest Exception was recorded.

ExceptionMessages

public List<string> ExceptionMessages

Contains exception or error messages accumulated during the backtest.

Finding Positions

3

FindOpenPositionAllSymbols

public Position FindOpenPositionAllSymbols(string symbol, PositionType pt)

Returns an open Position matching the symbol and PositionType, including Positions created using secondary-symbol BarHistory instances.

FindPosition

public Position FindPosition(Transaction t)
public Position FindPosition(BarHistory bh, PositionType posType, int positionTag = -1)
public Position FindPosition(BarHistory bh, int positionTag)
public Position FindPosition(string symbol, PositionType pt)

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.

GetOpenPositionQuantity

public double GetOpenPositionQuantity(string symbol, PositionType pt)

Returns the total quantity of all open Positions matching the specified symbol and PositionType.

Informational Properties

14

Cache

public Dictionary<string, object> Cache

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.

CompiledStrategy

public StrategyBase CompiledStrategy

Returns the executable StrategyBase instance used to perform the backtest.

CurrentDate

public DateTime CurrentDate

Returns the date currently being processed during backtest execution.

ExecutionDataSetName

public string ExecutionDataSetName

Returns the name of the DataSet used for the execution. Returns null when the execution is not associated with a DataSet.

ExecutionMode

public StrategyExecutionMode ExecutionMode

Returns the context in which the Strategy is being executed.
Possible values are:

  • Strategy
  • Optimization
  • StreamingChart
  • StrategyMonitor
  • Rankings
  • Evolver
  • SignalPublisher

ExecutionPhase

public StrategyExecutionPhase ExecutionPhase

Returns the current phase of Strategy execution.

IsBenchmarkBacktest

public bool IsBenchmarkBacktest

Returns true when this Backtester represents a benchmark Buy & Hold run.

Strategy

public Strategy Strategy

Returns the Strategy definition associated with the backtest.

Symbols

public List<BarHistory> Symbols

Returns the BarHistory instances that participated in the backtest.

UseGranularProcessing

public bool UseGranularProcessing

Returns true when the current Backtest Settings cause WealthLab to use a lower intraday scale for granular processing of entry Signals.

WasCanceled

public bool WasCanceled

Indicates whether the backtest was canceled before normal completion.

Live Positions

1

LiveAccount

public BrokerAccount LiveAccount

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.

Performance Metrics

2

Metrics

public dynamic Metrics

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.

RiskFreeRateOfReturn

public double RiskFreeRateOfReturn

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.

Position Results

10

AllOpenPositions

public PositionList AllOpenPositions

Returns all currently open Positions, combining the normal OpenPositions and NSFOpenPositions collections.

LongResults

public Backtester LongResults

Returns a Backtester containing results derived from only the Long Positions in the backtest. The value is created on demand.

LosingPositions

public PositionList LosingPositions

Returns the Positions whose Profit is less than or equal to zero. Consequently, break-even Positions are included in LosingPositions.

NSFOpenPositions

public PositionList NSFOpenPositions

Returns the NSF Positions that remain open at the end of the backtest.

NSFPositions

public PositionList NSFPositions

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.

OpenPositions

public PositionList OpenPositions

Returns the Positions that remain open. After backtest post-processing, NSF open Positions are separated into NSFOpenPositions.

PositionMetricNames

public List<string> PositionMetricNames

Returns the names of the Position Metrics currently available. The list includes Metrics supplied by installed Position ScoreCards as well as custom Position Metrics that were assigned during Strategy execution.

Positions

public PositionList Positions

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.

ShortResults

public Backtester ShortResults

Returns a Backtester containing results derived from only the Short Positions in the backtest. The value is created on demand.

WinningPositions

public PositionList WinningPositions

Returns the Positions whose Profit is greater than zero. Positions with a Profit of exactly zero are not included.

Trading Control

1

CancelationCode

public int? CancelationCode

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.

Trading Methods

4

CloseAtTrailingStop

public void CloseAtTrailingStop(Position pos, TrailingStopType tst, double amount, string signalName = "", int atrPeriod = 22)

Updates the Position's trailing stop according to the specified TrailingStopType and amount, then generates a Stop order at the resulting trailing stop price.

ClosePosition

public void ClosePosition(Position pos, OrderType orderType, double price = 0, string exitSignalName = "")

Creates an exit Transaction that closes the supplied Position. The appropriate Sell or Cover TransactionType is determined automatically from the Position's PositionType.

PlaceTrade

public Transaction PlaceTrade(BarHistory bars, TransactionType transType, OrderType orderType, double price = 0, int positionTag = -1, string signalName = "")

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.

Rebalance

public Transaction Rebalance(BarHistory bars, double percentOfEquity)

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.

Transactions and Signals

3

Orders

public List<Transaction> Orders

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.

PenultimateSignals

public List<Transaction> PenultimateSignals

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.

TransactionLog

public List<Transaction> TransactionLog

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.

Utility Methods

7

CalculateCommission

public double CalculateCommission(Position pos, Transaction t)

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.

CalculatePositionSize

public void CalculatePositionSize(BarHistory bars, int idx, Transaction t, double? currentEquity = null)

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.

GenerateMonthlyReturns

public TimeSeries GenerateMonthlyReturns(bool includeLastPartialMonth, bool negOnly)

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.

GetCurrentIndex

public int GetCurrentIndex(BarHistory bh)

Returns the current execution index for the supplied BarHistory. This is useful when working with different BarHistory instances during synchronized Strategy processing.

GetPlots

public List<IndicatorBase> GetPlots(string symbol)

Returns the Indicators plotted by the Strategy for the specified symbol.

PlottedIndicators

public List<string> PlottedIndicators

Returns persisted descriptions of Indicators that were recorded for plotting. This information is used by WealthLab features that need to reconstruct Strategy Indicator plots.

UseFuturesMode

public bool UseFuturesMode(BarHistory bars)

Returns true when Futures Mode is enabled in Backtest Settings and the supplied BarHistory's SymbolInfo indicates that Futures Mode can be used.

Need help with this API?

Ask the community or explore custom development services.