NAUTILUS / RUST source 3eb18933
Pages

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.

Account Management

Relevant Rust source files

  • crates/model/src/accounts/mod.rs
  • crates/model/src/accounts/cash.rs
  • crates/model/src/accounts/margin.rs
  • crates/portfolio/src/portfolio.rs

NautilusTrader's account management system tracks trading account state across different venue types and account models. This includes balance tracking, margin calculations, leverage configuration, and account event handling from both live and simulated venues.

This page explains:

  • Account types (CashAccount, MarginAccount, and BettingAccount)
  • Account state representation via AccountState events
  • Balance tracking (total, free, locked)
  • Margin calculations and leverage management
  • The AccountsManager and its role in the system

Account Type Hierarchy

NautilusTrader supports three specialized account types, each inheriting from a base Account class to handle specific balance management and risk characteristics.

Account Type Class Use Cases Leverage
CASH CashAccount Spot trading, non-leveraged positions No (1.0x)
MARGIN MarginAccount Futures, perpetuals, leveraged spot Yes
BETTING BettingAccount Sports betting, prediction markets No

Code Entity Mapping: Account Models

The following diagram bridges the natural language concepts of account types to their specific implementation classes and identifiers across the Rust layers.

Diagram — Account Entity Mapping

Account State and Balance Tracking

AccountState Event

The AccountState object is the primary data structure for conveying account snapshots across the system. It is generated by the AccountsManager or execution clients.

Field Type Description
account_id AccountId Unique identifier for the account.
balances list[AccountBalance] List of total, locked, and free amounts per currency.
margins list[MarginBalance] Initial and maintenance requirements (Margin only).
reported bool True if the state was reported by an external venue.

Balance Types

Accounts maintain three distinct balance metrics for every held currency:

  1. Total: The absolute amount of currency held.
  2. Locked: Capital reserved for open orders or as margin for open positions.
  3. Free: Capital available for new trades (Total - Locked).

In a CashAccount, submitting a BUY order locks the quote currency (cost + fees), while a SELL order locks the base currency (the asset being sold) If total locked exceeds total balance due to latency, the account clamps locked to total to avoid crashes

Margin and Leverage Management

MarginAccount allows for leveraged trading by tracking instrument-specific requirements and supporting both isolated and cross-margin modes.

Leverage Configuration

Leverage can be set globally for the account or overridden for specific instruments.

  • set_default_leverage(leverage): Sets the fallback leverage
  • set_leverage(instrument_id, leverage): Overrides leverage for a specific asset

Cross-Margin and Per-Currency Queries

NautilusTrader supports account-wide (cross-margin) requirements, often used in crypto derivatives.

  • account_margins(): Returns cross-margin balances keyed by collateral currency
  • margins(): Returns per-instrument (isolated) margin balances

Margin Calculations

The MarginAccount uses a MarginModel (defaulting to LeveragedMarginModel) to calculate requirements

Diagram — Margin Calculation Flow

Interactive Brokers venue reports returning through ExecutionEngine into cache and portfolio state after the outbound order passes RiskEngine.

An OrderFilled event and its canonical instrument and position identity drive account balance, PnL, and margin-model calculations. The resulting AccountState and margin balances are internal projections of the accepted venue event, not provider-specific objects.

Account Event Handling

Account management is orchestrated by the AccountsManager, which coordinates state updates between the Cache and the individual Account objects.

The AccountsManager

The AccountsManager is responsible for:

  1. Updating Balances: Processing OrderFilled events to adjust cash and margin
  2. State Generation: Creating AccountState snapshots for the rest of the system
  3. Order Updates: Locking or unlocking balances as orders are created or canceled

Data Flow: Fill to Balance Update

When an order is filled, the following flow occurs:

  1. An OrderFilled event is received by the system.
  2. AccountsManager.update_balances is called with the fill event
  3. The manager retrieves the associated Position from the Cache
  4. The specific Account (Cash or Margin) calculates PnL via calculate_pnls
  5. Balances are updated for either single-currency or multi-currency configurations

Betting Accounts

The BettingAccount is a specialized version of a CashAccount used for betting exchanges like Betfair. It enforces AccountType.CASH internally while specialized for betting logic

  • Stake Locking: Instead of locking base/quote currency, it manages locks specific to betting stakes.
  • PnL: Calculated based on the outcome of the betting market rather than standard security price movement.

Precision and Portfolio Integration

All accounting in NautilusTrader uses fixed-point arithmetic via the Money, Price, and Quantity classes to avoid floating-point errors.

Portfolio State Synchronization

The Portfolio component uses AccountsManager to maintain its internal state.

  • Portfolio contains an AccountsManager instance
  • It registers handlers for AccountState events to update the portfolio's view of balances
  • The PortfolioAnalyzer uses these balances to calculate statistics like Sharpe Ratio and Profit Factor