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.
Allows Broker Adapters to associate broker-specific information with the 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 is currently open. A Position is considered open when ExitBar is -1.
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."
Gets or sets an integer tag used by the backtester to track specific Positions.
Specifies whether the Position is long or short. Possible values are:
- PositionType.Long
- PositionType.Short
Returns the number of shares or contracts that comprise the Position.
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.
Gets or sets the DateTime associated with the signal that resulted in this Position.
Returns the symbol associated with the Position's Bars property. Returns null if Bars is null.
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.
Allows Performance Visualizers and similar components to associate arbitrary information with a Position.
Returns the Position's total commission in the base currency. This is the sum of EntryCommission and ExitCommission.
Returns the Position's total commission in the trade's currency. This is the sum of EntryCommissionNonBase and ExitCommissionNonBase.
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.
Contains the accumulated gain or loss attributable to currency conversion when Multi-Currency processing is enabled.
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 bar index in the Position's Bars where the Position entry occurred.
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 entry commission expressed in the trade's currency. This is particularly useful in Multi-Currency backtests.
Returns the DateTime corresponding to EntryBar. If EntryBar is beyond the available BarHistory, returns DateTime.MinValue.
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 the OrderType used to establish the Position.
Returns the price at which the Position was entered.
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.
Contains the signal name associated with the Transaction that opened this Position. The signal name is also displayed in the Positions visualizer.
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 bar index where the Position exited. Returns -1 while the Position remains open.
Returns the commission charged when the Position was exited. In a Multi-Currency backtest, ExitCommission is expressed in the base currency.
Returns the exit commission expressed in the trade's currency.
Returns the DateTime corresponding to ExitBar. If the Position is still open, returns DateTime.MaxValue.
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.
Indicates whether the Position exited at the market open. This property is used when calculating BarsHeld.
Returns the OrderType used to close the Position.
Returns the price at which the Position was exited. For an open Position, this value is normally zero.
Returns ExitPrice formatted for display. Returns "Open" if the Position is still open.
Contains the signal name associated with the Transaction that closed the Position. For an open Position, the value is normally an empty string.
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.
Indicates whether the Position's order was a Limit or Stop order that filled at the market open.
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 last applicable bar index for the Position. For an open Position, this is the last bar in Bars. For a closed Position, it is ExitBar.
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 in the trade's currency, including commissions.
Returns the Position's Maximum Adverse Excursion in the trade's currency as of the specified bar, including commissions.
Returns the Position's Maximum Adverse Excursion percentage in the base currency as of the specified bar.
Returns the Position's Maximum Adverse Excursion percentage in the trade's currency as of the specified bar.
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 Position's Maximum Adverse Excursion percentage in the trade's 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 in the trade's currency, including commissions.
Returns the Position's Maximum Favorable Excursion in the trade's currency as of the specified bar, including commissions.
Returns the Position's Maximum Favorable Excursion percentage in the base currency as of the specified bar.
Returns the Position's Maximum Favorable Excursion percentage in the trade's currency as of the specified bar.
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 the Position's Maximum Favorable Excursion percentage in the trade's currency.
Gets or sets the MetaStrategyComponent associated with this Position. Returns null when the Position is not associated with a MetaStrategy component.
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 a string describing the Position. The string contains the PositionType, Quantity, and symbol when a BarHistory is available.
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.
Returns the value of the Position Metric named metric. Returns Double.NaN if the Position has no metric with the specified name.
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 lowest price reached during the lifetime of the Position.
Returns the lowest price reached by the Position as of bar idx. The calculation accounts for entry and exit order types.
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 percentage profit per bar. The value is ProfitPercent divided by BarsHeld. Returns zero when BarsHeld is zero.
Returns the Position's profit or loss in the base currency, including commissions.
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.
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 the Position's profit expressed as a percentage of current portfolio equity. This value is calculated and assigned by the backtester.
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.
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 profit in the base currency divided by BarsHeld. Returns zero when BarsHeld is zero.
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 the Position's percentage profit in the trade's currency.
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.
Contains the most recently established trailing stop price for the Position. The default value is Double.NaN.
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.