Order Book¶
- class Blockchain
Bases:
objectRepresents different blockchain networks.
- ABSTRACT = Blockchain.ABSTRACT
- ARBITRUM = Blockchain.ARBITRUM
- ARBITRUM_NOVA = Blockchain.ARBITRUM_NOVA
- ARBITRUM_SEPOLIA = Blockchain.ARBITRUM_SEPOLIA
- AURORA = Blockchain.AURORA
- AVALANCHE = Blockchain.AVALANCHE
- BASE = Blockchain.BASE
- BASE_SEPOLIA = Blockchain.BASE_SEPOLIA
- BERACHAIN = Blockchain.BERACHAIN
- BERACHAIN_BARTIO = Blockchain.BERACHAIN_BARTIO
- BLAST = Blockchain.BLAST
- BLAST_SEPOLIA = Blockchain.BLAST_SEPOLIA
- BOBA = Blockchain.BOBA
- BSC = Blockchain.BSC
- BSC_TESTNET = Blockchain.BSC_TESTNET
- CELO = Blockchain.CELO
- CHILIZ = Blockchain.CHILIZ
- CITREA_TESTNET = Blockchain.CITREA_TESTNET
- CURTIS = Blockchain.CURTIS
- CYBER = Blockchain.CYBER
- DARWINIA = Blockchain.DARWINIA
- ETHEREUM = Blockchain.ETHEREUM
- FANTOM = Blockchain.FANTOM
- FLARE = Blockchain.FLARE
- FRAXTAL = Blockchain.FRAXTAL
- FUJI = Blockchain.FUJI
- GALADRIEL_DEVNET = Blockchain.GALADRIEL_DEVNET
- GNOSIS = Blockchain.GNOSIS
- GNOSIS_CHIADO = Blockchain.GNOSIS_CHIADO
- GNOSIS_TRACES = Blockchain.GNOSIS_TRACES
- HARMONY_SHARD0 = Blockchain.HARMONY_SHARD0
- HOLESKY = Blockchain.HOLESKY
- HOLESKY_TOKEN_TEST = Blockchain.HOLESKY_TOKEN_TEST
- HYPERLIQUID = Blockchain.HYPERLIQUID
- HYPERLIQUID_TEMP = Blockchain.HYPERLIQUID_TEMP
- INK = Blockchain.INK
- INTERNAL_TEST_CHAIN = Blockchain.INTERNAL_TEST_CHAIN
- KROMA = Blockchain.KROMA
- LINEA = Blockchain.LINEA
- LISK = Blockchain.LISK
- LUKSO = Blockchain.LUKSO
- LUKSO_TESTNET = Blockchain.LUKSO_TESTNET
- MANTA = Blockchain.MANTA
- MANTLE = Blockchain.MANTLE
- MEGAETH_TESTNET = Blockchain.MEGAETH_TESTNET
- MERLIN = Blockchain.MERLIN
- METALL2 = Blockchain.METALL2
- METIS = Blockchain.METIS
- MEV_COMMIT = Blockchain.MEV_COMMIT
- MODE = Blockchain.MODE
- MONAD_TESTNET = Blockchain.MONAD_TESTNET
- MONAD_TESTNET_BACKUP = Blockchain.MONAD_TESTNET_BACKUP
- MOONBASE_ALPHA = Blockchain.MOONBASE_ALPHA
- MOONBEAM = Blockchain.MOONBEAM
- MORPH = Blockchain.MORPH
- MORPH_HOLESKY = Blockchain.MORPH_HOLESKY
- OPBNB = Blockchain.OPBNB
- OPTIMISM = Blockchain.OPTIMISM
- OPTIMISM_SEPOLIA = Blockchain.OPTIMISM_SEPOLIA
- PHAROS_DEVNET = Blockchain.PHAROS_DEVNET
- POLYGON = Blockchain.POLYGON
- POLYGON_AMOY = Blockchain.POLYGON_AMOY
- POLYGON_ZK_EVM = Blockchain.POLYGON_ZK_EVM
- ROOTSTOCK = Blockchain.ROOTSTOCK
- SAAKURU = Blockchain.SAAKURU
- SCROLL = Blockchain.SCROLL
- SEPOLIA = Blockchain.SEPOLIA
- SHIMMER_EVM = Blockchain.SHIMMER_EVM
- SONEIUM = Blockchain.SONEIUM
- SOPHON = Blockchain.SOPHON
- SOPHON_TESTNET = Blockchain.SOPHON_TESTNET
- SUPERSEED = Blockchain.SUPERSEED
- UNICHAIN = Blockchain.UNICHAIN
- UNICHAIN_SEPOLIA = Blockchain.UNICHAIN_SEPOLIA
- XDC = Blockchain.XDC
- XDC_TESTNET = Blockchain.XDC_TESTNET
- ZETA = Blockchain.ZETA
- ZIRCUIT = Blockchain.ZIRCUIT
- ZORA = Blockchain.ZORA
- Z_KSYNC = Blockchain.Z_KSYNC
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class Chain
Bases:
objectDefines a blockchain with its unique identifiers and connection details for network interaction.
- static ARBITRUM()
- chain_id
- static from_chain_id(chain_id)
Returns a reference to the Chain corresponding to the given chain_id, or None if it is not found.
- static from_chain_name(chain_name)
Returns a reference to the Chain corresponding to the given chain name, or None if it is not found.
String matching is case-insensitive.
- hypersync_url
- name
- native_currency_decimals
- rpc_url
- set_rpc_url(rpc_url)
Sets the RPC URL endpoint.
- class Dex
Bases:
objectRepresents a decentralized exchange (DEX) in a blockchain ecosystem.
- amm_type
- burn_created_event
- chain
- factory
- factory_creation_block
- mint_created_event
- name
- pool_created_event
- swap_created_event
- class DexType
Bases:
objectRepresents different types of decentralized exchanges (DEXes) supported by Nautilus.
- AERODROME_SLIPSTREAM = DexType.AERODROME_SLIPSTREAM
- AERODROME_V1 = DexType.AERODROME_V1
- BALANCER_V2 = DexType.BALANCER_V2
- BALANCER_V3 = DexType.BALANCER_V3
- BASE_SWAP_V2 = DexType.BASE_SWAP_V2
- BASE_X = DexType.BASE_X
- CAMELOT_V3 = DexType.CAMELOT_V3
- CURVE_FINANCE = DexType.CURVE_FINANCE
- FLUID_DEX = DexType.FLUID_DEX
- MAVERICK_V1 = DexType.MAVERICK_V1
- MAVERICK_V2 = DexType.MAVERICK_V2
- PANCAKE_SWAP_V3 = DexType.PANCAKE_SWAP_V3
- SUSHI_SWAP_V2 = DexType.SUSHI_SWAP_V2
- SUSHI_SWAP_V3 = DexType.SUSHI_SWAP_V3
- UNISWAP_V2 = DexType.UNISWAP_V2
- UNISWAP_V3 = DexType.UNISWAP_V3
- UNISWAP_V4 = DexType.UNISWAP_V4
- class AccountBalance
Bases:
objectRepresents an account balance denominated in a particular currency.
- copy()
Returns a copy of this balance.
- currency
- free
- static from_dict(values)
Constructs an [AccountBalance] from a Python dict.
# Errors
Returns a PyErr if parsing or conversion fails.
- locked
- to_dict()
Converts this [AccountBalance] into a Python dict.
# Errors
Returns a PyErr if serialization fails.
- total
- class AccountId
Bases:
objectRepresents a valid account ID.
- static from_str(value)
- value
- class AccountState
Bases:
objectRepresents an event which includes information on the state of the account.
The optional info bag carries venue-specific account data that does not map to the typed balances and margins fields, such as wallet balance, available balance, or an account summary, so consumers can read the venue context that accompanied a given snapshot.
- account_id
- account_type
- balances
- base_currency
- event_id
- static from_dict(values)
Constructs an [AccountState] from a Python dict.
# Errors
Returns a PyErr if any required field is missing or type conversion fails.
- info
- is_reported
- margins
- to_dict()
Converts this [AccountState] into a Python dict.
# Errors
Returns a PyErr if serialization into a Python dict fails.
- ts_event
- ts_init
- class AccountType
Bases:
objectAn account type provided by a trading venue or broker.
- BETTING = AccountType.BETTING
- CASH = AccountType.CASH
- MARGIN = AccountType.MARGIN
- WALLET = AccountType.WALLET
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class ActorId
Bases:
objectRepresents a valid actor ID.
- static from_str(value)
- value
- class AggregationSource
Bases:
objectAn aggregation source for derived data.
- EXTERNAL = AggregationSource.EXTERNAL
- INTERNAL = AggregationSource.INTERNAL
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class AggressorSide
Bases:
objectThe side for the aggressing order of a trade in a market.
- BUY = AggressorSide.BUY
- NO_AGGRESSOR = AggressorSide.NO_AGGRESSOR
- SELL = AggressorSide.SELL
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class AmmType
Bases:
objectRepresents different types of Automated Market Makers (AMMs) in DeFi protocols.
- CLAMM = AmmType.CLAMM
- CLAM_ENHANCED = AmmType.CLAM_ENHANCED
- COMPOSABLE_POOL = AmmType.COMPOSABLE_POOL
- CPAMM = AmmType.CPAMM
- STABLE_SWAP = AmmType.STABLE_SWAP
- WEIGHTED_POOL = AmmType.WEIGHTED_POOL
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class AssetClass
Bases:
objectA broad financial market asset class.
- ALTERNATIVE = AssetClass.ALTERNATIVE
- COMMODITY = AssetClass.COMMODITY
- CRYPTOCURRENCY = AssetClass.CRYPTOCURRENCY
- DEBT = AssetClass.DEBT
- EQUITY = AssetClass.EQUITY
- FX = AssetClass.FX
- INDEX = AssetClass.INDEX
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class Bar
Bases:
objectRepresents an aggregated bar.
- bar_type
- close
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(bar_type, price_precision, size_precision)
Returns the metadata for the type, for use with serialization formats.
- high
- low
- open
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- ts_event
- ts_init
- volume
- class BarAggregation
Bases:
objectThe aggregation method through which a bar is generated and closed.
- DAY = BarAggregation.DAY
- HOUR = BarAggregation.HOUR
- MILLISECOND = BarAggregation.MILLISECOND
- MINUTE = BarAggregation.MINUTE
- MONTH = BarAggregation.MONTH
- RENKO = BarAggregation.RENKO
- SECOND = BarAggregation.SECOND
- TICK = BarAggregation.TICK
- TICK_IMBALANCE = BarAggregation.TICK_IMBALANCE
- TICK_RUNS = BarAggregation.TICK_RUNS
- VALUE = BarAggregation.VALUE
- VALUE_IMBALANCE = BarAggregation.VALUE_IMBALANCE
- VALUE_RUNS = BarAggregation.VALUE_RUNS
- VOLUME = BarAggregation.VOLUME
- VOLUME_IMBALANCE = BarAggregation.VOLUME_IMBALANCE
- VOLUME_RUNS = BarAggregation.VOLUME_RUNS
- WEEK = BarAggregation.WEEK
- YEAR = BarAggregation.YEAR
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class BarIntervalType
Bases:
objectThe interval type for bar aggregation.
- LEFT_OPEN = BarIntervalType.LEFT_OPEN
- RIGHT_OPEN = BarIntervalType.RIGHT_OPEN
- class BarSpecification
Bases:
objectRepresents a bar aggregation specification including a step, aggregation method/rule and price type.
- aggregation
- static check_information_aggregated(aggregation)
Returns whether the given aggregation is information-based.
- static check_threshold_aggregated(aggregation)
Returns whether the given aggregation is threshold-based.
- static check_time_aggregated(aggregation)
Returns whether the given aggregation is time-based.
- static from_str(value)
Creates a BarSpecification from a string representation.
- static from_timedelta(duration, price_type)
Creates a BarSpecification from a Python timedelta and price type.
- static fully_qualified_name()
- get_interval_ns()
Returns the interval length in nanoseconds for time-based bar specifications.
- is_information_aggregated()
Return a value indicating whether the aggregation method is information-driven: - BarAggregation.TickRuns - BarAggregation.VolumeRuns - BarAggregation.ValueRuns
- is_threshold_aggregated()
Return a value indicating whether the aggregation method is threshold-driven: - BarAggregation.Tick - BarAggregation.TickImbalance - BarAggregation.Volume - BarAggregation.VolumeImbalance - BarAggregation.Value - BarAggregation.ValueImbalance
- is_time_aggregated()
Return a value indicating whether the aggregation method is time-driven: - BarAggregation.Millisecond - BarAggregation.Second - BarAggregation.Minute - BarAggregation.Hour - BarAggregation.Day - BarAggregation.Week - BarAggregation.Month - BarAggregation.Year
- price_type
- step
- timedelta
Returns the SignedDuration interval for this bar specification.
# Notes
For BarAggregation.Month and BarAggregation.Year, proxy values are used (30 days for months, 365 days for years) to estimate their respective durations, since months and years have variable lengths.
- class BarType
Bases:
objectRepresents a bar type including the instrument ID, bar specification and aggregation source.
- class Composite
Bases:
BarType- aggregation_source
The bar type’s aggregation source.
- composite_aggregation
The composite type of bar aggregation.
- composite_aggregation_source
The composite bar type’s aggregation source.
- composite_step
The composite step for binning samples for bar aggregation.
- instrument_id
The bar type’s instrument ID.
- spec
The bar type’s specification.
- class Standard
Bases:
BarType- aggregation_source
The bar type’s aggregation source.
- instrument_id
The bar type’s instrument ID.
- spec
The bar type’s specification.
- aggregation_source
Returns the AggregationSource for this bar type.
- composite()
Returns any composite bar type component.
- static from_str(value)
- static fully_qualified_name()
- id_spec_key()
Returns the instrument ID and bar specification as a tuple key.
Useful as a hashmap key when aggregation source should be ignored, such as for indicator registration where INTERNAL and EXTERNAL bars should trigger the same indicators.
- instrument_id
Returns the InstrumentId for this bar type.
- is_composite()
Returns whether this instance is a composite bar type.
- is_externally_aggregated()
Returns whether the bar aggregation source is EXTERNAL.
- is_internally_aggregated()
Returns whether the bar aggregation source is INTERNAL.
- is_standard()
Returns whether this instance is a standard bar type.
- static new_composite(instrument_id, spec, aggregation_source, composite_step, composite_aggregation, composite_aggregation_source)
Creates a new composite BarType instance.
- spec
Returns the BarSpecification for this bar type.
- standard()
Returns the standard bar type component.
- class Bet
Bases:
objectA bet in a betting market.
- exposure()
Returns the bet’s exposure.
For BACK bets, exposure is positive; for LAY bets, it is negative.
- static from_liability(price, liability, side)
Creates a bet from a given liability.
- static from_stake(price, stake, side)
Creates a bet from a given stake.
- static from_stake_or_liability(price, volume, side)
Creates a bet from a stake or liability depending on the bet side.
For BetSide::Back this calls Self.from_stake and for BetSide::Lay it calls Self.from_liability.
- hedging_bet(price)
Creates a hedging bet for a given price.
- hedging_stake(price)
Returns the hedging stake given a new price.
- liability()
Returns the bet’s liability.
For BACK bets, liability equals the stake; for LAY bets, it is stake multiplied by (price - 1).
- outcome_lose_payoff()
Returns the outcome lose payoff.
For BACK bets this is the negative liability; for LAY bets it is the profit.
- outcome_win_payoff()
Returns the outcome win payoff.
For BACK bets this is the profit; for LAY bets it is the negative liability.
- price
Returns the bet’s price.
- profit()
Returns the bet’s profit.
For BACK bets, profit is stake * (price - 1); for LAY bets it equals the stake.
- side
Returns the bet’s side.
- stake
Returns the bet’s stake.
- class BetPosition
Bases:
objectA position comprising one or more bets.
- add_bet(bet)
Adds a bet to the position, adjusting exposure and realized PnL.
- as_bet()
Converts the current position into a single bet, if possible.
- exposure
Returns the position’s exposure.
- flattening_bet(price)
Creates a bet that would flatten (neutralize) the current position.
- price
Returns the position’s price.
- realized_pnl
Returns the position’s realized profit and loss.
- reset()
Resets the bet position to its initial state.
- side
Returns the overall side of the position.
If exposure is positive the side is BACK; if negative, LAY; if zero, None.
- total_pnl(price)
Returns the total profit and loss (realized plus unrealized) given a current price.
- unrealized_pnl(price)
Calculates the unrealized profit and loss given a current price.
- class BetSide
Bases:
objectRepresents the side of a bet in a betting market.
- BACK = BetSide.BACK
- LAY = BetSide.LAY
- classmethod from_order_side(order_side)
- classmethod from_str(data)
- name
- opposite()
Returns the opposite betting side.
- value
- classmethod variants()
- class BettingAccount
Bases:
object- account_type
- apply(event)
- balance(currency=None)
- balance_free(currency=None)
- balance_impact(instrument, quantity, price, order_side)
Returns the balance impact for a betting order.
For Sell (back) the impact is the negative stake (quantity). For Buy (lay) the impact is the negative liability (quantity * (price - 1)).
- balance_locked(currency=None)
- balance_total(currency=None)
- balances()
- balances_free()
- balances_locked()
- balances_total()
- base_currency
- calculate_account_state
- calculate_balance_locked(instrument, side, quantity, price, use_quote_for_inverse=None)
- calculate_commission(instrument, last_qty, last_px, liquidity_side, use_quote_for_inverse=None)
- calculate_pnls(instrument, fill, position=None)
- currencies()
- event_count
- events
- id
- is_cash_account()
- is_margin_account()
- last_event
- purge_account_events(ts_now, lookback_secs)
- starting_balances()
- to_dict()
- class BettingInstrument
Bases:
objectRepresents a betting instrument with complete market and selection details.
- asset_class
- betting_type
- competition_id
- competition_name
- currency
- event_country_code
- event_id
- event_name
- event_open_date
- event_type_id
- event_type_name
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- market_id
- market_name
- market_start_time
- market_type
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- selection_handicap
- selection_id
- selection_name
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class BinaryOption
Bases:
objectRepresents a generic binary option instrument.
- activation_ns
- asset_class
- currency
- description
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- outcome
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class BlackScholesGreeksResult
Bases:
objectResult structure for Black-Scholes greeks calculations This is a separate f64 struct (not a type alias) for Python compatibility
- delta
- gamma
- itm_prob
- price
- theta
- vega
- vol
- class Block
Bases:
objectRepresents an Ethereum-compatible blockchain block with essential metadata.
- base_fee_per_gas
- blob_gas_used
- chain
Returns the blockchain for this block.
- excess_blob_gas
- gas_limit
- gas_used
- hash
- l1_fee_scalar
- l1_gas_price
- l1_gas_used
- miner
- number
- parent_hash
- timestamp
- ts_event
- ts_init
- class BookAction
Bases:
objectThe type of order book action for an order book event.
- ADD = BookAction.ADD
- CLEAR = BookAction.CLEAR
- DELETE = BookAction.DELETE
- UPDATE = BookAction.UPDATE
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class BookLevel
Bases:
objectRepresents a discrete price level in an order book.
Orders are stored in an [IndexMap] which preserves FIFO (insertion) order.
- exposure()
Returns the total exposure (price * size) of all orders at this price level as a float.
- exposure_raw()
Returns the total exposure (price * size) of all orders at this price level as raw integer units.
Fixed-scale orders contribute price.raw * size.raw / FIXED_SCALAR. Native DeFi scales are normalized to the same fixed-scale result. Division truncates toward zero. Non-positive prices contribute zero. Saturates at QuantityRaw::MAX if the total exposure would overflow.
- first()
- get_orders()
Returns all orders at this price level in FIFO insertion order.
- is_empty()
Returns true if this price level has no orders.
- len()
Returns the number of orders at this price level.
- price
- size()
Returns the total size of all orders at this price level as a float.
- size_raw()
Returns the total size of all orders at this price level as raw integer units.
- class BookOrder
Bases:
objectRepresents an order in a book.
- exposure()
Returns the order exposure as an f64.
- static from_dict(values)
Constructs a BookOrder from its dictionary representation.
# Errors
Returns a PyErr if deserialization from the Python dict fails.
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- order_id
- price
- side
- signed_size()
Returns the signed order size as f64, positive for buys, negative for sells.
- size
- to_dict()
Converts the BookOrder into a Python dict representation.
# Errors
Returns a PyErr if serialization into a Python dict fails.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- class BookType
Bases:
objectThe order book type, representing the type of levels granularity and delta updating heuristics.
- L1_MBP = BookType.L1_MBP
- L2_MBP = BookType.L2_MBP
- L3_MBO = BookType.L3_MBO
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class CashAccount
Bases:
object- account_type
- allow_borrowing
- apply(event)
- balance(currency=None)
- balance_free(currency=None)
- balance_locked(currency=None)
- balance_total(currency=None)
- balances()
- balances_free()
- balances_locked()
- balances_total()
- base_currency
- calculate_account_state
- calculate_balance_locked(instrument, side, quantity, price, use_quote_for_inverse=None)
- calculate_commission(instrument, last_qty, last_px, liquidity_side, use_quote_for_inverse=None)
- calculate_pnls(instrument, fill, position=None)
- currencies()
- event_count
- events
- id
- is_cash_account()
- is_margin_account()
- last_event
- purge_account_events(ts_now, lookback_secs)
- starting_balances()
- to_dict()
- class Cfd
Bases:
objectRepresents a Contract for Difference (CFD) instrument.
Can represent both Fiat FX and Cryptocurrency pairs.
- asset_class
- base_currency
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class ClientId
Bases:
objectRepresents a system client ID.
- static from_str(value)
- value
- class ClientOrderId
Bases:
objectRepresents a valid client order ID (assigned by the Nautilus system).
- static from_str(value)
- value
- class Commodity
Bases:
objectRepresents a generic commodity instrument.
- asset_class
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class ComponentId
Bases:
objectRepresents a valid component ID.
- static from_str(value)
- value
- class ContingencyType
Bases:
objectThe order contingency type which specifies the behavior of linked orders.
[FIX 5.0 SP2 : ContingencyType <1385> field](https://www.onixs.biz/fix-dictionary/5.0.sp2/tagnum_1385.html).
- NO_CONTINGENCY = ContingencyType.NO_CONTINGENCY
- OCO = ContingencyType.OCO
- OTO = ContingencyType.OTO
- OUO = ContingencyType.OUO
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class ContinuousFutureAdjustmentType
Bases:
objectThe price-adjustment scheme applied when stitching segment contracts into a continuous future series.
The direction (backward vs. forward) selects the anchor contract: - Backward modes anchor on the most recent contract; prices in older
segments are shifted into the latest contract’s frame.
Forward modes anchor on the first contract; prices in later segments are shifted into the first contract’s frame.
The kind (spread vs. ratio) selects how each transition’s offset is combined: - Spread modes accumulate additive offsets (post_price - pre_price). - Ratio modes accumulate multiplicative factors (post_price / pre_price)
and require strictly positive prices.
- BACKWARD_RATIO = ContinuousFutureAdjustmentType.BACKWARD_RATIO
- BACKWARD_SPREAD = ContinuousFutureAdjustmentType.BACKWARD_SPREAD
- FORWARD_RATIO = ContinuousFutureAdjustmentType.FORWARD_RATIO
- FORWARD_SPREAD = ContinuousFutureAdjustmentType.FORWARD_SPREAD
- classmethod from_str(data)
- is_backward
Returns whether this mode anchors on the most recent contract.
- is_ratio
Returns whether this mode accumulates multiplicative factors.
- name
- value
- classmethod variants()
- class CryptoFuture
Bases:
objectRepresents a deliverable futures contract instrument, with crypto assets as underlying and for settlement.
- activation_ns
- asset_class
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- settlement_currency
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class CryptoFuturesSpread
Bases:
objectRepresents a crypto deliverable futures spread instrument, with crypto assets as underlying and for settlement.
- activation_ns
- asset_class
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- settlement_currency
- size_increment
- size_precision
- strategy_type
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class CryptoOption
Bases:
objectRepresents a generic option contract instrument.
- activation_ns
- asset_class
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- option_kind
- price_increment
- price_precision
- quote_currency
- raw_symbol
- settlement_currency
- size_increment
- size_precision
- strike_price
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class CryptoOptionSpread
Bases:
objectRepresents a crypto option spread instrument, with crypto assets as underlying and for settlement.
- activation_ns
- asset_class
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- settlement_currency
- size_increment
- size_precision
- strategy_type
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class CryptoPerpetual
Bases:
objectRepresents a crypto perpetual futures contract instrument (a.k.a. perpetual swap).
- asset_class
- base_currency
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- settlement_currency
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class Currency
Bases:
objectRepresents a medium of exchange in a specified denomination with a fixed decimal precision.
Handles up to [FIXED_PRECISION] decimals of precision.
- code
- currency_type
- static from_str(value, strict=False)
- static is_commodity_backed(code)
- static is_crypto(code)
Checks if the currency identified by the given code is a cryptocurrency.
# Errors
Returns an error if: - If a currency with the given code does not exist. - If there is a failure acquiring the lock on the currency map.
- static is_fiat(code)
Checks if the currency identified by the given code is a fiat currency.
# Errors
Returns an error if: - A currency with the given code does not exist. - There is a failure acquiring the lock on the currency map.
- iso4217
- name
- precision
- static register(currency, overwrite=False)
Register the given currency in the internal currency map.
If overwrite is true, any existing currency will be replaced.
If overwrite is false and the currency already exists, the operation is a no-op.
# Errors
Returns an error if there is a failure acquiring the lock on the currency map.
- class CurrencyPair
Bases:
objectRepresents a generic currency pair instrument in a spot/cash market.
Can represent both Fiat FX and Cryptocurrency pairs.
- asset_class
- base_currency
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class CurrencyType
Bases:
objectThe broad currency type.
- COMMODITY_BACKED = CurrencyType.COMMODITY_BACKED
- CRYPTO = CurrencyType.CRYPTO
- FIAT = CurrencyType.FIAT
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class CustomData
Bases:
objectA wrapper for custom data including its data type.
The data field holds an [Arc] to a [CustomDataTrait] implementation, enabling cheap cloning when passing to Python (Arc clone is O(1)). Custom data is always Rust-defined (optionally with PyO3 bindings).
- data
- data_type
- classmethod from_json_bytes(bytes)
Deserializes CustomData from JSON bytes (full CustomData format).
- to_json_bytes()
Serializes this CustomData to JSON bytes for roundtrip with from_json_bytes.
- ts_event
- ts_init
- class DataType
Bases:
objectRepresents a data type including metadata.
- identifier
Returns the optional catalog path identifier (can contain subdirs, e.g. “venue//symbol”).
- metadata
Returns the metadata for the data type.
- topic
Returns the messaging topic for the data type.
- type_name
Returns the type name for the data type.
- class DefiData
Bases:
objectRepresents DeFi-specific data events in a decentralized exchange ecosystem.
- class Block
Bases:
DefiDataA block completion in a blockchain network.
- class Pool
Bases:
DefiDataA DEX liquidity pool definition or update.
- class PoolFeeCollect
Bases:
DefiDataA fee collection event from a DEX pool position.
- class PoolFeeProtocolCollect
Bases:
DefiDataA protocol-fee withdrawal from a DEX pool.
- class PoolFeeProtocolUpdate
Bases:
DefiDataA protocol-fee configuration change in a DEX pool.
- class PoolFlash
Bases:
DefiDataA flash event
- class PoolLiquidityUpdate
Bases:
DefiDataA liquidity update event (mint/burn) in a DEX pool.
- class PoolSnapshot
Bases:
DefiDataA complete snapshot of a pool’s state at a specific point in time.
- class PoolSwap
Bases:
DefiDataA token swap transaction on a decentralized exchange.
- block_number
Returns the block number associated with this DeFi data.
- block_position()
Returns the block position associated with this DeFi data.
- log_index
Returns the log index associated with this DeFi data.
- timestamp
Returns the event timestamp associated with this DeFi data.
- transaction_index
Returns the transaction index associated with this DeFi data.
- ts_event
Returns the event timestamp associated with this DeFi data.
- ts_init
Returns the initialization timestamp associated with this DeFi data.
- class EnumIterator
Bases:
objectPython iterator over the variants of an enum.
- class Equity
Bases:
objectRepresents a generic equity instrument.
- asset_class
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class ExecAlgorithmId
Bases:
objectRepresents a valid execution algorithm ID.
- static from_str(value)
- value
- class ExecutionMassStatus
Bases:
objectRepresents an execution mass status report for an execution client - including status of all orders, trades for those orders and open positions.
- account_id
- add_fill_reports(reports)
Add fill reports to the mass status.
- add_order_reports(reports)
Add order reports to the mass status.
- add_position_reports(reports)
Add position reports to the mass status.
- client_id
- fill_reports
Get a copy of the fill reports map.
- static from_dict(values)
Creates an ExecutionMassStatus from a Python dictionary.
# Errors
Returns a Python exception if conversion from dict fails.
- lookback_start
Returns the lower timestamp bound applied to historical reports.
- order_reports
Get a copy of the order reports map.
- position_reports
Get a copy of the position reports map.
- report_id
- reports_complete
Returns whether every report source required for this mass status completed.
- to_dict()
- ts_init
- venue
- class FillReport
Bases:
objectRepresents a fill report of a single order execution.
- account_id
- avg_px
- client_order_id
- commission
- static from_dict(values)
Creates a FillReport from a Python dictionary.
# Errors
Returns a Python exception if conversion from dict fails.
- instrument_id
- last_px
- last_qty
- liquidity_side
- order_side
- report_id
- to_dict()
Converts the FillReport to a Python dictionary.
# Errors
Returns a Python exception if conversion to dict fails.
- trade_id
- ts_event
- ts_init
- venue_order_id
- venue_position_id
- class ForwardPrice
Bases:
objectRepresents a forward/underlying price for a derivatives instrument.
This is a general derivatives concept used for ATM determination in option chains and other forward-price dependent calculations.
- forward_price
- instrument_id
- ts_event
- ts_init
- underlying_index
- class FundingRateUpdate
Bases:
objectRepresents a funding rate update for perpetual swap instruments.
- static from_dict(values)
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(instrument_id)
Returns the metadata for the type, for use with serialization formats.
- instrument_id
- interval
- next_funding_ns
- rate
- to_dict()
- to_json()
- to_msgpack()
- ts_event
- ts_init
- class FuturesContract
Bases:
objectRepresents a generic deliverable futures contract instrument.
- activation_ns
- asset_class
- currency
- exchange
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class FuturesSpread
Bases:
objectRepresents a generic deliverable futures spread instrument.
- activation_ns
- asset_class
- currency
- exchange
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- strategy_type
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class GreeksConvention
Bases:
objectThe numeraire convention for option greeks published by a venue.
Crypto option venues commonly publish two parallel greek sets for the same instrument: Black-Scholes greeks in USD, and price-adjusted greeks denominated in the underlying/coin units. Deribit and OKX both expose the distinction; see the OKX reference for the canonical definition: <https://www.okx.com/docs-v5/en/#public-data-websocket-option-market-data>.
This is orthogonal to the percent-greeks transformation in the internal [GreeksCalculator](../../../nautilus_common/greeks/struct.GreeksCalculator.html), which rescales the delta/gamma input step rather than the numeraire.
- BLACK_SCHOLES = GreeksConvention.BLACK_SCHOLES
- PRICE_ADJUSTED = GreeksConvention.PRICE_ADJUSTED
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class GreeksData
Bases:
object- cost_of_carry
- delta
- expiry
- expiry_in_days
- expiry_in_years
- classmethod from_delta(instrument_id, delta, multiplier, ts_event=0)
- gamma
- instrument_id
- interest_rate
- is_call
- itm_prob
- multiplier
- pnl
- price
- quantity
- rho
- strike
- theta
- ts_event
- ts_init
- underlying_price
- vega
- vol
- class IndexInstrument
Bases:
objectRepresents a generic index instrument.
An index is typically not directly tradable.
- asset_class
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class IndexPriceUpdate
Bases:
objectRepresents an index price update.
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(instrument_id, price_precision)
Returns the metadata for the type, for use with serialization formats.
- instrument_id
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- ts_event
- ts_init
- value
- class InstrumentClass
Bases:
objectThe instrument class.
- BINARY_OPTION = InstrumentClass.BINARY_OPTION
- BOND = InstrumentClass.BOND
- CFD = InstrumentClass.CFD
- FORWARD = InstrumentClass.FORWARD
- FUTURE = InstrumentClass.FUTURE
- FUTURES_SPREAD = InstrumentClass.FUTURES_SPREAD
- OPTION = InstrumentClass.OPTION
- OPTION_SPREAD = InstrumentClass.OPTION_SPREAD
- SPORTS_BETTING = InstrumentClass.SPORTS_BETTING
- SPOT = InstrumentClass.SPOT
- SWAP = InstrumentClass.SWAP
- WARRANT = InstrumentClass.WARRANT
- allows_negative_price()
Returns whether this instrument class allows negative prices.
- classmethod from_str(data)
- has_expiration()
Returns whether this instrument class has an expiration.
- name
- parent_suffix()
Returns the canonical parent-symbol suffix for this class, if one exists.
Always emits the short form (FUT, OPT) so that adapters constructing parent ids produce a single canonical string per class.
- classmethod try_from_parent_suffix(suffix)
Returns the InstrumentClass for the parent-symbol suffix, if recognised.
Matches strict uppercase forms only. Both Databento-style abbreviations (FUT, OPT) and long forms (FUTURE, OPTION) are accepted.
- value
- classmethod variants()
- class InstrumentClose
Bases:
objectRepresents an instrument close at a venue.
- close_price
- close_type
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(instrument_id, price_precision)
Returns the metadata for the type, for use with serialization formats.
- instrument_id
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- ts_event
- ts_init
- class InstrumentCloseType
Bases:
objectThe type of event for an instrument close.
- CONTRACT_EXPIRED = InstrumentCloseType.CONTRACT_EXPIRED
- END_OF_SESSION = InstrumentCloseType.END_OF_SESSION
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class InstrumentId
Bases:
objectRepresents a valid instrument ID.
The symbol and venue combination should uniquely identify the instrument.
- static from_str(value)
- is_synthetic()
- parse_parent_components()
Returns the parent-symbol components (root, class) if this id has a recognised parent shape <root>.<class> in its symbol component.
Returns None when the symbol has zero or more than one ., or when the suffix is not a recognised InstrumentClass parent suffix (see InstrumentClass.try_from_parent_suffix).
Used to gate parent-style subscription fan-out: a None return means the id does not refer to a parent group and must not be expanded.
- symbol
- value
- venue
- class InstrumentStatus
Bases:
objectRepresents an event that indicates a change in an instrument market status.
- action
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- static get_metadata(instrument_id)
Returns the metadata for the type, for use with serialization formats.
- instrument_id
- is_quoting
- is_short_sell_restricted
- is_trading
- reason
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- trading_event
- ts_event
- ts_init
- class LeveragedMarginModel
Bases:
objectDivides notional value by leverage before applying margin rates.
Margin is calculated as (notional_value / leverage) * margin_rate. This is the default model, appropriate for crypto exchanges and venues where leverage directly reduces margin requirements.
- class LimitIfTouchedOrder
Bases:
object- account_id
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- commission(currency)
- commissions()
- contingency_type
- static create(init)
- display_qty
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- filled_qty
- static from_dict(values)
- has_price
- has_trigger_price
- init_event
- init_id
- instrument_id
- is_active_local
- is_aggressive
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_passive
- is_pending_cancel
- is_pending_update
- is_post_only
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- is_triggered
- last_event
- last_trade_id
- leaves_qty
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- price
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- trigger_instrument_id
- trigger_price
- trigger_type
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- ts_triggered
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class LimitOrder
Bases:
object- account_id
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- commission(currency)
- commissions()
- contingency_type
- static create(init)
- display_qty
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- expire_time_ns
- filled_qty
- static from_dict(values)
- has_price
- has_trigger_price
- init_event
- init_id
- instrument_id
- is_active_local
- is_aggressive
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_passive
- is_pending_cancel
- is_pending_update
- is_post_only
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- last_event
- last_trade_id
- leaves_qty
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- price
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- symbol
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- trigger_instrument_id
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- venue
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class LiquiditySide
Bases:
objectThe liquidity side for a trade.
- MAKER = LiquiditySide.MAKER
- NO_LIQUIDITY_SIDE = LiquiditySide.NO_LIQUIDITY_SIDE
- TAKER = LiquiditySide.TAKER
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class MarginAccount
Bases:
object- account_initial_margin(currency)
Returns the account-wide initial margin for the specified collateral currency.
- account_initial_margins()
Returns all account-wide initial margins keyed by currency.
- account_maintenance_margin(currency)
Returns the account-wide maintenance margin for the specified collateral currency.
- account_maintenance_margins()
Returns all account-wide maintenance margins keyed by currency.
- account_margin(currency)
Returns the account-wide margin balance for the specified collateral currency.
- account_margins()
- account_type
- apply(event)
- balance(currency=None)
- balance_free(currency=None)
- balance_locked(currency=None)
- balance_total(currency=None)
- balances()
- balances_free()
- balances_locked()
- balances_total()
- base_currency
- calculate_account_state
- calculate_balance_locked(instrument, side, quantity, price, use_quote_for_inverse=None)
- calculate_commission(instrument, last_qty, last_px, liquidity_side, use_quote_for_inverse=None)
- calculate_initial_margin(instrument, quantity, price, use_quote_for_inverse=None)
Calculates the initial margin amount for the specified instrument and quantity.
Delegates to the configured MarginModel.
# Errors
Returns an error if leverage is not positive, or if the result cannot be represented as Money.
- calculate_maintenance_margin(instrument, quantity, price, use_quote_for_inverse=None)
Calculates the maintenance margin amount for the specified instrument and quantity.
Delegates to the configured MarginModel.
# Errors
Returns an error if the result cannot be represented as Money.
- calculate_pnls(instrument, fill, position=None)
- currencies()
- default_leverage
- event_count
- events
- id
- initial_margin(instrument_id)
Returns the initial margin amount for the specified instrument.
- initial_margins()
- is_cash_account()
- is_margin_account()
- is_unleveraged(instrument_id)
- last_event
- leverage(instrument_id)
- leverages()
- maintenance_margin(instrument_id)
Returns the maintenance margin amount for the specified instrument.
- maintenance_margins()
- margin(instrument_id)
Returns the margin balance for the specified instrument.
- margins()
- purge_account_events(ts_now, lookback_secs)
- set_default_leverage(default_leverage)
Sets the default leverage for the account.
- set_leverage(instrument_id, leverage)
Sets the leverage for a specific instrument.
- starting_balances()
- to_dict()
- total_initial_margin(currency)
Returns the total initial margin reserved in the specified currency, summing per-instrument and account-wide entries.
- total_maintenance_margin(currency)
Returns the total maintenance margin reserved in the specified currency, summing per-instrument and account-wide entries.
- update_initial_margin(instrument_id, initial_margin)
Updates the initial margin for the specified instrument.
- update_maintenance_margin(instrument_id, maintenance_margin)
Updates the maintenance margin for the specified instrument.
- class MarginBalance
Bases:
objectRepresents a margin balance.
Margin entries have two mutually exclusive scopes:
Per-instrument: instrument_id = Some(id). Used for isolated margin and for calculated margin in backtest mode where each instrument carries its own reserve.
Account-wide (cross margin): instrument_id = None. Used for venues that report a single aggregate margin per collateral currency (most derivatives venues in cross-margin mode).
- copy()
Returns a copy of this margin balance.
- currency
- static from_dict(values)
Constructs a [MarginBalance] from a Python dict.
# Errors
Returns a PyErr if parsing or conversion fails.
- initial
- instrument_id
- maintenance
- to_dict()
Converts this [MarginBalance] into a Python dict.
# Errors
Returns a PyErr if serialization fails.
- class MarkPriceUpdate
Bases:
objectRepresents a mark price update.
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(instrument_id, price_precision)
Returns the metadata for the type, for use with serialization formats.
- instrument_id
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- ts_event
- ts_init
- value
- class MarketIfTouchedOrder
Bases:
object- account_id
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- commission(currency)
- commissions()
- contingency_type
- static create(init)
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- filled_qty
- static from_dict(values)
- has_price
- has_trigger_price
- init_event
- init_id
- instrument_id
- is_active_local
- is_aggressive
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_passive
- is_pending_cancel
- is_pending_update
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- is_triggered
- last_event
- last_trade_id
- leaves_qty
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- trigger_instrument_id
- trigger_price
- trigger_type
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- ts_triggered
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class MarketOrder
Bases:
object- account_id
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- commission(currency)
- commissions()
- contingency_type
- static create(init)
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- filled_qty
- static from_dict(values)
- init_event
- init_id
- instrument_id
- is_active_local
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_pending_cancel
- is_pending_update
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- last_event
- last_trade_id
- leaves_qty
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class MarketStatus
Bases:
objectThe status of an individual market on a trading venue.
- CLOSED = MarketStatus.CLOSED
- HALTED = MarketStatus.HALTED
- NOT_AVAILABLE = MarketStatus.NOT_AVAILABLE
- OPEN = MarketStatus.OPEN
- PAUSED = MarketStatus.PAUSED
- SUSPENDED = MarketStatus.SUSPENDED
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class MarketStatusAction
Bases:
objectAn action affecting the status of an individual market on a trading venue.
- CLOSE = MarketStatusAction.CLOSE
- CROSS = MarketStatusAction.CROSS
- HALT = MarketStatusAction.HALT
- NEW_PRICE_INDICATION = MarketStatusAction.NEW_PRICE_INDICATION
- NONE = MarketStatusAction.NONE
- NOT_AVAILABLE_FOR_TRADING = MarketStatusAction.NOT_AVAILABLE_FOR_TRADING
- PAUSE = MarketStatusAction.PAUSE
- POST_CLOSE = MarketStatusAction.POST_CLOSE
- PRE_CLOSE = MarketStatusAction.PRE_CLOSE
- PRE_CROSS = MarketStatusAction.PRE_CROSS
- PRE_OPEN = MarketStatusAction.PRE_OPEN
- QUOTING = MarketStatusAction.QUOTING
- ROTATION = MarketStatusAction.ROTATION
- SHORT_SELL_RESTRICTION_CHANGE = MarketStatusAction.SHORT_SELL_RESTRICTION_CHANGE
- SUSPEND = MarketStatusAction.SUSPEND
- TRADING = MarketStatusAction.TRADING
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class MarketToLimitOrder
Bases:
object- account_id
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- commission(currency)
- commissions()
- contingency_type
- static create(init)
- display_qty
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- filled_qty
- static from_dict(values)
- has_price
- init_event
- init_id
- instrument_id
- is_active_local
- is_aggressive
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_passive
- is_pending_cancel
- is_pending_update
- is_post_only
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- last_event
- last_trade_id
- leaves_qty
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- price
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class Money
Bases:
objectRepresents an amount of money in a specified currency denomination.
[MONEY_MAX] - Maximum representable money amount
[MONEY_MIN] - Minimum representable money amount
- as_decimal()
Returns the value of this instance as a Decimal.
- as_double()
- checked_add(other)
Performs a checked addition, returning None on raw integer overflow, when the result falls outside [MONEY_RAW_MIN, MONEY_RAW_MAX], or when the operands have mixed raw scales (e.g. a wei-scaled Money and a FIXED_SCALAR-scaled Money, even if their currency codes match).
- checked_sub(other)
Performs a checked subtraction, returning None on raw integer underflow, when the result falls outside [MONEY_RAW_MIN, MONEY_RAW_MAX], or when the operands have mixed raw scales (e.g. a wei-scaled Money and a FIXED_SCALAR-scaled Money, even if their currency codes match).
- currency
- static from_decimal(value, currency)
Creates a new Money from a Decimal value with specified currency.
This method provides more reliable parsing by using Decimal arithmetic to avoid floating-point precision issues during conversion.
# Errors
Returns an error if: - The decimal value cannot be converted to the raw representation. - Overflow occurs during scaling.
- static from_raw(raw, currency)
Creates a new Money instance from the given raw fixed-point value and the specified currency.
- static from_str(value)
- is_positive()
Returns true if the value of this instance is positive (> 0).
- is_zero()
Returns true if the value of this instance is zero.
- raw
- to_formatted_str()
- static zero(currency)
Creates a new Money instance with a value of zero with the given Currency.
- class OmsType
Bases:
objectThe order management system (OMS) type for a trading venue or trading strategy.
- HEDGING = OmsType.HEDGING
- NETTING = OmsType.NETTING
- UNSPECIFIED = OmsType.UNSPECIFIED
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class OptionChainSlice
Bases:
objectA point-in-time snapshot of an option chain for a single series.
- atm_strike
- call_count()
Returns the number of call entries.
- get_call(strike)
Returns the call data for a given strike price.
- get_call_greeks(strike)
Returns the call Greeks for a given strike price.
- get_call_quote(strike)
Returns the call quote for a given strike price.
- get_put(strike)
Returns the put data for a given strike price.
- get_put_greeks(strike)
Returns the put Greeks for a given strike price.
- get_put_quote(strike)
Returns the put quote for a given strike price.
- is_empty()
Returns true if the chain has no data.
- put_count()
Returns the number of put entries.
- series_id
- strike_count()
Returns the total number of unique strikes.
- strikes()
Returns all strike prices present in the chain (union of calls and puts).
- ts_event
- ts_init
- class OptionContract
Bases:
objectRepresents a generic option contract instrument.
- activation_ns
- asset_class
- currency
- exchange
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- option_kind
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- strike_price
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class OptionGreekValues
Bases:
objectCore option Greek sensitivity values (the 5 standard sensitivities). Designed as a composable building block embedded in all Greeks-carrying types.
- delta
- gamma
- rho
- theta
- vega
- class OptionGreeks
Bases:
objectExchange-provided option Greeks and implied volatility for a single instrument.
- ask_iv
- bid_iv
- convention
- delta
- gamma
- instrument_id
- mark_iv
- open_interest
- rho
- theta
- ts_event
- ts_init
- underlying_price
- vega
- class OptionKind
Bases:
objectThe kind of option contract.
- CALL = OptionKind.CALL
- PUT = OptionKind.PUT
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class OptionSeriesId
Bases:
objectIdentifies a unique option series: a specific venue + underlying + settlement currency + expiration.
- expiration_ns
- static from_expiry(venue, underlying, settlement_currency, date_str)
Creates an OptionSeriesId from venue name, underlying symbol, settlement currency, and date string.
The date_str is parsed via UnixNanos::FromStr, which accepts “YYYY-MM-DD”, RFC 3339 timestamps, integer nanoseconds, or floating-point seconds.
# Errors
Returns an error if venue or date_str is invalid.
- static from_str(value)
- settlement_currency
- underlying
- value
- venue
- class OptionSpread
Bases:
objectRepresents a generic option spread instrument.
- activation_ns
- asset_class
- currency
- exchange
- expiration_ns
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- strategy_type
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class OptionStrikeData
Bases:
objectCombined quote and Greeks data for a single strike in an option chain.
- greeks
- quote
- class OrderAccepted
Bases:
objectRepresents an event where an order has been accepted by the trading venue.
This event often corresponds to a NEW OrdStatus <39> field in FIX execution reports.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderBook
Bases:
objectProvides a high-performance, versatile order book.
Maintains buy (bid) and sell (ask) orders in price-time priority, supporting multiple market data formats: - L3 (MBO): Market By Order - tracks individual orders with unique IDs. - L2 (MBP): Market By Price - aggregates orders at each price level. - L1 (MBP): Top-of-Book - maintains only the best bid and ask prices.
- add(order, flags, sequence, ts_event)
Adds an order to the book after preprocessing based on book type.
- apply_delta(delta)
Applies a single order book delta operation.
# Errors
Returns an error if: - The delta’s instrument ID does not match this book’s instrument ID. - An Add is given with NoOrderSide (either explicitly or because the cache lookup failed). - An Add with NoOrderSide matches an order ID on both sides of the book. - After resolution the delta still has NoOrderSide but its action is not Clear.
# Notes
An ambiguous NoOrderSide Update or Delete is skipped with a warning.
- apply_deltas(deltas)
Applies multiple order book delta operations.
# Errors
Returns an error if: - The deltas’ instrument ID does not match this book’s instrument ID. - Any individual delta application fails (see Self.apply_delta).
- apply_depth(depth)
Replaces current book state with a depth snapshot.
# Errors
Returns an error if the depth’s instrument ID does not match this book’s instrument ID.
- asks(depth=None)
Returns an iterator over ask price levels.
- asks_filtered_to_dict(depth=None, own_book=None, status=None, accepted_buffer_ns=None, ts_now=None)
- asks_to_dict(depth=None)
- best_ask_price()
Returns the best ask price if available.
- best_ask_size()
Returns the size at the best ask price if available.
- best_bid_price()
Returns the best bid price if available.
- best_bid_size()
Returns the size at the best bid price if available.
- bids(depth=None)
Returns an iterator over bid price levels.
- bids_filtered_to_dict(depth=None, own_book=None, status=None, accepted_buffer_ns=None, ts_now=None)
- bids_to_dict(depth=None)
- book_type
- check_integrity()
- clear(sequence, ts_event)
Clears all orders from both sides of the book.
- clear_asks(sequence, ts_event)
Clears all ask orders from the book.
- clear_bids(sequence, ts_event)
Clears all bid orders from the book.
- clear_stale_levels(side=None)
Removes overlapped bid/ask levels when the book is strictly crossed (best bid > best ask)
Acts only when both sides exist and the book is crossed.
Deletes by removing whole price levels via the ladder API to preserve invariants.
side=None or NoOrderSide clears both overlapped ranges (conservative, may widen spread).
side=Buy clears crossed bids only; side=Sell clears crossed asks only.
Returns removed price levels (crossed bids first, then crossed asks), or None if nothing removed.
- delete(order, flags, sequence, ts_event)
Deletes an order from the book after preprocessing based on book type.
- filtered_view(own_book=None, depth=None, status=None, accepted_buffer_ns=None, ts_now=None)
Returns a filtered OrderBook view with own sizes subtracted from public levels.
- get_avg_px_for_quantity(qty, order_side)
Calculates the average price to fill the specified quantity.
- get_avg_px_qty_for_exposure(qty, order_side)
Calculates average price and quantity for target exposure. Returns (price, quantity, executed_exposure).
- get_quantity_at_level(price, order_side, size_precision)
Returns the quantity at a specific price level only, or 0 if no level exists.
Unlike get_quantity_for_price which returns cumulative quantity across multiple levels, this returns only the quantity at the exact price level.
- get_quantity_for_price(price, order_side)
Returns the cumulative quantity available at or better than the specified price.
For a BUY order, sums ask levels at or below the price. For a SELL order, sums bid levels at or above the price.
- get_worst_px_for_quantity(qty, order_side)
Calculates the worst (last-touched) price to fill the specified quantity.
- group_asks(group_size, depth=None)
Groups ask quantities by price into buckets, limited by depth.
- group_asks_filtered(group_size, depth=None, own_book=None, status=None, accepted_buffer_ns=None, ts_now=None)
Groups ask quantities into price buckets, truncating to a maximum depth, excluding own orders.
With own_book, subtracts own order sizes, filtered by status if provided. When now is provided, only subtracts orders whose acceptance time plus accepted_buffer_ns is at or before now. When now is None, acceptance-time filtering is disabled.
- group_bids(group_size, depth=None)
Groups bid quantities by price into buckets, limited by depth.
- group_bids_filtered(group_size, depth=None, own_book=None, status=None, accepted_buffer_ns=None, ts_now=None)
- instrument_id
- midpoint()
Returns the midpoint between best ask and bid prices if both exist.
- pprint(num_levels=3, group_size=None)
Return a formatted string representation of the order book.
- reset()
Resets the order book to its initial empty state.
- sequence
- simulate_fills(order)
Simulates fills for an order, returning list of (price, quantity) tuples.
- spread()
Returns the spread between best ask and bid prices if both exist.
- ts_event
- ts_init
- ts_last
- update(order, flags, sequence, ts_event)
Updates an existing order in the book after preprocessing based on book type.
- update_count
- class OrderBookDelta
Bases:
objectRepresents a single change/delta in an order book.
- action
- flags
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(instrument_id, price_precision, size_precision)
Returns the metadata for the type, for use with serialization formats.
- instrument_id
- order
- sequence
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- ts_event
- ts_init
- class OrderBookDeltas
Bases:
objectRepresents a grouped batch of OrderBookDelta updates for an OrderBook.
This type cannot be repr(C) due to the deltas vec.
- deltas
- flags
- static fully_qualified_name()
- instrument_id
- sequence
- ts_event
- ts_init
- class OrderBookDepth10
Bases:
objectRepresents an aggregated order book update with a fixed depth of 10 levels per side.
This structure is specifically designed for scenarios where a snapshot of the top 10 bid and ask levels in an order book is needed. It differs from OrderBookDelta or OrderBookDeltas in its fixed-depth nature and is optimized for cases where a full depth representation is not required or practical.
Note: This type is not compatible with OrderBookDelta or OrderBookDeltas due to its specialized structure and limited depth use case.
Per-level [BookOrder::order_id] values are non-semantic for this aggregated MBP data. Parquet catalog decoding canonicalizes them to zero.
- ask_counts
- asks
- bid_counts
- bids
- flags
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(instrument_id, price_precision, size_precision)
Returns the metadata for the type, for use with serialization formats.
- static get_stub()
- instrument_id
- sequence
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- ts_event
- ts_init
- class OrderCancelRejected
Bases:
objectRepresents an event where a CancelOrder command has been rejected by the trading venue.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reason
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderCanceled
Bases:
objectRepresents an event where an order has been canceled at the trading venue.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderDenied
Bases:
objectRepresents an event where an order has been denied by the Nautilus system.
This could be due an unsupported feature, a risk limit exceedance, or for any other reason that an otherwise valid order is not able to be submitted.
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reason
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- class OrderEmulated
Bases:
objectRepresents an event where an order has become emulated by the Nautilus system.
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- class OrderExpired
Bases:
objectRepresents an event where an order has expired at the trading venue.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderFillVoided
Bases:
objectRecords that a cumulative fill quantity no longer has economic effect.
The correction identity, voided quantity, and commission are cumulative for the referenced trade. is_reopened records positive evidence that the corrected order is executable again and therefore requires the referenced fill to have been applied locally. Without a local fill, a non-reopened correction is an authoritative terminal order void.
- account_id
- causation_id
- client_order_id
- commission_voided
- correction_id
- currency
- event_id
- static from_dict(values)
- info
- instrument_id
- is_reopened
- last_px
- liquidity_side
- order_side
- order_type
- position_id
- reason
- reconciliation
- strategy_id
- to_dict()
- trade_id
- trader_id
- ts_event
- ts_init
- venue_order_id
- voided_qty
- class OrderFilled
Bases:
object- account_id
- client_order_id
- commission
- currency
- event_id
- static from_dict(values)
Constructs an [OrderFilled] from a Python dict.
# Errors
Returns a PyErr if deserialization from the Python dict fails.
- info
- instrument_id
- is_buy
- is_sell
- last_px
- last_qty
- liquidity_side
- order_side
- order_type
- position_id
- reconciliation
- strategy_id
- to_dict()
Converts this [OrderFilled] into a Python dict.
# Errors
Returns a PyErr if serialization into a Python dict fails.
- trade_id
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderInitialized
Bases:
objectRepresents an event where an order has been initialized.
This is a seed event which can instantiate any order through a creation method. This event should contain enough information to be able to send it ‘over the wire’ and have a valid order created with exactly the same properties as if it had been instantiated locally.
- activation_price
- client_order_id
- contingency_type
- display_qty
- emulation_trigger
- event_id
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- static from_dict(values)
- instrument_id
- limit_offset
- linked_order_ids
- order_list_id
- order_side
- order_type
- parent_order_id
- post_only
- price
- quantity
- quote_quantity
- reconciliation
- reduce_only
- strategy_id
- tags
- time_in_force
- to_dict()
- trader_id
- trailing_offset
- trailing_offset_type
- trigger_instrument_id
- trigger_price
- trigger_type
- ts_event
- ts_init
- class OrderList
Bases:
objectLightweight identifier container for a group of related orders.
Stores only the order IDs; full order data lives in the cache. For serialization payload, see SubmitOrderList.order_inits.
All orders should share the same venue. The production constructors enforce this: [OrderList::from_orders] and OrderFactory::create_list panic on mixed venues, and Strategy::submit_order_list bails at the user-facing entry. [OrderList::new] is infallible and takes instrument_id directly; it does not verify the venues of the supplied client_order_ids. The instrument_id is a representative value taken from the first order; orders may target different instruments at that venue. Downstream consumers that need a per-order instrument should resolve each order from the cache.
- client_order_ids()
Returns the client order IDs contained in the order list.
- first_client_order_id
- id
- instrument_id
- strategy_id
- ts_init
- class OrderListId
Bases:
objectRepresents a valid order list ID (assigned by the Nautilus system).
- static from_str(value)
- value
- class OrderModifyRejected
Bases:
objectRepresents an event where a ModifyOrder command has been rejected by the trading venue.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reason
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderPendingCancel
Bases:
objectRepresents an event where a CancelOrder command has been sent to the trading venue.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderPendingUpdate
Bases:
objectRepresents an event where an ModifyOrder command has been sent to the trading venue.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderRejected
Bases:
objectRepresents an event where an order has been rejected by the trading venue.
- account_id
- client_order_id
- due_post_only
- event_id
- static from_dict(values)
- instrument_id
- reason
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- class OrderReleased
Bases:
objectRepresents an event where an order was released from the OrderEmulated by the Nautilus system.
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- released_price
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- class OrderSide
Bases:
objectThe order side for a specific order, or action related to orders.
- BUY = OrderSide.BUY
- NO_ORDER_SIDE = OrderSide.NO_ORDER_SIDE
- SELL = OrderSide.SELL
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class OrderSnapshot
Bases:
objectRepresents an order state snapshot as a certain instant.
- static from_dict(values)
- class OrderStatus
Bases:
objectThe status for a specific order.
- An order is considered _open_ for the following status:
ACCEPTED
TRIGGERED
PENDING_UPDATE
PENDING_CANCEL
PARTIALLY_FILLED
- An order is considered _in-flight_ for the following status:
SUBMITTED
PENDING_UPDATE
PENDING_CANCEL
- An order is considered _closed_ for the following status:
DENIED
REJECTED
CANCELED
EXPIRED
FILLED
VOIDED
- ACCEPTED = OrderStatus.ACCEPTED
- CANCELED = OrderStatus.CANCELED
- DENIED = OrderStatus.DENIED
- EMULATED = OrderStatus.EMULATED
- EXPIRED = OrderStatus.EXPIRED
- FILLED = OrderStatus.FILLED
- INITIALIZED = OrderStatus.INITIALIZED
- PARTIALLY_FILLED = OrderStatus.PARTIALLY_FILLED
- PENDING_CANCEL = OrderStatus.PENDING_CANCEL
- PENDING_UPDATE = OrderStatus.PENDING_UPDATE
- REJECTED = OrderStatus.REJECTED
- RELEASED = OrderStatus.RELEASED
- SUBMITTED = OrderStatus.SUBMITTED
- TRIGGERED = OrderStatus.TRIGGERED
- VOIDED = OrderStatus.VOIDED
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class OrderStatusReport
Bases:
objectRepresents an order status at a point in time.
- account_id
- activation_price
- avg_px
- cancel_reason
- client_order_id
- contingency_type
- display_qty
- expire_time
- filled_qty
- static from_dict(values)
Creates an OrderStatusReport from a Python dictionary.
# Errors
Returns a Python exception if conversion from dict fails.
- instrument_id
- is_open
- limit_offset
- linked_order_ids
- order_list_id
- order_side
- order_status
- order_type
- parent_order_id
- post_only
- price
- quantity
- reduce_only
- report_id
- time_in_force
- to_dict()
Converts the OrderStatusReport to a Python dictionary.
# Errors
Returns a Python exception if conversion to dict fails.
- trailing_offset
- trailing_offset_type
- trigger_price
- trigger_type
- ts_accepted
- ts_init
- ts_last
- ts_triggered
- venue_order_id
- venue_position_id
- class OrderSubmitted
Bases:
objectRepresents an event where an order has been submitted by the system to the trading venue.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- class OrderTriggered
Bases:
objectRepresents an event where an order has triggered.
Applicable to StopLimit, TrailingStopLimit, and LimitIfTouched orders.
- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- reconciliation
- strategy_id
- to_dict()
- trader_id
- ts_event
- ts_init
- venue_order_id
- class OrderType
Bases:
objectThe type of order.
- LIMIT = OrderType.LIMIT
- LIMIT_IF_TOUCHED = OrderType.LIMIT_IF_TOUCHED
- MARKET = OrderType.MARKET
- MARKET_IF_TOUCHED = OrderType.MARKET_IF_TOUCHED
- MARKET_TO_LIMIT = OrderType.MARKET_TO_LIMIT
- STOP_LIMIT = OrderType.STOP_LIMIT
- STOP_MARKET = OrderType.STOP_MARKET
- TRAILING_STOP_LIMIT = OrderType.TRAILING_STOP_LIMIT
- TRAILING_STOP_MARKET = OrderType.TRAILING_STOP_MARKET
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class OrderUpdated
Bases:
object- account_id
- client_order_id
- event_id
- static from_dict(values)
- instrument_id
- is_quote_quantity
- price
- quantity
- reconciliation
- strategy_id
- to_dict()
- trader_id
- trigger_price
- ts_event
- ts_init
- venue_order_id
- class OtoTriggerMode
Bases:
objectDefines when OTO (One-Triggers-Other) child orders are released.
- FULL = OtoTriggerMode.FULL
- PARTIAL = OtoTriggerMode.PARTIAL
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class OwnBookOrder
Bases:
objectRepresents an own/user order for a book.
This struct models an order that may be in-flight to the trading venue or actively working, depending on the value of the status field.
- client_order_id
- exposure()
Returns the order exposure as an f64.
- order_type
- price
- side
- signed_size()
Returns the signed order exposure as an f64.
- size
- status
- time_in_force
- ts_init
- ts_last
- class OwnOrderBook
Bases:
object- add(order)
Adds an own order to the book.
- ask_client_order_ids()
Returns the client order IDs currently on the ask side.
- ask_quantity(status=None, depth=None, group_size=None, accepted_buffer_ns=None, ts_now=None)
Aggregates own ask quantities per price level, omitting zero-quantity levels.
Filters by status if provided, including only matching orders. When ts_now is provided, only includes orders whose acceptance time plus accepted_buffer_ns is at or before ts_now. When ts_now is None, acceptance-time filtering is disabled.
If group_size is provided, groups quantities into price buckets. If depth is provided, limits the number of price levels returned.
- asks_to_dict(status=None, accepted_buffer_ns=None, ts_now=None)
- asks_to_list()
- audit_open_orders(open_order_ids)
- bid_client_order_ids()
Returns the client order IDs currently on the bid side.
- bid_quantity(status=None, depth=None, group_size=None, accepted_buffer_ns=None, ts_now=None)
Aggregates own bid quantities per price level, omitting zero-quantity levels.
Filters by status if provided, including only matching orders. When ts_now is provided, only includes orders whose acceptance time plus accepted_buffer_ns is at or before ts_now. When ts_now is None, acceptance-time filtering is disabled.
If group_size is provided, groups quantities into price buckets. If depth is provided, limits the number of price levels returned.
- bids_to_dict(status=None, accepted_buffer_ns=None, ts_now=None)
- bids_to_list()
- clear()
Clears all orders from both sides of the book.
- combined_with_opposite(opposite)
Returns a new own book containing this books orders plus parity-transformed opposite orders.
Opposite asks are transformed into bids with price 1 - price. Opposite bids are transformed into asks with price 1 - price.
# Errors
Returns BookViewError.OppositeInstrumentMatch if self and opposite have the same instrument ID.
- delete(order)
Deletes an own order from the book.
# Errors
Returns an error if the order is not found.
- instrument_id
- is_order_in_book(client_order_id)
Return whether the given client order ID is in the own book.
- orders_to_list()
- pprint(num_levels=3, group_size=None)
Return a formatted string representation of the order book.
- reset()
Resets the order book to its initial empty state.
- ts_last
- update(order)
Updates an existing own order in the book.
# Errors
Returns an error if the order is not found.
- update_count
- class PerpetualContract
Bases:
objectRepresents a perpetual contract instrument (perpetual swap).
Supports perpetuals on any asset class including FX, equities, commodities, indexes, and cryptocurrencies.
- asset_class
- base_currency
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- settlement_currency
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- underlying
- class Pool
Bases:
objectRepresents a liquidity pool in a decentralized exchange.
## Pool Identification Architecture
Pools are identified differently depending on the DEX protocol version:
UniswapV2/V3: Each pool has its own smart contract deployed at a unique address. - address = pool contract address - pool_identifier = same as address (hex string)
`UniswapV4`: All pools share a singleton PoolManager contract. Pools are distinguished by a unique Pool ID (keccak256 hash of currencies, fee, tick spacing, and hooks). - address = PoolManager contract address (shared by all pools) - pool_identifier = Pool ID (bytes32 as hex string)
## Instrument ID Format
The instrument ID encodes with the following components: - symbol - The pool identifier (address for V2/V3, Pool ID for V4) - venue - The chain name plus DEX ID
String representation: <POOL_IDENTIFIER>.<CHAIN_NAME>:<DEX_ID>
Example: 0x11b815efB8f581194ae79006d24E0d814B7697F6.Ethereum:UniswapV3
- address
- chain
- creation_block
- dex
- fee
- instrument_id
- tick_spacing
- token0
- token1
- ts_event
- ts_init
- class PoolAnalytics
Bases:
objectAnalytics counters and metrics for pool operations.
It tracks cumulative statistics about pool activity, including deposit and collection flows, event counts, and performance metrics for debugging.
- class PoolFeeCollect
Bases:
objectRepresents a fee collection event in a decentralized exchange (DEX) pool.
- amount0
- amount1
- block
- chain
- dex
- instrument_id
- log_index
- owner
- pool_identifier
- tick_lower
- tick_upper
- timestamp
- transaction_hash
- transaction_index
- ts_event
- ts_init
- class PoolFeeProtocolCollect
Bases:
objectRepresents a protocol-fee withdrawal from a Uniswap V3-style pool.
Emitted by CollectProtocol, this carries the protocol-fee amounts withdrawn to the recipient. The amounts decrement the pool’s accrued protocol-fee balances, leaving the on-chain remainder (Uniswap V3 keeps one wei in each slot to save gas).
- amount0
- amount1
- block
- chain
- dex
- instrument_id
- log_index
- pool_identifier
- recipient
- sender
- timestamp
- transaction_hash
- transaction_index
- ts_event
- ts_init
- class PoolFeeProtocolUpdate
Bases:
objectRepresents a protocol-fee configuration change in a Uniswap V3-style pool.
Emitted by SetFeeProtocol, this carries the new protocol-fee values for each token. Uniswap V3 uses 4-bit denominators, while PancakeSwap V3 uses uint32 basis-point shares. Only the new values are kept; the previous values in the event are not needed to rebuild state.
- block
- chain
- dex
- fee_protocol0_new
- fee_protocol1_new
- instrument_id
- log_index
- pool_identifier
- timestamp
- transaction_hash
- transaction_index
- ts_event
- ts_init
- class PoolFlash
Bases:
objectRepresents a flash loan event from a Uniswap V3 pool.
Flash loans allow users to borrow tokens without collateral as long as they are returned within the same transaction. Fees are paid on the borrowed amount, which are added to the pool’s fee growth accumulators.
- amount0
- amount1
- block
- chain
- dex
- instrument_id
- log_index
- paid0
- paid1
- pool_identifier
- recipient
- sender
- timestamp
- transaction_hash
- transaction_index
- ts_event
- ts_init
- class PoolLiquidityUpdate
Bases:
objectRepresents a liquidity update event in a decentralized exchange (DEX) pool.
- amount0
- amount1
- block
- chain
- dex
- instrument_id
- kind
- log_index
- owner
- pool_identifier
- position_liquidity
- sender
- tick_lower
- tick_upper
- timestamp
- transaction_hash
- transaction_index
- ts_event
- ts_init
- class PoolLiquidityUpdateType
Bases:
objectRepresents the type of liquidity update operation in a DEX pool.
- BURN = PoolLiquidityUpdateType.BURN
- MINT = PoolLiquidityUpdateType.MINT
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class PoolPosition
Bases:
objectRepresents a concentrated liquidity position in a DEX pool.
This struct tracks a specific liquidity provider’s position within a price range, including the liquidity amount, fee accumulation, and token deposits/withdrawals.
- class PoolProfiler
Bases:
objectA DeFi pool state tracker and event processor for UniswapV3-style AMM pools.
The PoolProfiler provides complete pool state management including: - Liquidity position tracking and management. - Tick crossing and price movement simulation. - Fee accumulation and distribution tracking. - Protocol fee calculation. - Pool state validation and maintenance.
This profiler can both process historical events and execute new operations, making it suitable for both backtesting and simulation scenarios.
# Usage
Create a new profiler with a pool definition, initialize it with a starting price, then either process historical events or execute new pool operations to simulate trading activity and analyze pool behavior.
- current_tick
- estimate_balance_of_token0()
Estimates the total amount of token0 in the pool.
Calculates token0 balance by summing: - Token0 amounts from all active liquidity positions - Accumulated trading fees (approximated from fee growth) - Protocol fees collected
- estimate_balance_of_token1()
Estimates the total amount of token1 in the pool.
Calculates token1 balance by summing: - Token1 amounts from all active liquidity positions - Accumulated trading fees (approximated from fee growth) - Protocol fees collected
- fee_protocol
- fee_protocol0_basis_points
- fee_protocol1_basis_points
- get_active_liquidity()
Returns the pool’s active liquidity tracked by the tick map.
This represents the effective liquidity available for trading at the current price. The tick map maintains this value efficiently by updating it during tick crossings as the price moves through different ranges.
# Returns The active liquidity (u128) at the current tick from the tick map
- get_active_tick_count()
Gets the number of active ticks.
- get_total_active_positions()
Gets the count of positions that are currently active.
Active positions are those with liquidity > 0 and whose tick range includes the current pool tick (meaning they have tokens in the pool).
- get_total_inactive_positions()
Gets the count of positions that are currently inactive.
Inactive positions are those that exist but don’t span the current tick, meaning their liquidity is entirely in one token or the other.
- get_total_liquidity()
- get_total_tick_count()
Gets the total number of ticks tracked by the tick map.
Returns count of all ticks that have ever been initialized, including those that may no longer have active liquidity.
# Returns Total tick count in the tick map
- instrument_id
- is_initialized
- liquidity_utilization_rate()
Calculates the liquidity utilization rate for the pool.
The utilization rate measures what percentage of total deployed liquidity is currently active (in-range and earning fees) at the current price tick.
- pool
- price_sqrt_ratio_x96
- protocol_fees_token0
- protocol_fees_token1
- size_for_impact_bps(impact_bps, zero_for_one)
Finds the maximum trade size that produces a target slippage (including fees).
Uses binary search to find the largest trade size that results in slippage at or below the target. The method iteratively simulates swaps at different sizes until it converges to the optimal size within the specified tolerance.
# Returns The maximum trade size (U256) that produces the target slippage
# Errors Returns error if: - Impact is zero or exceeds 100% (10000 bps) - Pool is not initialized - Swap simulations fail
- size_for_impact_bps_detailed(impact_bps, zero_for_one)
Finds the maximum trade size with search diagnostics. This is the detailed version of Self.size_for_impact_bps that returns extensive information about the search process.It is useful for debugging, monitoring, and analyzing search behavior in production.
# Returns Detailed result with size and search diagnostics
# Errors Returns error if: - Impact is zero or exceeds 100% (10000 bps) - Pool is not initialized - Swap simulations fail
- swap_exact_in(amount_in, zero_for_one, sqrt_price_limit_x96)
Simulates an exact input swap (know input amount, calculate output amount).
# Errors Returns error if pool is not initialized, input is zero, or price limit is invalid
- swap_exact_out(amount_out, zero_for_one, sqrt_price_limit_x96)
Simulates an exact output swap (know output amount, calculate required input amount).
# Errors Returns error if pool is not initialized, output is zero, price limit is invalid, or insufficient liquidity exists to fulfill the exact output amount
- total_amount0_collected
- total_amount0_deposited
- total_amount1_collected
- total_amount1_deposited
- class PoolSnapshot
Bases:
objectComplete snapshot of a liquidity pool’s state at a specific point in time.
PoolSnapshot provides a self-contained representation of a pool’s entire state, bundling together the global state variables, all liquidity positions, and the complete tick distribution.
- class PoolState
Bases:
objectGlobal state snapshot of a liquidity pool at a specific point in time.
PoolState encapsulates the core global variables that define a UniswapV3-style AMM pool’s current state. This includes the current price position, cumulative deposit/withdrawal flows, and protocol fee configuration.
- class PoolSwap
Bases:
objectRepresents a token swap transaction on a decentralized exchange (DEX).
This structure captures both the raw blockchain data from a swap event and optionally includes computed market-oriented trade information. It serves as the primary data structure for tracking and analyzing DEX swap activity.
- amount0
- amount1
- block
- chain
- dex
- instrument_id
- liquidity
- log_index
- pool_identifier
- recipient
- sender
- sqrt_price_x96
- tick
- timestamp
- transaction_hash
- transaction_index
- ts_event
- ts_init
- class PoolTick
Bases:
objectRepresents a tick in a Uniswap V3-style AMM with liquidity tracking and fee accounting.
- class PortfolioGreeks
Bases:
object- delta
- gamma
- pnl
- price
- rho
- theta
- ts_event
- ts_init
- vega
- class PortfolioSnapshot
Bases:
objectRepresents a point-in-time snapshot of portfolio state for a single account.
Unlike [AccountState](crate::events::AccountState), which fires only on balance or margin changes, PortfolioSnapshot carries a continuous mark-to-market view by folding open-position valuations into the totals. The default equity curve records one snapshot at account registration, at every UTC midnight, and at shutdown, including while the account is flat. An optional fine-grained stream records additional snapshots while positions are open. Totals span every venue the account holds positions on, so multi-venue accounts (e.g., a prime broker routing across exchanges) produce a single account-wide snapshot rather than per-venue slices.
- account_id
- account_type
- balances
- base_currency
- base_currency_equity
- event_id
- is_stale
- margins
- realized_pnls
- stale_currencies
- stale_instruments
- total_equity
- ts_event
- ts_init
- unpriced_instruments
- unrealized_pnls
- class Position
Bases:
objectRepresents a position in a market.
The position ID may be assigned at the trading venue, or can be system generated depending on a strategies OMS (Order Management System) settings. Replay events and cumulative fill corrections preserve derived state across close and reopen cycles.
- account_id
- adjustments()
- apply(fill)
Applies an OrderFilled event to this position.
- apply_adjustment(adjustment)
Applies a position adjustment event.
This method handles adjustments to position quantity or realized PnL that occur outside of normal order fills, such as: - Commission adjustments in base currency (crypto spot markets). - Funding payments (perpetual futures).
The adjustment event is stored in the position’s adjustment history for full audit trail.
- avg_px_close
- avg_px_open
- base_currency
- calculate_pnl(avg_px_open, avg_px_close, quantity)
Calculates profit and loss from the given prices and quantity.
- client_order_ids()
Returns unique client order IDs from all fill events, sorted.
- closing_order_id
- commissions()
Returns the cumulative commissions for the position as a vector.
- duration_ns
- entry
- event_count
Returns the count of order fill events applied to this position.
- events()
- static from_dict(values)
Constructs a [Position] from a Python dict.
# Errors
Returns a PyErr if deserialization from the Python dict fails.
- id
- instrument_class
- instrument_id
- is_closed
Returns whether the position is closed (flat with a close timestamp).
- is_inverse
- is_long
Returns whether the position is long (positive quantity).
- is_open
Returns whether the position is currently open (has quantity and no close timestamp).
- is_opposite_side(side)
Returns whether the given order side is opposite to the position entry side.
- is_short
Returns whether the position is short (negative quantity).
- is_spot_currency
- last_event
Returns the last OrderFilled event for the position (if any after purging).
- last_trade_id
Returns the last TradeId for the position (if any after purging).
- multiplier
- notional_value(price)
Calculates the notional value based on the last price.
- opening_order_id
- peak_qty
- price_precision
- purge_events_for_order(client_order_id)
Purges all order fill events for the given client order ID and recalculates derived state.
# Warning
This operation recalculates the entire position from scratch after removing the specified order’s fills. This is an expensive operation and should be used sparingly.
- quantity
- quote_currency
- realized_pnl
- realized_return
- settlement_currency
- side
- signed_qty
- size_precision
- strategy_id
- symbol
Returns the instrument symbol.
- to_dict()
Converts this [Position] into a Python dict.
# Errors
Returns a PyErr if serialization into a Python dict fails.
- total_pnl(last)
Returns total P&L (realized + unrealized) based on the last price.
- trade_ids()
Returns unique trade IDs from all fill events, sorted.
- trader_id
- ts_closed
- ts_init
- ts_last
- ts_opened
- unrealized_pnl(last)
Returns unrealized P&L based on the last price.
- venue
Returns the trading venue.
- venue_order_ids()
Returns unique venue order IDs from all fill events, sorted.
- class PositionAdjusted
Bases:
objectRepresents an adjustment to a position’s quantity or realized PnL.
This event is used to track changes to positions that occur outside of normal order fills, such as: - Commission adjustments that affect the actual quantity held (e.g., crypto spot commissions) - Funding payments that affect realized PnL (e.g., perpetual futures funding)
- account_id
- adjustment_type
- event_id
- static from_dict(values)
Constructs a [PositionAdjusted] from a Python dict.
# Errors
Returns a PyErr if deserialization from the Python dict fails.
- instrument_id
- pnl_change
- position_id
- quantity_change
- reason
- strategy_id
- to_dict()
Converts this [PositionAdjusted] into a Python dict.
# Errors
Returns a PyErr if serialization into a Python dict fails.
- trader_id
- ts_event
- ts_init
- class PositionAdjustmentType
Bases:
objectThe type of position adjustment.
- COMMISSION = PositionAdjustmentType.COMMISSION
- FUNDING = PositionAdjustmentType.FUNDING
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class PositionChanged
Bases:
objectRepresents an event where a position has changed.
- account_id
- avg_px_close
- avg_px_open
- static create(position, fill, event_id, ts_init)
- currency
- entry
- event_id
- instrument_id
- last_px
- last_qty
- opening_order_id
- peak_qty
- peak_quantity
- position_id
- quantity
- realized_pnl
- realized_return
- side
- signed_qty
- strategy_id
- trader_id
- ts_event
- ts_init
- ts_opened
- unrealized_pnl
- class PositionClosed
Bases:
objectRepresents an event where a position has been closed.
- account_id
- avg_px_close
- avg_px_open
- closing_order_id
- static create(position, fill, event_id, ts_init)
- currency
- duration
- entry
- event_id
- instrument_id
- last_px
- last_qty
- opening_order_id
- peak_qty
- peak_quantity
- position_id
- quantity
- realized_pnl
- realized_return
- side
- signed_qty
- strategy_id
- trader_id
- ts_closed
- ts_event
- ts_init
- ts_opened
- unrealized_pnl
- class PositionId
Bases:
objectRepresents a valid position ID.
- static from_str(value)
- value
- class PositionOpened
Bases:
objectRepresents an event where a position has been opened.
- account_id
- avg_px_open
- static create(position, fill, event_id, ts_init)
- currency
- entry
- event_id
- instrument_id
- last_px
- last_qty
- opening_order_id
- position_id
- quantity
- realized_pnl
- side
- signed_qty
- strategy_id
- trader_id
- ts_event
- ts_init
- class PositionSide
Bases:
objectThe market side for a specific position, or action related to positions.
- FLAT = PositionSide.FLAT
- LONG = PositionSide.LONG
- NO_POSITION_SIDE = PositionSide.NO_POSITION_SIDE
- SHORT = PositionSide.SHORT
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class PositionSnapshot
Bases:
objectRepresents a position state snapshot as a certain instant.
- static from_dict(values)
- class PositionStatusReport
Bases:
objectRepresents a position status at a point in time.
- account_id
- avg_px_open
- static from_dict(values)
Creates a PositionStatusReport from a Python dictionary.
# Errors
Returns a Python exception if conversion from dict fails.
- instrument_id
- is_flat
Checks if this is a flat position (quantity is zero).
- is_long
Checks if this is a long position.
- is_short
Checks if this is a short position.
- position_side
- quantity
- report_id
- strategy_id
- to_dict()
Converts the PositionStatusReport to a Python dictionary.
# Errors
Returns a Python exception if conversion to dict fails.
- ts_init
- ts_last
- venue_position_id
- class Price
Bases:
objectRepresents a price in a market with a specified precision.
The number of decimal places may vary. For certain asset classes, prices may have negative values. For example, prices for options instruments can be negative under certain conditions.
Handles up to [FIXED_PRECISION] decimals of precision.
[PRICE_MAX] - Maximum representable price value.
[PRICE_MIN] - Minimum representable price value.
- as_decimal()
Returns the value of this instance as a Decimal.
- as_double()
- checked_add(other)
Performs a checked addition, returning None on raw integer overflow, when the result falls outside [PRICE_RAW_MIN, PRICE_RAW_MAX], when either operand is a sentinel (PRICE_UNDEF, PRICE_ERROR, or ERROR_PRICE), or when the operands have mixed raw scales (one at FIXED_PRECISION scale, the other at a defi WEI_PRECISION scale).
Precision follows the Add implementation: uses the maximum precision of both operands.
- checked_sub(other)
Performs a checked subtraction, returning None on raw integer underflow, when the result falls outside [PRICE_RAW_MIN, PRICE_RAW_MAX], when either operand is a sentinel (PRICE_UNDEF, PRICE_ERROR, or ERROR_PRICE), or when the operands have mixed raw scales (one at FIXED_PRECISION scale, the other at a defi WEI_PRECISION scale).
Precision follows the Sub implementation: uses the maximum precision of both operands.
- static from_decimal(decimal)
Creates a new Price from a Decimal value with precision inferred from the decimal’s scale.
The precision is determined by the scale of the decimal (number of decimal places). The value is rounded to the inferred precision using banker’s rounding (round half to even).
# Errors
Returns an error if: - The inferred precision exceeds FIXED_PRECISION. - The decimal value cannot be converted to the raw representation. - Overflow occurs during scaling.
- static from_decimal_dp(decimal, precision)
Creates a new Price from a Decimal value with specified precision.
Uses pure integer arithmetic on the Decimal’s mantissa and scale for fast conversion. The value is rounded to the specified precision using banker’s rounding (round half to even).
# Errors
Returns an error if: - precision exceeds FIXED_PRECISION. - The decimal value cannot be converted to the raw representation. - Overflow occurs during scaling.
- static from_int(value)
- static from_mantissa_exponent(mantissa, exponent, precision)
Creates a new Price from a mantissa/exponent pair using pure integer arithmetic.
The value is mantissa * 10^exponent. This avoids all floating-point and Decimal operations, making it ideal for exchange data that arrives as mantissa/exponent pairs.
- static from_raw(raw, precision)
Creates a new Price instance from the given raw fixed-point value and precision.
- static from_str(value)
- is_positive()
Returns true if the value of this instance is position (> 0).
- is_zero()
Returns true if the value of this instance is zero.
- precision
- raw
- to_formatted_str()
- static zero(precision=0)
Creates a new Price instance with a value of zero with the given precision.
- class PriceType
Bases:
objectThe type of price for an instrument in a market.
- ASK = PriceType.ASK
- BID = PriceType.BID
- LAST = PriceType.LAST
- MARK = PriceType.MARK
- MID = PriceType.MID
- classmethod from_int(value)
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class Quantity
Bases:
objectRepresents a quantity with a non-negative value and specified precision.
Capable of storing either a whole number (no decimal places) of ‘contracts’ or ‘shares’ (instruments denominated in whole units) or a decimal value containing decimal places for instruments denominated in fractional units.
Handles up to [FIXED_PRECISION] decimals of precision.
[QUANTITY_MAX] - Maximum representable quantity value.
[QUANTITY_MIN] - 0 (non-negative values only).
- as_decimal()
Returns the value of this instance as a Decimal.
- as_double()
- checked_add(other)
Performs a checked addition, returning None on raw integer overflow, when the result exceeds QUANTITY_RAW_MAX, when either operand is QUANTITY_UNDEF, or when the operands have mixed raw scales (one at FIXED_PRECISION scale, the other at a defi WEI_PRECISION scale).
Precision follows the Add implementation: uses the maximum precision of both operands.
- checked_sub(other)
Performs a checked subtraction, returning None if rhs is greater than self, when either operand is QUANTITY_UNDEF, or when the operands have mixed raw scales (one at FIXED_PRECISION scale, the other at a defi WEI_PRECISION scale).
Precision follows the Sub implementation: uses the maximum precision of both operands.
- static from_decimal(decimal)
Creates a new Quantity from a Decimal value with precision inferred from the decimal’s scale.
The precision is determined by the scale of the decimal (number of decimal places). The value is rounded to the inferred precision using banker’s rounding (round half to even).
# Errors
Returns an error if: - The inferred precision exceeds FIXED_PRECISION. - The decimal value cannot be converted to the raw representation. - Overflow occurs during scaling.
- static from_decimal_dp(decimal, precision)
Creates a new Quantity from a Decimal value with specified precision.
Uses pure integer arithmetic on the Decimal’s mantissa and scale for fast conversion. The value is rounded to the specified precision using banker’s rounding (round half to even).
# Errors
Returns an error if: - precision exceeds FIXED_PRECISION. - The decimal value is negative. - The decimal value cannot be converted to the raw representation. - Overflow occurs during scaling.
- static from_int(value)
- static from_mantissa_exponent(mantissa, exponent, precision)
Creates a new Quantity from a mantissa/exponent pair using pure integer arithmetic.
The value is mantissa * 10^exponent. This avoids all floating-point and Decimal operations, making it ideal for exchange data that arrives as mantissa/exponent pairs.
- static from_raw(raw, precision)
Creates a new Quantity instance from the given raw fixed-point value and precision.
- static from_str(value)
- is_positive()
Returns true if the value of this instance is position (> 0).
- is_zero()
Returns true if the value of this instance is zero.
- precision
- raw
- saturating_sub(other)
Computes a saturating subtraction between two quantities, logging when clamped.
When rhs is greater than self, the result is clamped to zero and a warning is logged. Precision follows the Sub implementation: uses the maximum precision of both operands.
- to_formatted_str()
- static zero(precision=0)
Creates a new Quantity instance with a value of zero with the given precision.
- class QuoteTick
Bases:
objectRepresents a quote tick in a market.
- ask_price
- ask_size
- bid_price
- bid_size
- extract_price(price_type)
Returns the Price for this quote depending on the given price_type.
# Errors
Returns an error if price_type is not Bid, Ask, or Mid (a quote has no Last price).
- extract_size(price_type)
Returns the Quantity for this quote depending on the given price_type.
# Errors
Returns an error if price_type is not Bid, Ask, or Mid (a quote has no Last size).
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static from_raw(instrument_id, bid_price_raw, ask_price_raw, bid_price_prec, ask_price_prec, bid_size_raw, ask_size_raw, bid_size_prec, ask_size_prec, ts_event, ts_init)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(instrument_id, price_precision, size_precision)
Returns the metadata for the type, for use with serialization formats.
- instrument_id
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- ts_event
- ts_init
- class RecordFlag
Bases:
objectA record flag bit field, indicating event end and data information.
- F_LAST = RecordFlag.F_LAST
- F_MBP = RecordFlag.F_MBP
- F_SNAPSHOT = RecordFlag.F_SNAPSHOT
- F_TOB = RecordFlag.F_TOB
- RESERVED_1 = RecordFlag.RESERVED_1
- RESERVED_2 = RecordFlag.RESERVED_2
- classmethod from_str(data)
- matches(value)
Checks if the flag matches a given value.
- name
- value
- classmethod variants()
- class SizeForImpactResult
Bases:
objectDetailed result of a size-for-impact search.
Contains diagnostics about the binary search process including convergence information, iterations taken, bounds used, and final accuracy.
- accuracy_percent()
Get the convergence quality as a percentage.
# Returns Accuracy percentage (100.0 = perfect match, lower = less accurate)
- actual_impact_bps
- converged
- expansion_count
- final_high
- final_low
- initial_high
- iterations
- size
- target_impact_bps
- within_tolerance(tolerance_bps)
Check if the result is within the specified tolerance.
- zero_for_one
- class StandardMarginModel
Bases:
objectUses fixed margin percentages without leverage division.
Margin is calculated as notional_value * margin_rate, ignoring the account leverage. Appropriate for traditional brokers where margin requirements are fixed percentages of notional value.
- class StopLimitOrder
Bases:
object- account_id
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- contingency_type
- static create(init)
- display_qty
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- filled_qty
- static from_dict(values)
- has_price
- has_trigger_price
- init_event
- init_id
- instrument_id
- is_active_local
- is_aggressive
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_passive
- is_pending_cancel
- is_pending_update
- is_post_only
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- is_triggered
- last_event
- last_trade_id
- leaves_qty
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- price
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- trigger_instrument_id
- trigger_price
- trigger_type
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- ts_triggered
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class StopMarketOrder
Bases:
object- account_id
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- commission(currency)
- commissions()
- contingency_type
- static create(init)
- display_qty
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- filled_qty
- static from_dict(values)
- has_price
- has_trigger_price
- init_event
- init_id
- instrument_id
- is_active_local
- is_aggressive
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_passive
- is_pending_cancel
- is_pending_update
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- is_triggered
- last_event
- last_trade_id
- leaves_qty
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- trigger_instrument_id
- trigger_price
- trigger_type
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- ts_triggered
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class StrategyId
Bases:
objectRepresents a valid strategy ID.
- static from_str(value)
- value
- class StrikeRange
Bases:
objectPython wrapper for StrikeRange (complex enum).
- static atm_percent(pct)
Creates a StrikeRange::AtmPercent variant.
- static atm_relative(strikes_above, strikes_below)
Creates a StrikeRange::AtmRelative variant.
- static delta(target, tolerance)
Creates a StrikeRange::Delta variant.
- static fixed(strikes)
Creates a StrikeRange::Fixed variant.
- kind
Returns the variant name (Fixed, AtmRelative, AtmPercent, or Delta).
- class SwapQuote
Bases:
objectSwap quote containing profiling metrics for a hypothetical swap.
This structure provides detailed analysis of what would happen if a swap were executed, including price impact, fees, slippage, and execution details, without actually modifying the pool state.
- amount0
- amount1
- crossed_ticks_count
- fee_growth_global_after
- get_output_amount()
Gets the output amount for the given swap direction.
- liquidity_after
- lp_fee
- protocol_fee
- sqrt_price_after_x96
- sqrt_price_before_x96
- tick_after
- tick_before
- total_crossed_ticks()
Returns the number of tick boundaries crossed during this swap.
This equals the length of the crossed_ticks vector and indicates how much liquidity the swap traversed.
- total_fee()
Returns the total fees paid in input token(LP fees + protocol fees).
- zero_for_one()
Determines swap direction from amount signs.
Returns true if swapping token0 for token1 (zero_for_one).
- class Symbol
Bases:
objectRepresents a valid ticker symbol ID for a tradable instrument.
- static from_str(value)
- is_composite
Returns true if the symbol string contains a period (.).
- root
Returns the symbol root.
The symbol root is the substring that appears before the first period (.) in the full symbol string. It typically represents the underlying asset for futures and options contracts. If no period is found, the entire symbol string is considered the root.
- topic
Returns the symbol topic.
The symbol topic is the root symbol with a wildcard (*) appended if the symbol has a root, otherwise returns the full symbol string.
- value
- class SyntheticInstrument
Bases:
objectRepresents a synthetic instrument with prices derived from component instruments using a formula.
The id for the synthetic will become {symbol}.{SYNTH}.
- calculate(inputs)
Calculates the price of the synthetic instrument based on the given component input prices provided as an array of f64 values.
# Errors
Returns an error if the input length does not match, any input is non-finite, or formula evaluation fails.
- calculate_from_map(inputs)
Calculates the price of the synthetic instrument based on component input prices provided as a map.
# Errors
Returns an error if formula evaluation fails or a required component price is missing from the input map.
- change_formula(formula)
Replaces the derivation formula, recompiling it against the existing components.
# Errors
Returns an error if parsing the new formula fails.
- components
- formula
- id
- is_valid_formula(formula)
Returns whether the given formula compiles against this instrument’s components.
- price_increment
- price_precision
- ts_event
- ts_init
- class TimeInForce
Bases:
objectThe ‘Time in Force’ instruction for an order.
- AT_THE_CLOSE = TimeInForce.AT_THE_CLOSE
- AT_THE_OPEN = TimeInForce.AT_THE_OPEN
- DAY = TimeInForce.DAY
- FOK = TimeInForce.FOK
- GTC = TimeInForce.GTC
- GTD = TimeInForce.GTD
- IOC = TimeInForce.IOC
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class Token
Bases:
objectRepresents a cryptocurrency token on a blockchain network.
- address
- chain
- decimals
- name
- symbol
- class TokenizedAsset
Bases:
objectRepresents a tokenized real-world asset traded as a pair on a crypto venue.
Covers tokenized equities, ETFs, commodities, and other asset classes where the underlying is represented as a base token traded against a quote currency. The asset_class field identifies the underlying asset type.
- asset_class
- base_currency
- static from_dict(values)
- id
- info
- instrument_class
- is_inverse
- is_quanto
- isin
- lot_size
- make_price(value)
Returns a price rounded to the instruments price precision.
- make_qty(value, round_down=False)
Returns a quantity rounded to the instruments size precision.
- maker_fee
- margin_init
- margin_maint
- max_notional
- max_price
- max_quantity
- min_notional
- min_price
- min_quantity
- multiplier
- next_ask_price(value, num_ticks=0)
Returns the price num_ticks ask ticks away from value.
- next_ask_prices(value, num_ticks=100)
Returns prices up to num_ticks ask ticks away from value.
- next_bid_price(value, num_ticks=0)
Returns the price num_ticks bid ticks away from value.
- next_bid_prices(value, num_ticks=100)
Returns prices up to num_ticks bid ticks away from value.
- notional_value(quantity, price, use_quote_for_inverse=False)
Calculates the notional value from the given quantity and price.
- price_increment
- price_precision
- quote_currency
- raw_symbol
- size_increment
- size_precision
- taker_fee
- tick_scheme
- to_dict()
- ts_event
- ts_init
- type_name
- class TradeId
Bases:
objectRepresents a valid trade match ID (assigned by a trading venue).
The unique ID assigned to the trade entity once it is received or matched by the venue or central counterparty.
Can correspond to the TradeID <1003> field of the FIX protocol.
Maximum length is 36 characters.
- static from_str(value)
- value
- class TradeTick
Bases:
objectRepresents a trade tick in a market.
- aggressor_side
- static from_dict(values)
Returns a new object from the given dictionary representation.
- static from_json(data)
- static from_msgpack(data)
- static from_raw(instrument_id, price_raw, price_prec, size_raw, size_prec, aggressor_side, trade_id, ts_event, ts_init)
- static fully_qualified_name()
- static get_fields()
Returns the field map for the type, for use with Arrow schemas.
- static get_metadata(instrument_id, price_precision, size_precision)
Returns the metadata for the type, for use with serialization formats.
- instrument_id
- price
- size
- to_dict()
Return a dictionary representation of the object.
- to_json_bytes()
Return JSON encoded bytes representation of the object.
- to_msgpack_bytes()
Return MsgPack encoded bytes representation of the object.
- trade_id
- ts_event
- ts_init
- class TraderId
Bases:
objectRepresents a valid trader ID.
- static from_str(value)
- value
- class TradingState
Bases:
objectThe trading state for a node.
- ACTIVE = TradingState.ACTIVE
- HALTED = TradingState.HALTED
- REDUCING = TradingState.REDUCING
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class TrailingOffsetType
Bases:
objectThe trailing offset type for an order type which specifies a trailing stop/trigger or limit price.
- BASIS_POINTS = TrailingOffsetType.BASIS_POINTS
- NO_TRAILING_OFFSET = TrailingOffsetType.NO_TRAILING_OFFSET
- PRICE = TrailingOffsetType.PRICE
- PRICE_TIER = TrailingOffsetType.PRICE_TIER
- TICKS = TrailingOffsetType.TICKS
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class TrailingStopLimitOrder
Bases:
object- account_id
- activation_price
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- commission(currency)
- commissions()
- contingency_type
- static create(init)
- display_qty
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- filled_qty
- static from_dict(values)
- has_price
- has_trigger_price
- init_event
- init_id
- instrument_id
- is_activated
- is_active_local
- is_aggressive
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_passive
- is_pending_cancel
- is_pending_update
- is_post_only
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- is_triggered
- last_event
- last_trade_id
- leaves_qty
- limit_offset
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- price
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- trailing_offset
- trailing_offset_type
- trigger_instrument_id
- trigger_price
- trigger_type
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- ts_triggered
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class TrailingStopMarketOrder
Bases:
object- account_id
- activation_price
- apply(event)
- avg_px
- client_order_id
- static closing_side(side)
- commission(currency)
- commissions()
- contingency_type
- static create(init)
- display_qty
- emulation_trigger
- event_count
- events()
- exec_algorithm_id
- exec_algorithm_params
- exec_spawn_id
- expire_time
- filled_qty
- static from_dict(values)
- has_price
- has_trigger_price
- init_event
- init_id
- instrument_id
- is_activated
- is_active_local
- is_aggressive
- is_buy
- is_canceled
- is_closed
- is_emulated
- is_inflight
- is_open
- is_passive
- is_pending_cancel
- is_pending_update
- is_primary
- is_quote_quantity
- is_reduce_only
- is_sell
- is_spawned
- is_triggered
- last_event
- last_trade_id
- leaves_qty
- linked_order_ids
- liquidity_side
- static opposite_side(side)
- order_list_id
- order_type
- overfill_qty
- parent_order_id
- position_id
- quantity
- side
- signed_decimal_qty()
- slippage
- status
- strategy_id
- tags
- time_in_force
- to_dict()
- trade_ids
- trader_id
- trailing_offset
- trailing_offset_type
- trigger_instrument_id
- trigger_price
- trigger_type
- ts_accepted
- ts_closed
- ts_init
- ts_last
- ts_submitted
- ts_triggered
- venue_order_id
- venue_order_ids
- would_reduce_only(side, position_qty)
- class Transaction
Bases:
objectRepresents a transaction on an EVM based blockchain.
- block_hash
- block_number
- chain
- from
- gas
- gas_price
- hash
- to
- transaction_index
- value
- class TriggerType
Bases:
objectThe trigger type for the stop/trigger price of an order.
- BID_ASK = TriggerType.BID_ASK
- DEFAULT = TriggerType.DEFAULT
- DOUBLE_BID_ASK = TriggerType.DOUBLE_BID_ASK
- DOUBLE_LAST = TriggerType.DOUBLE_LAST
- INDEX_PRICE = TriggerType.INDEX_PRICE
- LAST_OR_BID_ASK = TriggerType.LAST_OR_BID_ASK
- LAST_PRICE = TriggerType.LAST_PRICE
- MARK_PRICE = TriggerType.MARK_PRICE
- MID_POINT = TriggerType.MID_POINT
- NO_TRIGGER = TriggerType.NO_TRIGGER
- classmethod from_str(data)
- name
- value
- classmethod variants()
- class Venue
Bases:
objectRepresents a valid trading venue ID.
- static from_str(value)
- value
- class VenueOrderId
Bases:
objectRepresents a valid venue order ID (assigned by a trading venue).
- static from_str(value)
- value
- class WalletAccount
Bases:
object- account_type
- apply(event)
- balance(currency=None)
- balance_free(currency=None)
- balance_locked(currency=None)
- balance_total(currency=None)
- balances()
- balances_free()
- balances_locked()
- balances_total()
- base_currency
- calculate_account_state
- calculate_balance_locked(instrument, side, quantity, price, use_quote_for_inverse=None)
- calculate_commission(instrument, last_qty, last_px, liquidity_side, use_quote_for_inverse=None)
- calculate_pnls(instrument, fill, position=None)
- currencies()
- event_count
- events
- id
- is_cash_account()
- is_margin_account()
- last_event
- purge_account_events(ts_now, lookback_secs)
- starting_balances()
- to_dict()
- betting_account_from_account_events(events, calculate_account_state)
Constructs a BettingAccount from a list of Python dict events.
# Errors
Returns a PyErr if the input events list is empty.
- black_scholes_greeks(s, r, b, vol, is_call, k, t)
Computes Black-Scholes greeks using the fast compute_greeks implementation. This function uses compute_greeks from black_scholes.rs which is optimized for performance.
- calc_bets_pnl(bets)
Calculates the combined profit and loss for a slice of bets.
- cash_account_from_account_events(events, calculate_account_state, allow_borrowing=False)
Constructs a CashAccount from a list of Python dict events.
# Errors
Returns a PyErr if an event cannot be converted or the input events list is empty.
- custom_data_backend_kind(custom)
- deserialize_custom_from_json(type_name, payload)
Deserializes custom data from JSON bytes into a PyO3 CustomData wrapper.
# Errors
Returns a PyErr if the type is not registered or JSON deserialization fails.
- fold_net_position(legs)
Replays position legs onto a hypothetical NETTING position in ts_opened order, returning (net_signed_qty, net_avg_px_open).
Each leg is (signed_qty, avg_px_open, ts_opened_ns). Rules follow Position.apply: - Same-side legs produce a quantity-weighted average open price. - Opposite-side legs partial-close at the existing average. - A leg that crosses zero makes the residual take that leg’s price.
Zero-quantity legs are skipped. Sort is stable on ts_opened; the caller orders ties (e.g. by position_id).
- imply_vol(s, r, b, is_call, k, t, price)
Computes the implied volatility for an option given its parameters and market price.
# Errors
Returns a PyErr if implied volatility calculation fails.
- imply_vol_and_greeks(s, r, b, is_call, k, t, price)
Computes implied volatility and greeks using the fast implementations. This function uses compute_greeks after implying volatility.
- inverse_probability_to_bet(probability, volume, side)
Converts a probability and volume into a Bet using the inverse probability.
The side is also inverted (BUY becomes SELL and vice versa).
# Errors
Returns an error if probability is 1.0 or its inverse is zero.
- margin_account_from_account_events(events, calculate_account_state)
Constructs a MarginAccount from a list of Python dict events.
# Errors
Returns a PyErr if an event cannot be converted or the input events list is empty.
- probability_to_bet(probability, volume, side)
Converts a probability and volume into a Bet.
For a BUY side, this creates a BACK bet; for SELL, a LAY bet.
# Errors
Returns an error if probability is zero or the conversion overflows.
- refine_vol_and_greeks(s, r, b, is_call, k, t, target_price, initial_vol)
Refines implied volatility using an initial guess and computes greeks. This function uses compute_iv_and_greeks which performs a Halley iteration to refine the volatility estimate from an initial guess.
- register_custom_data_class(data_class)
Registers a custom data type (class) with the catalog registry.
Use this when you prefer to pass the class instead of a sample instance. The class must have: - type_name_static() class method or __name__ (used as type name in storage) - from_json(data) class method - decode_record_batch_py(metadata, batch) class method - Instances must have ts_event, ts_init, and encode_record_batch_py(items).
# Arguments
data_class - The custom data class (e.g. MarketTickPython or module.MarketTickData)
# Errors
Returns a PyErr if the class lacks required methods or the type is already registered.
# Example
from nautilus_trader.model import register_custom_data_class
- class MarketTickPython:
ts_event = 0 ts_init = 0
- def to_json(self):
return json.dumps(self.__dict__)
@classmethod def from_json(cls, data):
instance = cls() instance.__dict__.update(data) return instance
- def encode_record_batch_py(self, items):
raise NotImplementedError(“Arrow encoding is not configured”)
@classmethod def decode_record_batch_py(cls, metadata, batch):
raise NotImplementedError(“Arrow decoding is not configured”)
register_custom_data_class(MarketTickPython) ```
The Arrow methods may raise for a message-bus-only class, but must be implemented before catalog persistence is used.
- update_book_with_quote_tick(book, quote)
Updates the OrderBook with a [QuoteTick].
# Errors
Returns a PyErr if the update operation fails.
- update_book_with_trade_tick(book, trade)
Updates the OrderBook with a [TradeTick].
# Errors
Returns a PyErr if the update operation fails.
- wallet_account_from_account_events(events, calculate_account_state)
Constructs a WalletAccount from a list of Python dict events.
# Errors
Returns a PyErr if an event cannot be converted or the input events list is empty.