Rust edition: this page follows the live DeepWiki structure but treats the current Rust crates as implementation authority. Non-Rust surfaces are identified at their boundary and are not presented as Rust APIs.
Position and Portfolio Management
Relevant Rust source files
crates/model/src/position.rscrates/portfolio/src/portfolio.rscrates/analysis/src/analyzer.rs
Overview
Position and portfolio management in NautilusTrader tracks the complete lifecycle of trading positions through order fills, position adjustments, and closures while maintaining accurate PnL calculations. The system supports two Order Management System (OMS) types—HEDGING and NETTING—which determine position identification and aggregation. The Portfolio component aggregates positions across strategies and instruments, tracks account balances via the AccountsManager, and calculates unrealized PnL using real-time market data.
This guide covers:
- Rust
Positionstructure and lifecycle. - OMS types (
HEDGINGvsNETTING) and position ID generation - PnL calculations for standard and inverse instruments
PositionAdjustedevents for commission and funding adjustments- Portfolio accounting and exposure tracking
PortfolioAnalyzerandReportProviderfor performance statistics and reporting
Position Class Structure
Core Position Model
The Rust Position struct represents a trading position for one instrument and applies fills to update quantity, average price, realized PnL, and lifecycle state.
Position Entity Mapping
Position Identifiers and Properties
Key position properties tracked by the Position class:
| Property | Type | Description |
|---|---|---|
id |
PositionId |
Unique identifier (OMS-type dependent) |
instrument_id |
InstrumentId |
Associated trading instrument |
side |
PositionSide |
LONG, SHORT, or FLAT |
signed_qty |
double |
Signed quantity (+ for LONG, - for SHORT) |
avg_px_open |
double |
Volume-weighted average open price |
realized_pnl |
Money |
Cumulative realized PnL including commissions |
ts_opened |
uint64_t |
UNIX timestamp (ns) when position was opened |
Order Management System (OMS) Types
OMS types determine how positions are identified and tracked per instrument.
OMS Type Variants
The OmsType enum defines how fills aggregate into positions :
| OMS Type | Behavior | Position ID Generation |
|---|---|---|
NETTING |
Single position per instrument/strategy. Fills offset each other. | Handled by system-generated netting IDs |
HEDGING |
Multiple concurrent positions allowed for the same instrument. | Sequential P- prefix IDs or venue-assigned |
The ExecutionEngine manages oms_overrides per strategy
Position Lifecycle and State Transitions
Side Transition Logic
Position side transitions are driven by OrderFilled events via the apply() method In Rust, this logic is encapsulated in Position::new and subsequent fill processing
Position Side State Machine
A position progresses from flat to long or short as fills arrive, may reduce to flat, and may flip when an opposing fill exceeds the current quantity. Portfolio updates are projections of accepted fill events rather than independent venue truth.
Rebuilding and Purging
NautilusTrader allows for the purging of specific order events from a position, which triggers a full state recalculation from the remaining fills The Rust implementation purge_events_for_order preserves non-commission adjustments while replaying fills to reconstruct the position state
PnL Calculations
Standard vs Inverse Instruments
NautilusTrader supports both linear and inverse PnL accounting.
Standard (Linear) PnL:
Calculated in quote currency.
PnL = Quantity * Multiplier * (ClosePrice - OpenPrice)
Inverse PnL:
Common in crypto derivatives (e.g., BitMEX XBTUSD). Quantity is in USD, but PnL is in BTC.
PnL = Quantity * Multiplier * (1/OpenPrice - 1/ClosePrice)
Unrealized PnL and Mark Prices
The Portfolio component tracks unrealized PnL by subscribing to market data updates
- Quote Ticks: Uses the mid-price or last trade price
- Mark Prices: High-precision prices provided by venues for derivatives valuation
Portfolio Management and Accounting
The Portfolio Component
The Portfolio is the central hub for tracking the global state of all accounts and positions. It uses an AccountsManager to handle balance updates and margin requirements
Portfolio Accounting Data Flow
Account and Balance Management
The AccountsManager coordinates updates between positions and accounts. It handles:
- Balance Updates: Adjusting available and locked balances based on fills
- Margin Requirements: Calculating initial and maintenance margin for
MarginAccounttypes - Betting Accounts: Specialized logic for betting exchange balance locking
Performance Analysis and Reporting
PortfolioAnalyzer
The PortfolioAnalyzer calculates high-level performance metrics by aggregating trade data and account returns. It is integrated directly into the PortfolioState
Core Performance Statistics:
- Risk Ratios:
SharpeRatio,SortinoRatio,ProfitFactor,RiskReturnRatio - Trade Stats:
WinRate,AvgWinner,AvgLoser,Expectancy,MaxWinner,MaxLoser - Returns Analysis:
ReturnsVolatility,ReturnsAverage,ReturnsAverageWin,ReturnsAverageLoss
ReportProvider
The ReportProvider generates structured reports for orders, fills, positions, and accounts.
- Execution Reports: The
ExecutionEnginetracksExecutionReportandExecutionMassStatus - Position Snapshots: Netting OMS positions are snapshotted to track historical state
- Portfolio Snapshots: The
Portfoliomaintains a buffer ofPortfolioSnapshotevents for analysis
Exposure Tracking
The Portfolio tracks net exposure per instrument and account using net_positions This is maintained within the PortfolioState and updated as positions change side or quantity