Accounting¶
The accounting subpackage defines both different account types and account management machinery.
There is also an ExchangeRateCalculator for calculating the exchange rate between FX and/or Crypto pairs. The AccountManager is mainly used from the Portfolio to manage accounting operations.
The AccountFactory supports customized account types for specific integrations. These custom account types can be registered with the factory and will then be instantiated when an AccountState event is received for that integration.
A cash account that cannot hold leveraged positions.
Balance locking¶
The account tracks locked balances per (InstrumentId, Currency) to support instruments that lock different currencies depending on order side:
BUY orders lock quote currency (cost of purchase).
SELL orders lock base currency (assets being sold).
Callers must clear all existing locks via clear_balance_locked before applying new locks. This prevents stale currency entries when order compositions change.
Graceful degradation¶
When total locked exceeds total balance (e.g., due to venue/client state latency), the account clamps locked to total rather than raising an error. This yields zero free balance, preventing new orders while avoiding crashes in live trading.
- class CashAccount¶
Bases:
AccountCashAccount(AccountState event, bool calculate_account_state=False, bool allow_borrowing=False)
Provides a cash account.
- Parameters:
event (AccountState) – The initial account state event.
calculate_account_state (bool, optional) – If the account state should be calculated from order fills.
allow_borrowing (bool, optional) – If borrowing is allowed (negative balances).
- Raises:
ValueError – If event.account_type is not equal to
CASH.
- ACCOUNT_TYPE = 1¶
- allow_borrowing¶
If borrowing is allowed (negative balances).
- Returns:
bool
- apply(self, AccountState event) void¶
Apply the given account event to the account.
Clears per-instrument locked balances only for externally reported state, since external state is authoritative. Internal state preserves lock tracking.
- Parameters:
event (AccountState) – The account event to apply.
Warning
System method (not intended to be called by user code).
- balance(self, Currency currency=None) AccountBalance¶
Return the current account balance total.
For multi-currency accounts, specify the currency for the query.
- Parameters:
currency (Currency, optional) – The currency for the query. If
Nonethen will use the default currency (if set).- Return type:
AccountBalance or
None- Raises:
ValueError – If currency is
Noneand base_currency isNone.
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- balance_free(self, Currency currency=None) Money¶
Return the account balance free.
For multi-currency accounts, specify the currency for the query.
- Parameters:
currency (Currency, optional) – The currency for the query. If
Nonethen will use the default currency (if set).- Return type:
Money or
None- Raises:
ValueError – If currency is
Noneand base_currency isNone.
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- balance_impact(self, Instrument instrument, Quantity quantity, Price price, OrderSide order_side) Money¶
- balance_locked(self, Currency currency=None) Money¶
Return the account balance locked.
For multi-currency accounts, specify the currency for the query.
- Parameters:
currency (Currency, optional) – The currency for the query. If
Nonethen will use the default currency (if set).- Return type:
Money or
None- Raises:
ValueError – If currency is
Noneand base_currency isNone.
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- balance_total(self, Currency currency=None) Money¶
Return the current account balance total.
For multi-currency accounts, specify the currency for the query.
- Parameters:
currency (Currency, optional) – The currency for the query. If
Nonethen will use the default currency (if set).- Return type:
Money or
None- Raises:
ValueError – If currency is
Noneand base_currency isNone.
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- base_currency¶
The accounts base currency (
Nonefor multi-currency accounts).- Returns:
Currency or
None
- calculate_account_state¶
If the accounts state should be calculated by Nautilus.
- Returns:
bool
- calculate_balance_locked(self, Instrument instrument, OrderSide side, Quantity quantity, Price price, bool use_quote_for_inverse=False) Money¶
Calculate the locked balance.
Result will be in quote currency for standard instruments, or base currency for inverse instruments.
- Parameters:
instrument (Instrument) – The instrument for the calculation.
side (OrderSide {
BUY,SELL}) – The order side.quantity (Quantity) – The order quantity.
price (Price) – The order price.
use_quote_for_inverse (bool) – If inverse instrument calculations use quote currency (instead of base).
- Return type:
- calculate_commission(self, Instrument instrument, Quantity last_qty, Price last_px, LiquiditySide liquidity_side, bool use_quote_for_inverse=False) Money¶
Calculate the commission generated from a transaction with the given parameters.
Result will be in quote currency for standard instruments, or base currency for inverse instruments.
- Parameters:
instrument (Instrument) – The instrument for the calculation.
last_qty (Quantity) – The transaction quantity.
last_px (Price) – The transaction price.
liquidity_side (LiquiditySide {
MAKER,TAKER}) – The liquidity side for the transaction.use_quote_for_inverse (bool) – If inverse instrument calculations use quote currency (instead of base).
- Return type:
- Raises:
ValueError – If liquidity_side is
NO_LIQUIDITY_SIDE.
- calculate_pnls(self, Instrument instrument, OrderFilled fill, Position position: Position | None = None) list¶
Return the calculated PnL.
The calculation does not include any commissions.
- Parameters:
instrument (Instrument) – The instrument for the calculation.
fill (OrderFilled) – The fill for the calculation.
position (Position, optional) – The position for the calculation (can be None).
- Return type:
list[Money]
- clear_balance_locked(self, InstrumentId instrument_id) void¶
Clear all balances locked for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument for which to clear all locked balances.
- commission(self, Currency currency) Money¶
Return the total commissions for the given currency.
- Parameters:
currency (Currency) – The currency for the commission.
- Return type:
Money or
None
- commissions(self) dict¶
Return the total commissions for the account.
- event_count¶
Return the count of events.
- Return type:
int
- events¶
Return all events received by the account.
- Return type:
list[AccountState]
- static from_dict(dict values)¶
- id¶
The accounts ID.
- Returns:
AccountId
- is_cash_account¶
If the account is a type of
CASHaccount.
- is_margin_account¶
If the account is a type of
MARGINaccount.
- is_unleveraged(self, InstrumentId instrument_id) bool¶
- last_event¶
Return the accounts last state event.
- Return type:
- purge_account_events(self, uint64_t ts_now, uint64_t lookback_secs=0) void¶
Purge all account state events which are outside the lookback window.
Guaranteed to retain at least the latest event.
- Parameters:
ts_now (uint64_t) – The current UNIX timestamp (nanoseconds).
lookback_secs (uint64_t, default 0) – The purge lookback window (seconds) from when the account state event occurred. Only events which are outside the lookback window will be purged. A value of 0 means purge all account state events.
- starting_balances(self) dict¶
Return the account starting balances.
- static to_dict(CashAccount obj)¶
- type¶
The accounts type.
- Returns:
AccountType
- update_balance_locked(self, InstrumentId instrument_id, Money locked) void¶
Update the balance locked for the given instrument ID and currency.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the update.
locked (Money) – The locked balance for the instrument.
- Raises:
ValueError – If locked is negative (< 0).
Warning
System method (not intended to be called by user code).
- update_balances(self, list balances) void¶
Update the account balances.
There is no guarantee that every account currency is included in the given balances, therefore we only update included balances.
- Parameters:
balances (list[AccountBalance]) – The balances for the update.
- Raises:
ValueError – If balances is empty.
AccountBalanceNegative – If borrowing is not allowed and balance is negative.
A margin account capable of holding leveraged positions and tracking instrument-specific leverage ratios.
PnL calculation¶
The account calculates PnL differently based on instrument type:
Premium instruments (options, option spreads, binary options, warrants): Realize the notional value as a cash flow on every fill. BUY = negative (premium paid), SELL = positive (premium received).
Other instruments: Only realize PnL on position reduction (fill side opposite to entry). Use the minimum of fill and position quantity to avoid double-counting.
- class MarginAccount¶
Bases:
AccountMarginAccount(AccountState event, bool calculate_account_state=False)
Provides a margin account.
- Parameters:
event (AccountState) – The initial account state event.
calculate_account_state (bool, optional) – If the account state should be calculated from order fills.
- Raises:
ValueError – If event.account_type is not equal to
MARGIN.
- apply(self, AccountState event) void¶
Apply the given account event to the account.
- Parameters:
event (AccountState) – The account event to apply.
- Raises:
ValueError – If event.account_type is not equal to self.type.
ValueError – If event.account_id is not equal to self.id.
ValueError – If event.base_currency is not equal to self.base_currency.
Warning
System method (not intended to be called by user code).
- balance(self, Currency currency=None) AccountBalance¶
Return the current account balance total.
For multi-currency accounts, specify the currency for the query.
- Parameters:
currency (Currency, optional) – The currency for the query. If
Nonethen will use the default currency (if set).- Return type:
AccountBalance or
None- Raises:
ValueError – If currency is
Noneand base_currency isNone.
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- balance_free(self, Currency currency=None) Money¶
Return the account balance free.
For multi-currency accounts, specify the currency for the query.
- Parameters:
currency (Currency, optional) – The currency for the query. If
Nonethen will use the default currency (if set).- Return type:
Money or
None- Raises:
ValueError – If currency is
Noneand base_currency isNone.
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- balance_impact(self, Instrument instrument, Quantity quantity, Price price, OrderSide order_side) Money¶
- balance_locked(self, Currency currency=None) Money¶
Return the account balance locked.
For multi-currency accounts, specify the currency for the query.
- Parameters:
currency (Currency, optional) – The currency for the query. If
Nonethen will use the default currency (if set).- Return type:
Money or
None- Raises:
ValueError – If currency is
Noneand base_currency isNone.
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- balance_total(self, Currency currency=None) Money¶
Return the current account balance total.
For multi-currency accounts, specify the currency for the query.
- Parameters:
currency (Currency, optional) – The currency for the query. If
Nonethen will use the default currency (if set).- Return type:
Money or
None- Raises:
ValueError – If currency is
Noneand base_currency isNone.
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- base_currency¶
The accounts base currency (
Nonefor multi-currency accounts).- Returns:
Currency or
None
- calculate_account_state¶
If the accounts state should be calculated by Nautilus.
- Returns:
bool
- calculate_commission(self, Instrument instrument, Quantity last_qty, Price last_px, LiquiditySide liquidity_side, bool use_quote_for_inverse=False) Money¶
Calculate the commission generated from a transaction with the given parameters.
Result will be in quote currency for standard instruments, or base currency for inverse instruments.
- Parameters:
instrument (Instrument) – The instrument for the calculation.
last_qty (Quantity) – The transaction quantity.
last_px (Price) – The transaction price.
liquidity_side (LiquiditySide {
MAKER,TAKER}) – The liquidity side for the transaction.use_quote_for_inverse (bool) – If inverse instrument calculations use quote currency (instead of base).
- Return type:
- Raises:
ValueError – If liquidity_side is
NO_LIQUIDITY_SIDE.
- calculate_margin_init(self, Instrument instrument, Quantity quantity, Price price, bool use_quote_for_inverse=False) Money¶
Calculate the initial (order) margin.
Result will be in quote currency for standard instruments, or base currency for inverse instruments.
- Parameters:
instrument (Instrument) – The instrument for the calculation.
quantity (Quantity) – The order quantity.
price (Price) – The order price.
use_quote_for_inverse (bool) – If inverse instrument calculations use quote currency (instead of base).
- Return type:
- calculate_margin_maint(self, Instrument instrument, PositionSide side, Quantity quantity, Price price, bool use_quote_for_inverse=False) Money¶
Calculate the maintenance (position) margin.
Result will be in quote currency for standard instruments, or base currency for inverse instruments.
- Parameters:
instrument (Instrument) – The instrument for the calculation.
side (PositionSide {
LONG,SHORT}) – The currency position side.quantity (Quantity) – The currency position quantity.
price (Price) – The positions current price.
use_quote_for_inverse (bool) – If inverse instrument calculations use quote currency (instead of base).
- Return type:
- calculate_pnls(self, Instrument instrument, OrderFilled fill, Position position: Position | None = None) list¶
Return the calculated PnL.
The calculation does not include any commissions.
- Parameters:
instrument (Instrument) – The instrument for the calculation.
fill (OrderFilled) – The fill for the calculation.
position (Position, optional) – The position for the calculation.
- Return type:
list[Money]
- clear_margin(self, InstrumentId instrument_id) void¶
Clear the maintenance (position) margins for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument for the maintenance margin to clear.
Warning
System method (not intended to be called by user code).
- clear_margin_init(self, InstrumentId instrument_id) void¶
Clear the initial (order) margins for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument for the initial margin to clear.
Warning
System method (not intended to be called by user code).
- clear_margin_maint(self, InstrumentId instrument_id) void¶
Clear the maintenance (position) margins for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument for the maintenance margin to clear.
Warning
System method (not intended to be called by user code).
- commission(self, Currency currency) Money¶
Return the total commissions for the given currency.
- Parameters:
currency (Currency) – The currency for the commission.
- Return type:
Money or
None
- commissions(self) dict¶
Return the total commissions for the account.
- default_leverage¶
The accounts default leverage setting.
- Returns:
Decimal
- event_count¶
Return the count of events.
- Return type:
int
- events¶
Return all events received by the account.
- Return type:
list[AccountState]
- static from_dict(dict values)¶
- id¶
The accounts ID.
- Returns:
AccountId
- is_cash_account¶
If the account is a type of
CASHaccount.
- is_margin_account¶
If the account is a type of
MARGINaccount.
- is_unleveraged(self, InstrumentId instrument_id) bool¶
- last_event¶
Return the accounts last state event.
- Return type:
- leverage(self, InstrumentId instrument_id)¶
Return the leverage for the given instrument (if found).
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the leverage.
- Return type:
Decimal or
None
- leverages(self) dict¶
Return the account leverages.
- Return type:
dict[InstrumentId, Decimal]
- margin(self, InstrumentId instrument_id) MarginBalance¶
Return the current margin balance.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the query.
- Return type:
MarginBalance or
None
Warning
Returns
Noneif there is no applicable information for the query, rather than MarginBalance with zero amounts.
- margin_init(self, InstrumentId instrument_id) Money¶
Return the current initial (order) margin.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the query.
- Return type:
Money or
None
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- margin_maint(self, InstrumentId instrument_id) Money¶
Return the current maintenance (position) margin.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the query.
- Return type:
Money or
None
Warning
Returns
Noneif there is no applicable information for the query, rather than Money of zero amount.
- margins(self) dict¶
Return the initial (order) margins for the account.
- Return type:
dict[InstrumentId, Money]
- margins_init(self) dict¶
Return the initial (order) margins for the account.
- Return type:
dict[InstrumentId, Money]
- margins_maint(self) dict¶
Return the maintenance (position) margins for the account.
- Return type:
dict[InstrumentId, Money]
- purge_account_events(self, uint64_t ts_now, uint64_t lookback_secs=0) void¶
Purge all account state events which are outside the lookback window.
Guaranteed to retain at least the latest event.
- Parameters:
ts_now (uint64_t) – The current UNIX timestamp (nanoseconds).
lookback_secs (uint64_t, default 0) – The purge lookback window (seconds) from when the account state event occurred. Only events which are outside the lookback window will be purged. A value of 0 means purge all account state events.
- set_default_leverage(self, leverage: Decimal) void¶
Set the default leverage for the account (if not specified by instrument).
- Parameters:
leverage (Decimal) – The default leverage value
- Returns:
TypeError – If leverage is not of type Decimal.
ValueError – If leverage is not >= 1.
- set_leverage(self, InstrumentId instrument_id, leverage: Decimal) void¶
Set the leverage for the given instrument.
- Parameters:
instrument_id (InstrumentId) – The instrument for the leverage.
leverage (Decimal) – The leverage value
- Returns:
TypeError – If leverage is not of type Decimal.
ValueError – If leverage is not >= 1.
- set_margin_model(self, MarginModel margin_model) void¶
Set the margin calculation model for the account.
- Parameters:
margin_model (MarginModel) – The margin model to use for calculations.
- starting_balances(self) dict¶
Return the account starting balances.
- static to_dict(MarginAccount obj)¶
- type¶
The accounts type.
- Returns:
AccountType
- update_balances(self, list balances) void¶
Update the account balances.
There is no guarantee that every account currency is included in the given balances, therefore we only update included balances.
- Parameters:
balances (list[AccountBalance]) – The balances for the update.
- Raises:
ValueError – If balances is empty.
AccountBalanceNegative – If account type is
CASH, and balance is negative.
- update_commissions(self, Money commission) void¶
Update the commissions.
Can be negative which represents credited commission.
- Parameters:
commission (Money) – The commission to update with.
Warning
System method (not intended to be called by user code).
- update_margin(self, MarginBalance margin) void¶
Update the margin balance.
- Parameters:
margin (MarginBalance)
Warning
System method (not intended to be called by user code).
- update_margin_init(self, InstrumentId instrument_id, Money margin_init) void¶
Update the initial (order) margin.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the update.
margin_init (Money) – The current initial (order) margin for the instrument.
- Raises:
ValueError – If margin_init is negative (< 0).
Warning
System method (not intended to be called by user code).
- update_margin_maint(self, InstrumentId instrument_id, Money margin_maint) void¶
Update the maintenance (position) margin.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the update.
margin_maint (Money) – The current maintenance (position) margin for the instrument.
- Raises:
ValueError – If margin_maint is negative (< 0).
Warning
System method (not intended to be called by user code).
- class RolloverInterestCalculator¶
Bases:
objectRolloverInterestCalculator(data: pd.DataFrame)
Provides rollover interest rate calculations.
If rate_data_csv_path is empty then will default to the included short-term interest rate data csv (data since 1956).
- Parameters:
data (str) – The short term interest rate data.
- calc_overnight_rate(self, InstrumentId instrument_id, date date)¶
Return the rollover interest rate between the given base currency and quote currency.
- Parameters:
instrument_id (InstrumentId) – The forex instrument ID for the calculation.
date (date) – The date for the overnight rate.
- Return type:
Decimal
- Raises:
ValueError – If instrument_id.symbol length is not in range [6, 7].
Notes
1% = 0.01 bp
- get_rate_data(self)¶
Return the short-term interest rate dataframe.
- Return type:
pd.DataFrame
- class AccountFactory¶
Bases:
objectProvides a factory for creating different account types.
- static create(AccountState event) Account¶
Create an account based on the events account type.
- Parameters:
event (AccountState) – The account state event for the creation.
- Return type:
Account
- static deregister_cash_borrowing(str issuer)¶
Deregister cash borrowing for the given issuer.
This is primarily intended for test cleanup to prevent global state leakage.
- Parameters:
issuer (str) – The issuer to deregister.
- static register_account_type(str issuer, type account_cls)¶
Register the given custom account type for the issuer.
- Parameters:
issuer (str) – The issuer for the account.
account_cls (type) – The custom account type.
- Raises:
KeyError – If issuer has already registered a custom account type.
- static register_calculated_account(str issuer)¶
Register for account state of the given issuer to be calculated from order fills.
- Parameters:
issuer (str) – The issuer for the account.
- Raises:
KeyError – If an issuer has already been registered for the issuer.
- static register_cash_borrowing(str issuer)¶
Register for cash accounts of the given issuer to allow borrowing (negative balances).
- Parameters:
issuer (str) – The issuer for the account.
- Raises:
KeyError – If cash borrowing has already been registered for the issuer.
- class AccountsManager¶
Bases:
objectAccountsManager(CacheFacade cache, Logger logger, Clock clock) -> None
Provides account management functionality.
- Parameters:
cache (CacheFacade) – The read-only cache for the manager.
logger (Logger) – The logger for the manager.
clock (Clock) – The clock for the manager.
- generate_account_state(self, Account account, uint64_t ts_event) AccountState¶
Generate a new account state event for the given account.
- Parameters:
account (Account) – The account for the state event.
ts_event (uint64_t) – The UNIX timestamp (nanoseconds) when the event occurred.
- Return type:
- update_balances(self, Account account, Instrument instrument, OrderFilled fill) void¶
Update the account balances based on the fill event.
- Parameters:
account (Account) – The account to update.
instrument (Instrument) – The instrument for the update.
fill (OrderFilled) – The order filled event for the update
- Raises:
AccountBalanceNegative – If account type is
CASHand a balance becomes negative.
- update_orders(self, Account account, Instrument instrument, list orders_open, uint64_t ts_event) bool¶
Update the account states based on the given orders.
- Parameters:
account (MarginAccount) – The account to update.
instrument (Instrument) – The instrument for the update.
orders_open (list[Order]) – The open orders for the update.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the account event occurred.
- Returns:
The result of the account operation.
- Return type:
bool
- update_positions(self, MarginAccount account, Instrument instrument, list positions_open, uint64_t ts_event) bool¶
Update the maintenance (position) margin.
Will return
Noneif operation fails.- Parameters:
account (Account) – The account to update.
instrument (Instrument) – The instrument for the update.
positions_open (list[Position]) – The open positions for the update.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the account event occurred.
- Returns:
The result of the account operation.
- Return type:
bool