Search Framework:
Position
Namespace: WealthLab.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.

Basic Properties
BacktestSettings
public BacktestSettings BacktestSettings

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.


Bars
public BarHistory Bars

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.


BrokerTag
public object BrokerTag

Allows Broker Adapters to associate broker-specific information with the Position.


Index
public int Index

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.


IsLiveBrokerPosition
public bool IsLiveBrokerPosition

Indicates whether this Position represents a live broker Position. WL9 can use this property to render live broker Positions differently from backtest Positions.


IsOpen
public bool IsOpen

Returns true if the Position is currently open. A Position is considered open when ExitBar is -1.


IsOpenAsOf
public bool IsOpenAsOf(DateTime dt)

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.


NSF
public bool NSF

Indicates whether the Position was rejected because there was not sufficient simulated capital available to take the trade. NSF stands for "Not Sufficient Funds."


PositionTag
public int PositionTag

Gets or sets an integer tag used by the backtester to track specific Positions.


PositionType
public PositionType PositionType

Specifies whether the Position is long or short. Possible values are:

  • PositionType.Long
  • PositionType.Short

Quantity
public double Quantity

Returns the number of shares or contracts that comprise the Position.


QuantityDisplay
public string QuantityDisplay

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.


SignalDate
public DateTime SignalDate

Gets or sets the DateTime associated with the signal that resulted in this Position.


Symbol
public string Symbol

Returns the symbol associated with the Position's Bars property. Returns null if Bars is null.


Tag
public object Tag

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.


VisualizerTag
public object VisualizerTag

Allows Performance Visualizers and similar components to associate arbitrary information with a Position.



Commissions and Cost Basis
Commission
public double Commission

Returns the Position's total commission in the base currency. This is the sum of EntryCommission and ExitCommission.


CommissionNonBase
public double CommissionNonBase

Returns the Position's total commission in the trade's currency. This is the sum of EntryCommissionNonBase and ExitCommissionNonBase.


CostBasis
public double CostBasis

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.


CostBasisNonBase
public double CostBasisNonBase

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.


CurrencyAdjustment
public double CurrencyAdjustment

Contains the accumulated gain or loss attributable to currency conversion when Multi-Currency processing is enabled.



Constructors
Position
public Position(int entryBar)

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.



Entry Properties
BasisPrice
public double BasisPrice

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.


EntryBar
public int EntryBar

Returns the bar index in the Position's Bars where the Position entry occurred.


EntryCommission
public double EntryCommission

Returns the commission charged when the Position was entered. In a Multi-Currency backtest, EntryCommission is expressed in the base currency. See also EntryCommissionNonBase.


EntryCommissionNonBase
public double EntryCommissionNonBase

Returns the entry commission expressed in the trade's currency. This is particularly useful in Multi-Currency backtests.


EntryDate
public DateTime EntryDate

Returns the DateTime corresponding to EntryBar. If EntryBar is beyond the available BarHistory, returns DateTime.MinValue.


EntryDateString
public string EntryDateString

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.


EntryOrderType
public OrderType EntryOrderType

Returns the OrderType used to establish the Position.


EntryPrice
public double EntryPrice

Returns the price at which the Position was entered.


EntryPriceString
public string EntryPriceString

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.


EntrySignalName
public string EntrySignalName

Contains the signal name associated with the Transaction that opened this Position. The signal name is also displayed in the Positions visualizer.


EntryTransactionType
public TransactionType EntryTransactionType

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.


ExchangeRateAtEntry
public double ExchangeRateAtEntry

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.


GranularEntryTime
public TimeSpan? GranularEntryTime

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.



Exit Properties
EffectiveExitPrice
public double EffectiveExitPrice

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.


ExchangeRateLast
public double ExchangeRateLast

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.


ExitBar
public int ExitBar

Returns the bar index where the Position exited. Returns -1 while the Position remains open.


ExitCommission
public double ExitCommission

Returns the commission charged when the Position was exited. In a Multi-Currency backtest, ExitCommission is expressed in the base currency.


ExitCommissionNonBase
public double ExitCommissionNonBase

Returns the exit commission expressed in the trade's currency.


ExitDate
public DateTime ExitDate

Returns the DateTime corresponding to ExitBar. If the Position is still open, returns DateTime.MaxValue.


ExitDateString
public string ExitDateString

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.


ExitedAtMarketOpen
public bool ExitedAtMarketOpen

Indicates whether the Position exited at the market open. This property is used when calculating BarsHeld.


ExitOrderType
public OrderType ExitOrderType

Returns the OrderType used to close the Position.


ExitPrice
public double ExitPrice

Returns the price at which the Position was exited. For an open Position, this value is normally zero.


ExitPriceString
public string ExitPriceString

Returns ExitPrice formatted for display. Returns "Open" if the Position is still open.


ExitSignalName
public string ExitSignalName

Contains the signal name associated with the Transaction that closed the Position. For an open Position, the value is normally an empty string.


ExitTransactionType
public TransactionType ExitTransactionType

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.


FilledAtOpenLimitOrStop
public bool FilledAtOpenLimitOrStop

Indicates whether the Position's order was a Limit or Stop order that filled at the market open.


GranularExitTime
public TimeSpan? GranularExitTime

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.


LastBar
public int LastBar

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.


LastPrice
public double LastPrice

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.



Futures
FuturesMode
public bool FuturesMode

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.



