API documentation, members, signatures, and C# examples.
Search the framework
Find classes, members, and documentation.
NamespaceWealthLab.Backtest
Parent
Object
The Position class represents a long or short position generated by the WealthLab backtester. A long Position results from a buy transaction, while a short Position results from a short transaction.
A Position contains information about its entry and exit, quantity, profit and loss, commissions, excursions, position metrics, currency conversion, and other details associated with the simulated or live position.
Contains the BacktestSettings instance associated with this Position.
This allows a Position to retain the settings under which it was generated, including Futures Mode and Multi-Currency settings.
Returns the BarHistory instance on which this Position is based.
Strategies that trade multiple symbols can use this property to determine the symbol and historical data associated with a particular Position.
Returns the index occupied by this Position in the Backtester Positions collection.
This property is primarily useful to Performance Visualizers and other components that work directly with the Backtester Positions collection.
Indicates whether this Position represents a live broker Position.
WL9 can use this property to render live broker Positions differently from backtest Positions.
Returns true if the Position was open as of the specified DateTime dt.
The method returns false if the Position had not yet been entered at dt, and also returns false if it had already exited by that time.
Indicates whether the Position was rejected because there was not sufficient simulated capital available to take the trade.
NSF stands for "Not Sufficient Funds."
Returns the Position's Quantity formatted for display.
If Bars is available, the quantity is formatted using the number of quantity decimal places specified by Bars.QuantityDecimals. Otherwise, it is formatted with no decimal places.
Allows a C# Coded Strategy to associate arbitrary Strategy-specific information with a Position.
If the Transaction that created the Position has a Tag, that value can be passed along to the resulting Position.
Returns the Position's cost basis in the base currency.
For ordinary securities this is EntryPrice multiplied by Quantity and the exchange rate at entry.
In Futures Mode, futures use the contract margin multiplied by Quantity and the exchange rate. Options and futures options use 100 times EntryPrice multiplied by Quantity and the exchange rate.
Returns the Position's cost basis in the trade's currency.
For ordinary securities this is EntryPrice multiplied by Quantity.
In Futures Mode, futures use the contract margin multiplied by Quantity. Options and futures options use 100 times EntryPrice multiplied by Quantity.
Creates a new Position whose entry occurs at the specified entryBar.
The constructor initializes ExitBar to -1, indicating an open Position, and PositionTag to -1.
Positions are normally created and managed by the WealthLab backtester rather than instantiated directly by Strategies.
Contains the price that was used to determine the Position's quantity.
For Market and MarketClose orders, the basis price is normally based on the price selected in Backtest Settings. For Limit and Stop orders, it is generally the specified limit or stop price.
The actual EntryPrice can differ from BasisPrice because of gaps, slippage, and other execution effects.
Returns the commission charged when the Position was entered.
In a Multi-Currency backtest, EntryCommission is expressed in the base currency.
See also EntryCommissionNonBase.
Returns the Position's entry date formatted for display according to the scale of its BarHistory.
If GranularEntryTime is available, that time is appended to the formatted date.
Returns EntryPrice formatted using the number of price decimal places specified by the Position's BarHistory.
If Bars is null, two decimal places are used.
Returns the TransactionType that represents an entry for this Position.
For a long Position this returns TransactionType.Buy. For a short Position it returns TransactionType.Short.
Gets or sets the exchange rate used when the Position was entered.
This value is used for Multi-Currency calculations. Assigning Double.NaN causes the property to use 1.0 instead.
Contains the Position's more precise entry time when granular processing information is available.
The property is null when no granular entry time is available.
Returns the effective current exit price of the Position.
For an open Position, this is the latest closing price. For a closed Position, it is ExitPrice.
Gets or sets the most recent exchange rate associated with the Position.
For a closed Position this is used as the exit exchange rate. Assigning Double.NaN causes the property to use 1.0 instead.
Returns the Position's exit date formatted for display.
If the Position is open, returns "Open". If GranularExitTime is available, that time is included in the formatted value.
Returns the TransactionType that represents an exit for this Position.
For a long Position this returns TransactionType.Sell. For a short Position it returns TransactionType.Cover.
Contains the Position's more precise exit time when granular processing information is available.
The property is null when no granular exit time is available.
Returns the latest applicable price for the Position.
For an open Position, this is the latest closing price in Bars. For a closed Position, it is ExitPrice.
Returns true if the Position is operating under Futures Mode.
The Position's BacktestSettings must have Futures Mode enabled, the security type must support Futures Mode, and the associated SymbolInfo must have valid Margin and PointValue values.
Returns the Maximum Adverse Excursion generated by the Position, including commissions.
In a Multi-Currency backtest, MAE is expressed in the base currency.
MAE is normally negative or zero.
Returns the Maximum Adverse Excursion in the base currency as of the specified bar, including commissions.
Use this method when evaluating an active Position during Strategy execution.
Returns the Position's Maximum Adverse Excursion as a percentage.
For Multi-Currency backtests this value is calculated with respect to the base currency.
Returns the Maximum Favorable Excursion generated by the Position, including commissions.
In a Multi-Currency backtest, MFE is expressed in the base currency.
Returns the Maximum Favorable Excursion in the base currency as of the specified bar, including commissions.
Use this method when evaluating an active Position during Strategy execution.
Returns the Position's Maximum Favorable Excursion as a percentage.
For Multi-Currency backtests this value is calculated with respect to the base currency.
Returns a descriptive name for the Position's MetaStrategy component.
The value consists of the component Strategy's qualified name followed by its scale.
Returns an empty string if MetaStrategyComponent is null.
Returns the value of the Position in the base currency as of the specified bar idx.
Set useOpenPrice to true to value the Position using the bar's opening price. Set it to false to use the closing price.
For Futures Mode, the value includes the Position's futures margin plus its gain or loss as of the specified bar.
Gets or sets the Dictionary containing the Position's custom metrics.
The Dictionary keys are metric names and the values are the corresponding metric values.
Assigns value to the custom Position Metric named metric.
If the Position's PositionMetrics Dictionary has not yet been created, the method creates it automatically.
Returns the highest price reached during the lifetime of the Position.
For an open Position, the calculation extends through the final available bar. For a closed Position, it extends through the exit.
Returns the highest price reached by the Position as of bar idx.
The calculation accounts for entry and exit order types so that price movement that occurred before the Position was entered or after it exited on a particular bar is not incorrectly included.
Returns the Position's profit or loss expressed as price points.
For a long Position this is the latest price minus EntryPrice. For a short Position the sign is reversed.
Returns the Position's profit or loss in the base currency as of the specified bar idx.
Use this method during Strategy execution when you need the Position's profit at a particular point in the backtest.
C# example
using WealthLab.Backtest;
using WealthLab.Core;
using WealthLab.Indicators;
namespace WealthScript
{
public class ProfitAsOfExample : UserStrategyBase
{
private SMA _sma;
public override void Initialize(BarHistory bars)
{
StartIndex = 20;
_sma = SMA.Series(bars.Close, 20);
PlotIndicator(_sma);
}
public override void Execute(BarHistory bars, int idx)
{
if (!HasOpenPosition(bars, PositionType.Long))
{
if (bars.Close.CrossesOver(_sma, idx))
PlaceTrade(bars, TransactionType.Buy, OrderType.Market);
}
else
{
Position pos = LastPosition;
if (pos.ProfitAsOf(idx) >= 500.0)
ClosePosition(
pos,
OrderType.Market,
exitSignalName: "$500 Profit");
}
}
}
}
Returns a TimeSeries representing the Position's profit in the base currency over its lifetime.
The TimeSeries begins at EntryBar and continues through the Position's exit or the end of its BarHistory.
Returns the Position's profit or loss in the trade's currency, including commissions.
For an open Position, this property should only be accessed during the Cleanup or BacktestComplete phases. During normal Strategy execution use ProfitAsOf or ProfitPctAsOf instead.
Returns the Position's percentage profit in the base currency as of the specified bar idx.
This method is appropriate for use during Strategy execution.
C# example
using WealthLab.Backtest;
using WealthLab.Core;
using WealthLab.Indicators;
namespace WealthScript
{
public class ProfitPctAsOfExample : UserStrategyBase
{
private SMA _sma;
public override void Initialize(BarHistory bars)
{
StartIndex = 20;
_sma = SMA.Series(bars.Close, 20);
}
public override void Execute(BarHistory bars, int idx)
{
if (!HasOpenPosition(bars, PositionType.Long))
{
if (bars.Close.CrossesOver(_sma, idx))
PlaceTrade(bars, TransactionType.Buy, OrderType.Market);
}
else
{
Position pos = LastPosition;
if (pos.ProfitPctAsOf(idx) >= 6.0)
ClosePosition(
pos,
OrderType.Market,
exitSignalName: "6% Profit");
}
}
}
}
Returns the Position's percentage profit in the base currency.
For Futures Mode, the calculation can be either margin-based or raw price percentage-based according to Backtest Settings.
For calculations during Strategy execution, use ProfitPctAsOf.
Returns true when the Position is operating in Futures Mode and Backtest Settings specify that futures percentage profit should be based on raw price movement rather than futures margin.
Calculates and updates TrailingStopPrice for the Position as of bar idx using the specified TrailingStopType and amount.
Depending on tst, the trailing stop can be based on closing prices, high/low prices, percentages, or ATR.
For TrailingStopType.ATR, amount represents the ATR multiple and atrPeriod specifies the ATR period.
For a long Position, TrailingStopPrice can only move higher. For a short Position, it can only move lower.
The method does nothing if the Position is already closed.
Contains the stop-loss level established for the Position when Max Risk Percent position sizing is used.
This value can be used to issue a stop-loss order designed to keep the Position's maximum loss within the desired risk amount.
Returns the number of bars the Position was held.
For an open Position, BarsHeld is calculated through the final bar of its BarHistory. For a closed Position, the calculation also considers whether the Position exited at the market open and the CountMarketExitAsFullBar setting.
Returns the Backtest Settings value that determines whether a Position that exits at the market open counts its exit bar as a full bar when calculating BarsHeld.
Returns the number of trading days that have passed since the Position was established when using intraday data.
Returns -1 for non-intraday BarHistory scales.
When countByLastBarOfDay is false, the count advances as new trading days begin. When true, the current trading day is counted when idx represents its final bar.
Need help with this API?
Ask the community or explore custom development services.