BenchmarkBacktestResults
public Backtester BenchmarkBacktestResultsReturns the Backtester containing the results of the benchmark Buy & Hold run. Returns null if a benchmark backtest has not been generated.
API documentation, members, signatures, and C# examples.
Find classes, members, and documentation.
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.
public Backtester BenchmarkBacktestResultsReturns the Backtester containing the results of the benchmark Buy & Hold run. Returns null if a benchmark backtest has not been generated.
public TimeSeries CashCurveReturns a TimeSeries representing the simulated cash balance throughout the backtest.
public double CashInterestEarnedReturns the total simulated interest earned on positive cash balances during the backtest.
public TimeSeries ClosedEquityReturns 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.
public double CommissionsPaidReturns the total simulated commissions paid during the backtest.
public double CurrentBuyingPowerReturns 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.
public double CurrentCashReturns 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.
public double CurrentEquityReturns 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.
public TimeSeries DailyReturnsReturns a TimeSeries containing percentage returns calculated from the equity curve on a daily basis.
public double DividendsPaidReturns the total simulated dividends collected during the backtest when dividend collection is enabled in Backtest Settings.
public TimeSeries DrawdownCurveReturns a TimeSeries representing the account's drawdown from its previous equity high. Drawdown is calculated from the simulated equity curve using closing values.
public TimeSeries DrawdownPctCurveReturns a TimeSeries representing percentage drawdown from the account's previous equity high.
public TimeSeries EquityCurveReturns the simulated equity curve. The curve reflects cash plus the current marked value of open positions.
public double MarginInterestPaidReturns the total simulated margin interest paid during the backtest.
public TimeSeries MonthlyNegativeReturnsReturns a TimeSeries containing only negative monthly percentage returns. This series is used by calculations such as the Sortino Ratio.
public TimeSeries MonthlyReturnsReturns a TimeSeries containing monthly percentage returns calculated from the equity curve.
public double NetProfitReturns the net profit of the backtest, calculated as CurrentEquity - StartingCapital.
public double NetProfitPctReturns Net Profit expressed as a percentage of Starting Capital. If Starting Capital is zero, returns zero.
public int OpenPositionCountReturns the number of currently open, non-NSF Positions.
public TimeSeries OpenPositionCountHistoryReturns a TimeSeries containing the number of open, non-NSF Positions over the course of the backtest.
public TimeSeries PrePrunedEquityCurveReturns a copy of the equity curve before WealthLab removes the bars preceding the Strategy's StartIndex.
public TimeSeries SameBarExposureReturns a TimeSeries containing the amount of same-bar exposure during the backtest.
public TimeSeries TradeCountHistoryReturns a TimeSeries containing the number of trades entered during each simulation interval. This is not a cumulative trade count.
public TimeSeries YearlyReturnsReturns a TimeSeries containing yearly percentage returns calculated from the equity curve.
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.
public Backtester RunBenchmarkBacktest(BarHistory benchmarkData)Runs a Buy & Hold benchmark backtest using the supplied BarHistory. The resulting Backtester is assigned to BenchmarkBacktestResults and returned.
public Exception BacktestExceptionContains the Exception associated with a failed backtest, when one was recorded. Returns null when no Backtest Exception was recorded.
public List<string> ExceptionMessagesContains exception or error messages accumulated during the backtest.
public Position FindOpenPositionAllSymbols(string symbol, PositionType pt)Returns an open Position matching the symbol and PositionType, including Positions created using secondary-symbol BarHistory instances.
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.
public double GetOpenPositionQuantity(string symbol, PositionType pt)Returns the total quantity of all open Positions matching the specified symbol and PositionType.
public BacktestSettings BacktestSettingsReturns the BacktestSettings used for the simulation. Backtester maintains its own cloned BacktestSettings instance.
public Dictionary<string, object> CacheProvides 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.
public StrategyBase CompiledStrategyReturns the executable StrategyBase instance used to perform the backtest.
public DateTime CurrentDateReturns the date currently being processed during backtest execution.
public string ExecutionDataSetNameReturns the name of the DataSet used for the execution. Returns null when the execution is not associated with a DataSet.
public StrategyExecutionMode ExecutionModeReturns the context in which the Strategy is being executed.
Possible values are:
public StrategyExecutionPhase ExecutionPhaseReturns the current phase of Strategy execution.
public bool IsBenchmarkBacktestReturns true when this Backtester represents a benchmark Buy & Hold run.
public PositionSize PositionSizeReturns the PositionSize configuration used by the backtest.
public double StartingCapitalReturns the starting capital configured in PositionSize.
public Strategy StrategyReturns the Strategy definition associated with the backtest.
public List<BarHistory> SymbolsReturns the BarHistory instances that participated in the backtest.
public bool UseGranularProcessingReturns true when the current Backtest Settings cause WealthLab to use a lower intraday scale for granular processing of entry Signals.
public bool WasCanceledIndicates whether the backtest was canceled before normal completion.
public BrokerAccount LiveAccountReturns 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)
{
}
}
}
public dynamic MetricsReturns 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.
public double RiskFreeRateOfReturnReturns 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.
public PositionList AllOpenPositionsReturns all currently open Positions, combining the normal OpenPositions and NSFOpenPositions collections.
public Backtester LongResultsReturns a Backtester containing results derived from only the Long Positions in the backtest. The value is created on demand.
public PositionList LosingPositionsReturns the Positions whose Profit is less than or equal to zero. Consequently, break-even Positions are included in LosingPositions.
public PositionList NSFOpenPositionsReturns the NSF Positions that remain open at the end of the backtest.
public PositionList NSFPositionsReturns 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.
public PositionList OpenPositionsReturns the Positions that remain open. After backtest post-processing, NSF open Positions are separated into NSFOpenPositions.
public List<string> PositionMetricNamespublic PositionList PositionsReturns 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.
public Backtester ShortResultsReturns a Backtester containing results derived from only the Short Positions in the backtest. The value is created on demand.
public PositionList WinningPositionsReturns the Positions whose Profit is greater than zero. Positions with a Profit of exactly zero are not included.
public int? CancelationCodeAssign 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;
}
}
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.
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.
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.
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.
public List<Transaction> OrdersReturns 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.
public List<Transaction> PenultimateSignalsReturns 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.
public List<Transaction> TransactionLogReturns 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.
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.
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.
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.
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.
public List<IndicatorBase> GetPlots(string symbol)Returns the Indicators plotted by the Strategy for the specified symbol.
public List<string> PlottedIndicatorsReturns persisted descriptions of Indicators that were recorded for plotting. This information is used by WealthLab features that need to reconstruct Strategy Indicator plots.
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.
Ask the community or explore custom development services.