Maximum Adverse Excursion
MAE
public double MAE

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.


MAEAsOf
public double MAEAsOf(int bar)

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.


MAENonBase
public double MAENonBase

Returns the Position's Maximum Adverse Excursion in the trade's currency, including commissions.


MAENonBaseAsOf
public double MAENonBaseAsOf(int bar)

Returns the Position's Maximum Adverse Excursion in the trade's currency as of the specified bar, including commissions.


MAEPctAsOf
public double MAEPctAsOf(int bar)

Returns the Position's Maximum Adverse Excursion percentage in the base currency as of the specified bar.


MAEPctNonBaseAsOf
public double MAEPctNonBaseAsOf(int bar)

Returns the Position's Maximum Adverse Excursion percentage in the trade's currency as of the specified bar.


MAEPercent
public double MAEPercent

Returns the Position's Maximum Adverse Excursion as a percentage. For Multi-Currency backtests this value is calculated with respect to the base currency.


MAEPercentNonBase
public double MAEPercentNonBase

Returns the Position's Maximum Adverse Excursion percentage in the trade's currency.



Maximum Favorable Excursion
MFE
public double MFE

Returns the Maximum Favorable Excursion generated by the Position, including commissions. In a Multi-Currency backtest, MFE is expressed in the base currency.


MFEAsOf
public double MFEAsOf(int bar)

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.


MFENonBase
public double MFENonBase

Returns the Position's Maximum Favorable Excursion in the trade's currency, including commissions.


MFENonBaseAsOf
public double MFENonBaseAsOf(int bar)

Returns the Position's Maximum Favorable Excursion in the trade's currency as of the specified bar, including commissions.


MFEPctAsOf
public double MFEPctAsOf(int bar)

Returns the Position's Maximum Favorable Excursion percentage in the base currency as of the specified bar.


MFEPctNonBaseAsOf
public double MFEPctNonBaseAsOf(int bar)

Returns the Position's Maximum Favorable Excursion percentage in the trade's currency as of the specified bar.


MFEPercent
public double MFEPercent

Returns the Position's Maximum Favorable Excursion as a percentage. For Multi-Currency backtests this value is calculated with respect to the base currency.


MFEPercentNonBase
public double MFEPercentNonBase

Returns the Position's Maximum Favorable Excursion percentage in the trade's currency.



MetaStrategy
MetaStrategyComponent
public MetaStrategyComponent MetaStrategyComponent

Gets or sets the MetaStrategyComponent associated with this Position. Returns null when the Position is not associated with a MetaStrategy component.


MetaStrategyName
public string MetaStrategyName

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.



Other Methods
ToString
public override string ToString()

Returns a string describing the Position. The string contains the PositionType, Quantity, and symbol when a BarHistory is available.


ValueAsOf
public double ValueAsOf(
int idx,
bool useOpenPrice)

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.



Position Metrics
GetMetric
public double GetMetric(string metric)

Returns the value of the Position Metric named metric. Returns Double.NaN if the Position has no metric with the specified name.


PositionMetrics
public Dictionary<string, double> PositionMetrics

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.


SetMetric
public void SetMetric(
string metric,
double value)

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.



Price Excursions
HighestHigh
public double HighestHigh

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.


HighestHighAsOf
public double HighestHighAsOf(int idx)

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.


LowestLow
public double LowestLow

Returns the lowest price reached during the lifetime of the Position.


LowestLowAsOf
public double LowestLowAsOf(int idx)

Returns the lowest price reached by the Position as of bar idx. The calculation accounts for entry and exit order types.



Profit
PointProfit
public double PointProfit

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.


PPPB
public double PPPB

Returns the Position's percentage profit per bar. The value is ProfitPercent divided by BarsHeld. Returns zero when BarsHeld is zero.


Profit
public double Profit

Returns the Position's profit or loss in the base currency, including commissions.


ProfitAsOf
public double ProfitAsOf(int idx)

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.

Example Code
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");
            }
        }
    }
}

ProfitAsPctOfCurrentEquity
public double ProfitAsPctOfCurrentEquity

Returns the Position's profit expressed as a percentage of current portfolio equity. This value is calculated and assigned by the backtester.


ProfitCurve
public TimeSeries ProfitCurve

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.


ProfitNonBase
public double ProfitNonBase

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.


ProfitPctAsOf
public double ProfitPctAsOf(int idx)

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.

Example Code
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");
            }
        }
    }
}

ProfitPerBar
public double ProfitPerBar

Returns the Position's profit in the base currency divided by BarsHeld. Returns zero when BarsHeld is zero.


ProfitPercent
public double ProfitPercent

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.


ProfitPercentNonBase
public double ProfitPercentNonBase

Returns the Position's percentage profit in the trade's currency.


UseRawProfitFutures
public bool UseRawProfitFutures

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.



Risk and Trailing Stops
EstablishTrailingStopValue
public void EstablishTrailingStopValue(
int idx,
TrailingStopType tst,
double amount,
int atrPeriod = 22)

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.


RiskStopLevel
public double RiskStopLevel

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.


TrailingStopPrice
public double TrailingStopPrice

Contains the most recently established trailing stop price for the Position. The default value is Double.NaN.



Time in Position
BarsHeld
public int BarsHeld

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.


CountMarketExitAsFullBar
public bool CountMarketExitAsFullBar

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.


DaysInPosition
public int DaysInPosition(
int idx,
bool countByLastBarOfDay)

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.