Model¶
The model subpackage defines a rich trading domain model.
The domain model is agnostic of any system design, seeking to represent the logic and state transitions of trading in a generic way. Many system implementations could be built around this domain model.
- class AccountBalance¶
Bases:
objectAccountBalance(Money total, Money locked, Money free) -> None
Represents an account balance denominated in a particular currency.
- Parameters:
- Raises:
ValueError – If money currencies are not equal.
ValueError – If total - locked != free.
- copy(self) AccountBalance¶
Return a copy of this account balance.
- Return type:
- currency¶
The currency of the account.
- Returns:
Currency
- free¶
The account balance free for trading.
- Returns:
Money
- static from_dict(dict values) AccountBalance¶
Return an account balance from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- locked¶
The account balance locked (assigned to pending orders).
- Returns:
Money
- to_dict(self) dict¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- total¶
The total account balance.
- Returns:
Money
- class AccountId¶
Bases:
IdentifierAccountId(str value) -> None
Represents a valid account ID.
Must be correctly formatted with two valid strings either side of a hyphen. It is expected an account ID is the name of the issuer with an account number separated by a hyphen.
Example: “IB-D02851908”.
- Parameters:
value (str) – The account ID value.
- Raises:
ValueError – If value is not a valid string containing a hyphen.
Warning
The issuer and number ID combination must be unique at the firm level.
- get_id(self) str¶
Return the account ID without issuer name.
- Return type:
str
- get_issuer(self) str¶
Return the account issuer for this ID.
- Return type:
str
- class Bar¶
Bases:
DataBar(BarType bar_type, Price open, Price high, Price low, Price close, Quantity volume, uint64_t ts_event, uint64_t ts_init, bool is_revision=False) -> None
Represents an aggregated bar.
- Parameters:
bar_type (BarType) – The bar type for this bar.
open (Price) – The bars open price.
high (Price) – The bars high price.
low (Price) – The bars low price.
close (Price) – The bars close price.
volume (Quantity) – The bars volume.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the data event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
is_revision (bool, default False) – If this bar is a revision of a previous bar with the same ts_event.
- Raises:
ValueError – If high is not >= low.
ValueError – If high is not >= close.
ValueError – If low is not <= close.
- bar_type¶
BarType
Return the bar type of bar.
- Return type:
- Type:
- static from_dict(dict values) Bar¶
Return a bar parsed from the given values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_bar) Bar¶
Return a legacy Cython bar converted from the given pyo3 Rust object.
- Parameters:
pyo3_bar (nautilus_pyo3.Bar) – The pyo3 Rust bar to convert from.
- Return type:
- static from_pyo3_list(list pyo3_bars) list[Bar]¶
Return legacy Cython bars converted from the given pyo3 Rust objects.
- Parameters:
pyo3_bars (list[nautilus_pyo3.Bar]) – The pyo3 Rust bars to convert from.
- Return type:
list[Bar]
- static from_raw(BarType bar_type, PriceRaw open, PriceRaw high, PriceRaw low, PriceRaw close, uint8_t price_prec, QuantityRaw volume, uint8_t size_prec, uint64_t ts_event, uint64_t ts_init) Bar¶
Create a bar from raw fixed-point values.
Warning
This method is primarily for internal use. Most users should use
from_dict()or other higher-level construction methods instead.All raw price/size values must be valid multiples of the scale factor for the given precision. Invalid raw values will raise a
ValueError. See: https://nautilustrader.io/docs/nightly/concepts/data#fixed-point-precision-and-raw-values
- static from_raw_arrays_to_list(BarType bar_type, uint8_t price_prec, uint8_t size_prec, double[: ] opens, double[: ] highs, double[: ] lows, double[: ] closes, double[: ] volumes, uint64_t[: ] ts_events, uint64_t[: ] ts_inits) list[Bar]¶
- is_revision¶
If this bar is a revision for a previous bar with the same ts_event.
- Returns:
bool
- is_single_price(self) bool¶
If the OHLC are all equal to a single price.
- Return type:
bool
- static to_dict(Bar obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- to_pyo3(self) nautilus_pyo3.Bar¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.Bar
- static to_pyo3_list(list bars) list[nautilus_pyo3.Bar]¶
Return pyo3 Rust bars converted from the given legacy Cython objects.
- Parameters:
bars (list[Bar]) – The legacy Cython bars to convert from.
- Return type:
list[nautilus_pyo3.Bar]
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- volume¶
Quantity
Return the volume of the bar.
- Return type:
- Type:
- class BarSpecification¶
Bases:
objectBarSpecification(int step, BarAggregation aggregation, PriceType price_type) -> None
Represents a bar aggregation specification that defines how market data should be aggregated into bars (candlesticks).
A bar specification consists of three main components: - Step: The quantity or interval for aggregation (e.g., 5 for 5-minute bars) - Aggregation: The method/rule for aggregation (time, tick, volume, value, etc.) - Price Type: Which price to use for aggregation (BID, ASK, MID, LAST)
Bar specifications are used to define different types of bars:
Time-based bars: Aggregate data over fixed time intervals - Examples: 1-MINUTE-LAST, 5-MINUTE-MID, 1-HOUR-BID
Tick-based bars: Aggregate data after a certain number of ticks - Examples: 100-TICK-LAST, 1000-TICK-MID
Volume-based bars: Aggregate data after a certain volume threshold - Examples: 1000-VOLUME-LAST, 10000-VOLUME-MID
Value-based bars: Aggregate data after a certain dollar value threshold - Examples: 100000-VALUE-LAST, 1000000-VALUE-MID
Information-based bars: Advanced aggregation based on information flow - Examples: 1000-VALUE_IMBALANCE-MID, 500-VALUE_RUNS-LAST
The specification determines: - What triggers bar creation (aggregation method) - How often bars are created (step size) - Which price level to use for OHLCV calculation (price type)
- Parameters:
step (int) – The step size for bar aggregation. Must be positive. - For time bars: interval in time units (1=1min, 5=5min, etc.) - For tick bars: number of ticks per bar - For volume/value bars: threshold amount
aggregation (BarAggregation) – The aggregation method (MINUTE, TICK, VOLUME, VALUE, etc.)
price_type (PriceType) – The price type to use (BID, ASK, MID, LAST)
- Raises:
ValueError – If step is not valid or if invalid aggregation/price_type combinations
Notes
Time Bar Aggregation Steps:
Time-based bars have specific constraints on allowed step values to ensure alignment with standard market time intervals:
- MILLISECOND: Steps 1-999 milliseconds (must divide evenly into 1000)
Valid: 1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500
- SECOND: Steps 1-59 seconds (must divide evenly into 60)
Valid: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30
- MINUTE: Steps 1-59 minutes (must divide evenly into 60)
Valid: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30
- HOUR: Steps 1-23 hours (must divide evenly into 24)
Valid: 1, 2, 3, 4, 6, 8, 12
DAY: Only step=1 allowed (1 day intervals)
WEEK: Only step=1 allowed (1 week intervals)
- MONTH: Steps 1-11 months (must divide evenly into 12)
Valid: 1, 2, 3, 4, 6 (e.g., 1-month, quarterly, semi-annual)
Invalid step values will raise ValueError during construction.
Composite Bars:
Composite bars are created by aggregating smaller time frame bars into larger time frame bars internally within the system. For example, a 5-minute composite bar can be created by aggregating five 1-minute bars.
Examples
Create time bar specifications with valid steps:
>>> spec1 = BarSpecification(1, BarAggregation.MINUTE, PriceType.LAST) # 1-min >>> spec4h = BarSpecification(4, BarAggregation.HOUR, PriceType.LAST) # 4-hour >>> spec6m = BarSpecification(6, BarAggregation.MONTH, PriceType.LAST) # semi-annual
>>> # Invalid steps will raise ValueError >>> try: ... invalid = BarSpecification(7, BarAggregation.MINUTE, PriceType.LAST) # 7 doesn't divide 60 ... except ValueError as e: ... print(f"Error: {e}")
Create composite bar setup:
>>> # Composite 5-minute specification for internal aggregation >>> composite_spec = BarSpecification(5, BarAggregation.MINUTE, PriceType.LAST) >>> composite_bar_type = BarType(instrument_id, composite_spec, AggregationSource.INTERNAL)
Check aggregation type and get timedelta:
>>> spec = BarSpecification(30, BarAggregation.SECOND, PriceType.LAST) >>> spec.is_time_aggregated() True >>> spec.timedelta datetime.timedelta(seconds=30)
>>> # Note: MONTH and YEAR aggregation doesn't support timedelta conversion >>> month_spec = BarSpecification(1, BarAggregation.MONTH, PriceType.LAST) >>> month_spec.is_time_aggregated() True >>> # month_spec.timedelta # This would raise ValueError
>>> # Threshold-based bars >>> tick_spec = BarSpecification(1000, BarAggregation.TICK, PriceType.MID) >>> tick_spec.is_threshold_aggregated() True >>> tick_spec.is_time_aggregated() False
Parse from string representation:
>>> spec = BarSpecification.from_str("15-MINUTE-BID") >>> print(f"Step: {spec.step}, Aggregation: {spec.aggregation}") Step: 15, Aggregation: BarAggregation.MINUTE
- aggregation¶
BarAggregation
Return the aggregation for the specification.
- Return type:
- Type:
- static check_information_aggregated(BarAggregation aggregation)¶
Check if the given aggregation is an information-based aggregation type.
Information-based aggregation creates bars based on market microstructure patterns and sequential runs of similar market events. These bars capture information flow and market efficiency patterns by detecting sequences of directionally similar price movements or trading activity.
Information-based aggregation types include: -
TICK_RUNS: Bars created when runs of tick price movements occur -VOLUME_RUNS: Bars created when runs of volume patterns occur -VALUE_RUNS: Bars created when runs of value patterns occurRuns are sequences of consecutive events with the same directional property (e.g., consecutive upticks or downticks). This aggregation method is useful for analyzing market microstructure, information flow, and detecting patterns in high-frequency trading activity.
This differs from time-based aggregation (fixed intervals) and threshold-based aggregation (activity levels), focusing instead on sequential patterns and information content of market events.
- Parameters:
aggregation (BarAggregation) – The aggregation type to check.
- Returns:
True if the aggregation is information-based, else False.
- Return type:
bool
Examples
>>> BarSpecification.check_information_aggregated(BarAggregation.TICK_RUNS) True >>> BarSpecification.check_information_aggregated(BarAggregation.VOLUME) False
- static check_threshold_aggregated(BarAggregation aggregation)¶
Check if the given aggregation is a threshold-based aggregation type.
Threshold-based aggregation creates bars when accumulated market activity reaches predefined thresholds, providing activity-driven sampling rather than time-driven sampling. These bars capture market dynamics based on actual trading patterns and volumes.
Threshold-based aggregation types include: -
TICK: Bars created after N ticks (price changes) -TICK_IMBALANCE: Bars created when tick imbalance reaches threshold -VOLUME: Bars created after N units of volume are traded -VOLUME_IMBALANCE: Bars created when volume imbalance reaches threshold -VALUE: Bars created after N units of notional value are traded -VALUE_IMBALANCE: Bars created when value imbalance reaches thresholdThis differs from time-based aggregation which creates bars at fixed time intervals, and information-based aggregation which creates bars based on market microstructure patterns and runs.
- Parameters:
aggregation (BarAggregation) – The aggregation type to check.
- Returns:
True if the aggregation is threshold-based, else False.
- Return type:
bool
Examples
>>> BarSpecification.check_threshold_aggregated(BarAggregation.VOLUME) True >>> BarSpecification.check_threshold_aggregated(BarAggregation.MINUTE) False
- static check_time_aggregated(BarAggregation aggregation)¶
Check if the given aggregation is a time-based aggregation type.
Time-based aggregation creates bars at fixed time intervals, where each bar represents market data for a specific time period. These bars are emitted when the time interval expires, regardless of trading activity level.
Time-based aggregation types include: -
MILLISECOND: Bars created every N milliseconds -SECOND: Bars created every N seconds -MINUTE: Bars created every N minutes -HOUR: Bars created every N hours -DAY: Bars created every N days (calendar days) -WEEK: Bars created every N weeks (calendar weeks) -MONTH: Bars created every N months (calendar months) -YEAR: Bars created every N years (calendar years)This is distinct from threshold-based aggregation (TICK, VOLUME, VALUE) which creates bars when activity thresholds are reached, and information-based aggregation (RUNS) which creates bars based on market microstructure patterns.
- Parameters:
aggregation (BarAggregation) – The aggregation type to check.
- Returns:
True if the aggregation is time-based, else False.
- Return type:
bool
Examples
>>> BarSpecification.check_time_aggregated(BarAggregation.MINUTE) True >>> BarSpecification.check_time_aggregated(BarAggregation.TICK) False
- static from_str(str value) BarSpecification¶
Return a bar specification parsed from the given string.
- Parameters:
value (str) – The bar specification string to parse.
Examples
String format example is ‘200-TICK-MID’.
- Return type:
- Raises:
ValueError – If value is not a valid string.
- static from_timedelta(timedelta duration, PriceType price_type) BarSpecification¶
Return a bar specification parsed from the given timedelta and price_type.
- Parameters:
duration (timedelta) – The bar specification timedelta to parse.
price_type (PriceType) – The bar specification price_type.
Examples
BarSpecification.from_timedelta(datetime.timedelta(minutes=5), PriceType.LAST).
- Return type:
- Raises:
ValueError – If duration is not rounded step of aggregation.
- get_interval_ns(self) uint64_t¶
Return the interval length in nanoseconds for time-based bar specifications.
Converts the bar specification’s time interval to nanoseconds based on its aggregation type and step size. This method is used for time calculations and (TODO: bar alignment).
- Returns:
The interval length in nanoseconds.
- Return type:
uint64_t
- Raises:
ValueError – If the aggregation is not a time-based aggregation.
Notes
Only time-based aggregations can be converted to nanosecond intervals. Threshold-based and information-based aggregations will raise a ValueError.
Month or year intervals use proxy values to estimate their respective durations.
Examples
>>> spec = BarSpecification(5, BarAggregation.MINUTE, PriceType.LAST) >>> spec.get_interval_ns() # Returns 5 minutes in nanoseconds 300000000000
- is_information_aggregated(self) bool¶
Return a value indicating whether the aggregation method is information-driven.
Information-based aggregation creates bars based on market microstructure patterns and sequential runs of similar market events. This aggregation method captures information flow, market efficiency patterns, and the sequential nature of trading activity by detecting directional runs.
Information-based aggregation types supported: -
TICK_RUNS: Bars based on runs of directional tick movements (upticks/downticks) -VOLUME_RUNS: Bars based on runs of volume patterns and clustering -VALUE_RUNS: Bars based on runs of notional value patternsA “run” is a sequence of consecutive market events with the same directional or categorical property. For example, a tick run might be 5 consecutive upticks followed by 3 consecutive downticks.
Information-based bars are ideal for: - Market microstructure analysis and information flow studies - Detecting patterns in high-frequency trading and market efficiency - Analyzing sequential dependencies in market data - Capturing information content rather than just time or activity levels - Studying market maker behavior and order flow dynamics
This differs from time-based aggregation (fixed time intervals) and threshold-based aggregation (activity levels), focusing instead on the sequential information content and patterns within market events.
- Returns:
True if the aggregation method is information-based, else False.
- Return type:
bool
See also
Get timedelta for time-based bars:
>>> spec = BarSpecification(30, BarAggregation.SECOND, PriceType.LAST) >>> spec.timedelta datetime.timedelta(seconds=30)
Examples
>>> spec = BarSpecification(1000, BarAggregation.VALUE_RUNS, PriceType.LAST) >>> spec.is_information_aggregated() True >>> spec = BarSpecification(1000, BarAggregation.VOLUME, PriceType.LAST) >>> spec.is_information_aggregated() False
- is_threshold_aggregated(self) bool¶
Return a value indicating whether the aggregation method is threshold-based.
Threshold-based aggregation types trigger bar creation when cumulative activity reaches predefined levels, making them ideal for volume and value-driven analysis rather than time-based intervals.
Threshold-Based Aggregation Types
Activity threshold types supported: -
TICK: Bars based on tick count thresholds (every N ticks) -VOLUME: Bars based on volume thresholds (every N units traded) -VALUE: Bars based on notional value thresholds (every N dollars/currency traded)Imbalance threshold types supported: -
TICK_IMBALANCE: Bars based on cumulative tick flow imbalances -VOLUME_IMBALANCE: Bars based on cumulative volume imbalances -VALUE_IMBALANCE: Bars based on cumulative value flow imbalancesThreshold-based bars are ideal for: - Volume and activity-based analysis independent of time - Capturing market activity during varying trading intensities - Equal-activity sampling for statistical analysis - Risk management based on position sizing and exposure levels - Algorithmic trading strategies sensitive to market participation
This differs from time-based aggregation (fixed time intervals) and information-based aggregation (information content patterns), focusing instead on measurable activity and participation thresholds.
- Returns:
True if the aggregation method is threshold-based, else False.
- Return type:
bool
See also
check_threshold_aggregatedStatic method for threshold aggregation checking
is_time_aggregatedCheck for time-based aggregation
is_information_aggregatedCheck for information-based aggregation
Examples
>>> spec = BarSpecification(1000, BarAggregation.TICK, PriceType.LAST) >>> spec.is_threshold_aggregated() True >>> spec = BarSpecification(100000, BarAggregation.VOLUME, PriceType.LAST) >>> spec.is_threshold_aggregated() True >>> spec = BarSpecification(5, BarAggregation.MINUTE, PriceType.LAST) >>> spec.is_threshold_aggregated() False
- is_time_aggregated(self) bool¶
Return a value indicating whether the aggregation method is time-driven.
Time-based aggregation creates bars at fixed time intervals based on calendar or clock time, providing consistent temporal sampling of market data. Each bar covers a specific time period regardless of trading activity level.
Time-based aggregation types supported: -
MILLISECOND: Fixed millisecond intervals (high-frequency sampling) -SECOND: Fixed second intervals (short-term patterns) -MINUTE: Fixed minute intervals (most common for retail trading) -HOUR: Fixed hour intervals (intraday analysis) -DAY: Fixed daily intervals (daily charts, longer-term analysis) -WEEK: Fixed weekly intervals (weekly patterns, medium-term trends) -MONTH: Fixed monthly intervals (long-term analysis, seasonal patterns) -YEAR: Fixed yearly intervals (annual trends, long-term investment)Time-based bars are ideal for: - Regular time-series analysis and charting - Consistent temporal sampling across different market conditions - Traditional technical analysis and pattern recognition - Comparing market behavior across fixed time periods
This differs from threshold aggregation (volume/tick-based) which creates bars when activity levels are reached, and information aggregation which creates bars based on market microstructure patterns.
- Returns:
True if the aggregation method is time-based, else False.
- Return type:
bool
See also
is_threshold_aggregatedCheck for threshold-based aggregation
is_information_aggregatedCheck for information-based aggregation
Examples
Create a 5-minute bar specification using last price:
>>> spec = BarSpecification(5, BarAggregation.MINUTE, PriceType.LAST) >>> str(spec) '5-MINUTE-LAST'
Create a tick bar specification:
>>> spec = BarSpecification(1000, BarAggregation.TICK, PriceType.MID) >>> str(spec) '1000-TICK-MID'
Parse from string:
>>> spec = BarSpecification.from_str("15-MINUTE-BID") >>> spec.step 15 >>> spec.aggregation BarAggregation.MINUTE
Check aggregation type:
>>> spec = BarSpecification(1, BarAggregation.HOUR, PriceType.LAST) >>> spec.is_time_aggregated() True >>> spec.is_threshold_aggregated() False
- price_type¶
PriceType
Return the price type for the specification.
- Return type:
PriceType
- Type:
- step¶
int
Return the step size for the specification.
- Return type:
int
- Type:
- timedelta¶
pd.Timedelta
Return the timedelta for the specification.
- Return type:
pandas.Timedelta
- Raises:
ValueError – If aggregation is not a time aggregation, or is``MONTH`` (which is ambiguous).
- Type:
- class BarType¶
Bases:
objectBarType(InstrumentId instrument_id, BarSpecification bar_spec, AggregationSource aggregation_source=AggregationSource.EXTERNAL) -> None
Represents a bar type including the instrument ID, bar specification and aggregation source.
- Parameters:
instrument_id (InstrumentId) – The bar type’s instrument ID.
bar_spec (BarSpecification) – The bar type’s specification.
aggregation_source (AggregationSource, default EXTERNAL) – The bar type aggregation source. If
INTERNALthe DataEngine will subscribe to the necessary ticks and aggregate bars accordingly. Else ifEXTERNALthen bars will be subscribed to directly from the venue / data provider.
Notes
Time aggregations support timedelta conversion
Threshold aggregations (tick, volume, value) don’t have fixed time intervals
Information aggregations use complex algorithms for bar creation
- String representation format: “{step}-{aggregation}-{price_type}”
It is expected that all bar aggregation methods other than time will be internally aggregated.
- aggregation_source¶
AggregationSource
Return the aggregation source for the bar type.
- Return type:
AggregationSource
- Type:
- static from_str(str value) BarType¶
Return a bar type parsed from the given string.
- Parameters:
value (str) – The bar type string to parse.
- Return type:
- Raises:
ValueError – If value is not a valid string.
- id_spec_key(self) tuple¶
Return 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.
- Return type:
tuple[InstrumentId, BarSpecification]
- instrument_id¶
InstrumentId
Return the instrument ID for the bar type.
- Return type:
- Type:
- is_composite(self) bool¶
Return a value indicating whether the bar type corresponds to BarType::Composite in Rust.
- Return type:
bool
- is_externally_aggregated(self) bool¶
Return a value indicating whether the bar aggregation source is
EXTERNAL.- Return type:
bool
- is_internally_aggregated(self) bool¶
Return a value indicating whether the bar aggregation source is
INTERNAL.- Return type:
bool
- is_standard(self) bool¶
Return a value indicating whether the bar type corresponds to BarType::Standard in Rust.
- Return type:
bool
- static new_composite(InstrumentId instrument_id, BarSpecification bar_spec, AggregationSource aggregation_source, int composite_step, BarAggregation composite_aggregation, AggregationSource composite_aggregation_source) BarType¶
- spec¶
BarSpecification
Return the specification for the bar type.
- Return type:
- Type:
- class BookLevel¶
Bases:
objectRepresents an order book price level.
A price level on one side of the order book with one or more individual orders.
This class is read-only and cannot be initialized from Python.
- Parameters:
- Raises:
ValueError – If orders is empty.
- exposure(self) double¶
Return the exposure at this level (price * volume).
- Return type:
double
- price¶
Price
Return the price for the level.
- Return type:
- Type:
- side¶
OrderSide
Return the side for the level.
- Return type:
OrderSide
- Type:
- size(self) double¶
Return the size at this level.
- Return type:
double
- class BookOrder¶
Bases:
objectBookOrder(OrderSide side, Price price, Quantity size, uint64_t order_id) -> None
Represents an order in a book.
- Parameters:
- exposure(self) double¶
Return the total exposure for this order (price * size).
- Return type:
double
- static from_dict(dict values) BookOrder¶
Return an order from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_raw(OrderSide side, PriceRaw price_raw, uint8_t price_prec, QuantityRaw size_raw, uint8_t size_prec, uint64_t order_id) BookOrder¶
Return a book order from the given raw values.
Warning
This method is primarily for internal use. Most users should use other higher-level construction methods instead.
All raw price/size values must be valid multiples of the scale factor for the given precision. Invalid raw values will raise a
ValueError. See: https://nautilustrader.io/docs/nightly/concepts/data#fixed-point-precision-and-raw-values- Parameters:
side (OrderSide {
BUY,SELL}) – The order side.price_raw (int) – The order raw price (as a scaled fixed-point integer).
price_prec (uint8_t) – The order price precision.
size_raw (int) – The order raw size (as a scaled fixed-point integer).
size_prec (uint8_t) – The order size precision.
order_id (uint64_t) – The order ID.
- Return type:
- order_id¶
uint64_t
Return the book orders side.
- Return type:
uint64_t
- Type:
- price¶
Price
Return the book orders price.
- Return type:
- Type:
- side¶
OrderSide
Return the book orders side.
- Return type:
OrderSide
- Type:
- signed_size(self) double¶
Return the signed size of the order (negative for
SELL).- Return type:
double
- size¶
Quantity
Return the book orders size.
- Return type:
- Type:
- static to_dict(BookOrder obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- class ClientId¶
Bases:
IdentifierClientId(str value) -> None
Represents a system client ID.
- Parameters:
value (str) – The client ID value.
- Raises:
ValueError – If value is not a valid string.
Warning
The ID value must be unique at the trader level.
- class ClientOrderId¶
Bases:
IdentifierClientOrderId(str value) -> None
Represents a valid client order ID (assigned by the Nautilus system).
- Parameters:
value (str) – The client order ID value.
- Raises:
ValueError – If value is not a valid string.
Warning
The ID value must be unique at the firm level.
- class ComponentId¶
Bases:
IdentifierComponentId(str value) -> None
Represents a valid component ID.
- Parameters:
value (str) – The component ID value.
- Raises:
ValueError – If value is not a valid string.
Warning
The ID value must be unique at the trader level.
- class Currency¶
Bases:
objectCurrency(str code, uint8_t precision, uint16_t iso4217, str name, CurrencyType currency_type) -> None
Represents a medium of exchange in a specified denomination with a fixed decimal precision.
Handles up to 16 decimals of precision (in high-precision mode).
- Parameters:
code (str) – The currency code.
precision (uint8_t) – The currency decimal precision.
iso4217 (uint16) – The currency ISO 4217 code.
name (str) – The currency name.
currency_type (CurrencyType) – The currency type.
- Raises:
ValueError – If code is not a valid string.
OverflowError – If precision is negative (< 0).
ValueError – If precision greater than 16.
ValueError – If name is not a valid string.
- code¶
str
Return the currency code.
- Return type:
str
- Type:
- currency_type¶
CurrencyType
Return the currency type.
- Return type:
CurrencyType
- Type:
- static from_internal_map(str code)¶
Return the currency with the given code from the built-in internal map (if found).
- Parameters:
code (str) – The code of the currency.
- Return type:
Currency or
None
- static from_str(str code, bool strict=False)¶
Parse a currency from the given string (if found).
- Parameters:
code (str) – The code of the currency.
strict (bool, default False) – If not strict mode then an unknown currency will very likely be a Cryptocurrency, so for robustness will then return a new Currency object using the given code with a default precision of 8.
- Return type:
Currency or
None
- static is_crypto(str code)¶
Return whether a currency with the given code is
CRYPTO.- Parameters:
code (str) – The code of the currency.
- Returns:
True if
CRYPTO, else False.- Return type:
bool
- Raises:
ValueError – If code is not a valid string.
- static is_fiat(str code)¶
Return whether a currency with the given code is
FIAT.- Parameters:
code (str) – The code of the currency.
- Returns:
True if
FIAT, else False.- Return type:
bool
- Raises:
ValueError – If code is not a valid string.
- iso4217¶
int
Return the currency ISO 4217 code.
- Return type:
str
- Type:
- name¶
str
Return the currency name.
- Return type:
str
- Type:
- precision¶
int
Return the currency decimal precision.
- Return type:
uint8
- Type:
- class CustomData¶
Bases:
DataCustomData(DataType data_type, Data data) -> None
Provides a wrapper for custom data which includes data type information.
- data¶
The data.
- Returns:
Data
- data_type¶
The data type.
- Returns:
DataType
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- class DataType¶
Bases:
objectDataType(type type, dict metadata=None) -> None
Represents a data type including metadata.
- Parameters:
type (type) – The Data type of the data.
metadata (dict) – The data types metadata.
- Raises:
ValueError – If type is not either a subclass of Data or meets the Data contract.
TypeError – If metadata contains a key or value which is not hashable.
Warning
This class may be used as a key in hash maps throughout the system, thus the key and value contents of metadata must themselves be hashable.
- metadata¶
The data types metadata.
- Returns:
dict[str, object]
- topic¶
The data types topic string.
- Returns:
str
- type¶
The Data type of the data.
- Returns:
type
- class ExecAlgorithmId¶
Bases:
IdentifierExecAlgorithmId(str value) -> None
Represents a valid execution algorithm ID.
- Parameters:
value (str) – The execution algorithm ID value.
- Raises:
ValueError – If value is not a valid string.
- class FundingRateUpdate¶
Bases:
DataFundingRateUpdate(InstrumentId instrument_id, rate, uint64_t ts_event, uint64_t ts_init, next_funding_ns=None) -> None
Represents a funding rate update for a perpetual swap instrument.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the funding rate.
rate (Decimal) – The current funding rate.
next_funding_ns (int, optional) – UNIX timestamp (nanoseconds) of the next funding payment (if available).
ts_event (int) – UNIX timestamp (nanoseconds) when the update occurred.
ts_init (int) – UNIX timestamp (nanoseconds) when the data object was initialized.
- static from_dict(dict values) FundingRateUpdate¶
Return a funding rate update from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_funding_rate) FundingRateUpdate¶
Return a legacy Cython funding rate update converted from the given pyo3 Rust object.
- Parameters:
pyo3_funding_rate (nautilus_pyo3.FundingRateUpdate) – The pyo3 Rust funding rate update to convert from.
- Return type:
- static from_pyo3_list(list pyo3_funding_rates) list[FundingRateUpdate]¶
Return legacy Cython funding rate updates converted from the given pyo3 Rust objects.
- Parameters:
pyo3_funding_rates (list[nautilus_pyo3.FundingRateUpdate]) – The pyo3 Rust funding rate updates to convert from.
- Return type:
list[FundingRateUpdate]
- instrument_id¶
The instrument ID for the funding rate.
- Returns:
InstrumentId
- next_funding_ns¶
UNIX timestamp (nanoseconds) of the next funding payment (if available, otherwise zero).
- Returns:
int or
None
- rate¶
The current funding rate.
- Returns:
Decimal
- static to_dict(FundingRateUpdate obj) dict[str, object]¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- class InstrumentClose¶
Bases:
DataInstrumentClose(InstrumentId instrument_id, Price close_price, InstrumentCloseType close_type, uint64_t ts_event, uint64_t ts_init) -> None
Represents an instrument close at a venue.
- Parameters:
instrument_id (InstrumentId) – The instrument ID.
close_price (Price) – The closing price for the instrument.
close_type (InstrumentCloseType) – The type of closing price.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the close price event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
- close_price¶
The instrument close price.
- Returns:
Price
- close_type¶
The instrument close type.
- Returns:
InstrumentCloseType
- static from_dict(dict values) InstrumentClose¶
Return an instrument close price event from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_close) InstrumentClose¶
Return a legacy Cython instrument close converted from the given pyo3 Rust object.
- Parameters:
pyo3_close (nautilus_pyo3InstrumentClose.) – The pyo3 Rust instrument close to convert from.
- Return type:
- static from_pyo3_list(list pyo3_closes) list[InstrumentClose]¶
Return legacy Cython instrument closes converted from the given pyo3 Rust objects.
- Parameters:
pyo3_closes (list[nautilus_pyo3.InstrumentClose]) – The pyo3 Rust instrument closes to convert from.
- Return type:
list[InstrumentClose]
- instrument_id¶
The event instrument ID.
- Returns:
InstrumentId
- static to_dict(InstrumentClose obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- to_pyo3(self) nautilus_pyo3.InstrumentClose¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.InstrumentClose
- static to_pyo3_list(list closes) list[nautilus_pyo3.InstrumentClose]¶
Return pyo3 Rust index prices converted from the given legacy Cython objects.
- Parameters:
closes (list[InstrumentClose]) – The legacy Cython Rust instrument closes to convert from.
- Return type:
list[nautilus_pyo3.InstrumentClose]
- ts_event¶
UNIX timestamp (nanoseconds) when the data event occurred.
- Returns:
uint64_t
- ts_init¶
UNIX timestamp (nanoseconds) when the instance was created.
- Returns:
uint64_t
- class InstrumentId¶
Bases:
IdentifierInstrumentId(Symbol symbol, Venue venue) -> None
Represents a valid instrument ID.
The symbol and venue combination should uniquely identify the instrument.
- Parameters:
- static from_pyo3(pyo3_instrument_id) InstrumentId¶
Return an instrument ID from the given PyO3 instance.
- Parameters:
value (nautilus_pyo3.InstrumentId) – The PyO3 instrument ID instance.
- Return type:
- static from_str(str value: str) InstrumentId¶
Return an instrument ID parsed from the given string value. Must be correctly formatted including symbol and venue components either side of a single period.
Examples: ‘AUD/USD.IDEALPRO’, ‘BTCUSDT.BINANCE’
- Parameters:
value (str) – The instrument ID string value to parse.
- Return type:
- Raises:
ValueError – If value is not a valid instrument ID string.
- is_synthetic(self) bool¶
Return whether the instrument ID is a synthetic instrument (with venue of ‘SYNTH’).
- Return type:
bool
- symbol¶
Symbol
Returns the instrument ticker symbol.
- Return type:
- Type:
- to_pyo3(self)¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.InstrumentId
- venue¶
Venue
Returns the instrument trading venue.
- Return type:
- Type:
- class InstrumentStatus¶
Bases:
DataInstrumentStatus(InstrumentId instrument_id, MarketStatusAction action, uint64_t ts_event, uint64_t ts_init, str reason=None, str trading_event=None, bool is_trading: bool | None = None, bool is_quoting: bool | None = None, bool is_short_sell_restricted: bool | None = None) -> None
Represents an event that indicates a change in an instrument market status.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the status change.
action (MarketStatusAction) – The instrument market status action.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the status event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
reason (str, optional) – Additional details about the cause of the status change.
trading_event (str, optional) – Further information about the status change (if provided).
is_trading (bool, optional) – The state of trading in the instrument.
is_quoting (bool, optional) – The state of quoting in the instrument.
is_short_sell_restricted (bool, optional) – The state of short sell restrictions for the instrument (if applicable).
- action¶
The instrument market status action.
- Returns:
MarketStatusAction
- static from_dict(dict values) InstrumentStatus¶
Return an instrument status update from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_status) InstrumentStatus¶
Return a legacy Cython quote tick converted from the given pyo3 Rust object.
- Parameters:
pyo3_status (nautilus_pyo3.InstrumentStatus) – The pyo3 Rust instrument status to convert from.
- Return type:
- static from_pyo3_list(list pyo3_status_list) list[QuoteTick]¶
Return legacy Cython instrument status converted from the given pyo3 Rust objects.
- Parameters:
pyo3_status_list (list[nautilus_pyo3.InstrumentStatus]) – The pyo3 Rust instrument status list to convert from.
- Return type:
list[InstrumentStatus]
- instrument_id¶
The instrument ID.
- Returns:
InstrumentId
- is_quoting¶
bool | None
Return the state of quoting in the instrument (if known).
- Return type:
bool or
None- Type:
- is_short_sell_restricted¶
bool | None
Return the state of short sell restrictions for the instrument (if known and applicable).
- Return type:
bool or
None- Type:
- is_trading¶
bool | None
Return the state of trading in the instrument (if known).
- Return type:
bool or
None- Type:
- reason¶
Additional details about the cause of the status change.
- Returns:
str or
None
- static to_dict(InstrumentStatus obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- to_pyo3(self) nautilus_pyo3.InstrumentStatus¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.InstrumentStatus
- trading_event¶
Further information about the status change (if provided).
- Returns:
str or
None
- ts_event¶
UNIX timestamp (nanoseconds) when the data event occurred.
- Returns:
uint64_t
- ts_init¶
UNIX timestamp (nanoseconds) when the instance was created.
- Returns:
uint64_t
- class MarginBalance¶
Bases:
objectMarginBalance(Money initial, Money maintenance, InstrumentId instrument_id=None) -> None
Represents a margin balance optionally associated with a particular instrument.
- Parameters:
initial (Money) – The initial (order) margin requirement for the instrument.
maintenance (Money) – The maintenance (position) margin requirement for the instrument.
instrument_id (InstrumentId, optional) – The instrument ID associated with the margin.
- Raises:
ValueError – If margin_init currency does not equal currency.
ValueError – If margin_maint currency does not equal currency.
ValueError – If any margin is negative (< 0).
- copy(self) MarginBalance¶
Return a copy of this margin balance.
- Return type:
- currency¶
The currency of the margin.
- Returns:
Currency
- static from_dict(dict values) MarginBalance¶
Return a margin balance from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
MarginAccountBalance
- initial¶
The initial margin requirement.
- Returns:
Money
- instrument_id¶
The instrument ID associated with the margin.
- Returns:
InstrumentId or
None
- maintenance¶
The maintenance margin requirement.
- Returns:
Money
- to_dict(self) dict¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- class MarkPriceUpdate¶
Bases:
DataMarkPriceUpdate(InstrumentId instrument_id, Price value, uint64_t ts_event, uint64_t ts_init) -> None
Represents a mark price update.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the mark price.
value (Price) – The mark price.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the update occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
- static from_dict(dict values) MarkPriceUpdate¶
Return a mark price from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_mark_price) MarkPriceUpdate¶
Return a legacy Cython mark price converted from the given pyo3 Rust object.
- Parameters:
pyo3_trade (nautilus_pyo3.MarkPriceUpdate) – The pyo3 Rust mark price to convert from.
- Return type:
- static from_pyo3_list(list pyo3_mark_prices) list[MarkPriceUpdate]¶
Return legacy Cython trades converted from the given pyo3 Rust objects.
- Parameters:
pyo3_mark_prices (list[nautilus_pyo3.MarkPriceUpdate]) – The pyo3 Rust mark prices to convert from.
- Return type:
list[MarkPriceUpdate]
- instrument_id¶
InstrumentId
Return the instrument ID.
- Return type:
- Type:
- static to_dict(MarkPriceUpdate obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- to_pyo3(self) nautilus_pyo3.MarkPriceUpdate¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.MarkPriceUpdate
- static to_pyo3_list(list mark_prices) list[nautilus_pyo3.MarkPriceUpdate]¶
Return pyo3 Rust mark prices converted from the given legacy Cython objects.
- Parameters:
mark_prices (list[MarkPriceUpdate]) – The legacy Cython Rust mark prices to convert from.
- Return type:
list[nautilus_pyo3.MarkPriceUpdate]
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- value¶
Price
The mark price.
- Return type:
- Type:
- class Money¶
Bases:
objectMoney(value, Currency currency) -> None
Represents an amount of money in a specified currency denomination.
MONEY_MAX= 17_014_118_346_046MONEY_MIN= -17_014_118_346_046
- Parameters:
value (integer, float, string or Decimal) – The amount of money in the currency denomination.
currency (Currency) – The currency of the money.
- Raises:
ValueError – If value is greater than 17_014_118_346_046.
ValueError – If value is less than -17_014_118_346_046.
- as_decimal(self)¶
Return the value as a built-in Decimal.
- Return type:
Decimal
- as_double(self) double¶
Return the value as a double.
- Return type:
double
- currency¶
Currency
Return the currency for the money.
- Return type:
- Type:
- static from_decimal(amount: decimal.Decimal, Currency currency) Money¶
Return money from the given Decimal amount and currency.
Handles up to 16 decimals of precision (in high-precision mode).
- Parameters:
amount (Decimal) – The Decimal amount for the money.
currency (Currency) – The currency of the money.
- Return type:
- Raises:
ValueError – If inferred currency precision is greater than 16.
ValueError – If raw value is outside the valid representable range [MONEY_RAW_MIN, MONEY_RAW_MAX].
OverflowError – If inferred currency precision is negative (< 0).
Warning
The decimal precision will be inferred from the number of digits following the ‘.’ point (if no point then precision zero).
- static from_raw(int raw: int, Currency currency) Money¶
Return money from the given raw fixed-point integer and currency.
- Parameters:
raw (int) – The raw fixed-point money amount.
currency (Currency) – The currency of the money.
- Return type:
Warning
Small raw values can produce a zero money amount depending on the precision of the currency.
- static from_str(str value) Money¶
Return money parsed from the given string.
Must be correctly formatted with a value and currency separated by a whitespace delimiter.
Example: “1000000.00 USD”.
- Parameters:
value (str) – The value to parse.
- Return type:
- Raises:
ValueError – If inferred currency precision is greater than 16.
ValueError – If raw value is outside the valid representable range [MONEY_RAW_MIN, MONEY_RAW_MAX].
OverflowError – If inferred currency precision is negative (< 0).
- raw¶
MoneyRaw
Return the raw memory representation of the money amount.
- Return type:
int
- Type:
- to_formatted_str(self) str¶
Return the formatted string representation of the money.
- Return type:
str
- class OrderBook¶
Bases:
DataOrderBook(InstrumentId instrument_id, BookType book_type) -> None
Provides an order book which can handle L1/L2/L3 granularity data.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the order book.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.
- add(self, BookOrder order, uint64_t ts_event, uint8_t flags=0, uint64_t sequence=0) void¶
Add the given order to the book.
- Parameters:
order (BookOrder) – The order to add.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the book event occurred.
flags (uint8_t, default 0) – The record flags bit field, indicating event end and data information.
sequence (uint64_t, default 0) – The unique sequence number for the update. If default 0 then will increment the sequence.
- Raises:
RuntimeError – If the book type is L1_MBP.
- apply(self, Data data) void¶
Apply the given data to the order book.
- Parameters:
delta (OrderBookDelta, OrderBookDeltas) – The data to apply.
- apply_delta(self, OrderBookDelta delta) void¶
Apply the order book delta.
- Parameters:
delta (OrderBookDelta) – The delta to apply.
- Raises:
ValueError – If delta.book_type is not equal to self.type.
- apply_deltas(self, OrderBookDeltas deltas) void¶
Apply the bulk deltas to the order book.
- Parameters:
deltas (OrderBookDeltas) – The deltas to apply.
- apply_depth(self, OrderBookDepth10 depth) void¶
Apply the depth update to the order book.
- Parameters:
depth (OrderBookDepth10) – The depth update to apply.
- asks(self) list¶
Return the bid levels for the order book.
- Returns:
Sorted in ascending order of price.
- Return type:
list[BookLevel]
- best_ask_price(self)¶
Return the best ask price in the book (if no asks then returns
None).- Return type:
double
- best_ask_size(self)¶
Return the best ask size in the book (if no asks then returns
None).- Return type:
double or
None
- best_bid_price(self)¶
Return the best bid price in the book (if no bids then returns
None).- Return type:
double
- best_bid_size(self)¶
Return the best bid size in the book (if no bids then returns
None).- Return type:
double
- bids(self) list¶
Return the bid levels for the order book.
- Returns:
Sorted in descending order of price.
- Return type:
list[BookLevel]
- book_type¶
BookType
Return the order book type.
- Return type:
BookType
- Type:
- check_integrity(self) void¶
Check book integrity.
For all order books: - The bid side price should not be greater than the ask side price.
- Raises:
RuntimeError – If book integrity check fails.
- clear(self, uint64_t ts_event, uint64_t sequence=0) void¶
Clear the entire order book.
- clear_asks(self, uint64_t ts_event, uint64_t sequence=0) void¶
Clear the asks from the order book.
- clear_bids(self, uint64_t ts_event, uint64_t sequence=0) void¶
Clear the bids from the order book.
- delete(self, BookOrder order, uint64_t ts_event, uint8_t flags=0, uint64_t sequence=0) void¶
Cancel the given order in the book.
- Parameters:
order (Order) – The order to delete.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the book event occurred.
flags (uint8_t, default 0) – The record flags bit field, indicating event end and data information.
sequence (uint64_t, default 0) – The unique sequence number for the update. If default 0 then will increment the sequence.
- get_all_crossed_levels(self, OrderSide order_side, Price price, uint8_t size_prec) list¶
Return all price levels that would be crossed by an order at the given price.
Unlike simulate_fills, this returns ALL crossed levels regardless of order quantity. Used when liquidity consumption tracking needs visibility into all available levels.
- get_avg_px_for_quantity(self, Quantity quantity, OrderSide order_side) double¶
Return the average price expected for the given quantity based on the current state of the order book.
- Parameters:
quantity (Quantity) – The quantity for the calculation.
order_side (OrderSide) – The order side for the calculation.
- Return type:
double
- Raises:
ValueError – If order_side is equal to
NO_ORDER_SIDE
Warning
If no average price can be calculated then will return 0.0 (zero).
- get_quantity_at_level(self, Price price, OrderSide order_side, uint8_t size_precision) Quantity¶
Return the quantity at a specific price level only.
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(self, Price price, OrderSide order_side) double¶
Return the cumulative quantity at or better than the given 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.
- Parameters:
price (Price) – The price for the calculation.
order_side (OrderSide) – The order side for the calculation.
- Return type:
double
- Raises:
ValueError – If order_side is equal to
NO_ORDER_SIDE
- get_worst_px_for_quantity(self, Quantity quantity, OrderSide order_side)¶
Return the worst (last-touched) price required to fill the given quantity based on the current state of the order book.
- Parameters:
quantity (Quantity) – The quantity for the calculation.
order_side (OrderSide) – The order side for the calculation.
- Return type:
Price or
None- Raises:
ValueError – If order_side is equal to
NO_ORDER_SIDE
Warning
If no worst price can be calculated then returns
None.
- instrument_id¶
InstrumentId
Return the books instrument ID.
- Return type:
- Type:
- midpoint(self)¶
Return the mid point (if no market exists then returns
None).- Return type:
double or
None
- pprint(self, int num_levels=3) str¶
Return a string representation of the order book in a human-readable table format.
- Parameters:
num_levels (int) – The number of levels to include.
- Return type:
str
- reset(self) void¶
Reset the order book (clear all stateful values).
- sequence¶
int
Return the last sequence number for the book.
- Return type:
int
- Type:
- simulate_fills(self, Order order, uint8_t price_prec, uint8_t size_prec, bool is_aggressive) list¶
Simulate filling the book with the given order.
- Parameters:
order (Order) – The order to simulate fills for.
price_prec (uint8_t) – The price precision for the fills.
size_prec (uint8_t) – The size precision for the fills (based on the instrument definition).
is_aggressive (bool) – If the order is an aggressive liquidity taking order.
- spread(self)¶
Return the top-of-book spread (if no bids or asks then returns
None).- Return type:
double or
None
- to_deltas_c(self, uint64_t ts_event, uint64_t ts_init) OrderBookDeltas¶
- to_quote_tick(self) QuoteTick¶
Return a QuoteTick created from the top of book levels.
Returns
Nonewhen the top-of-book bid or ask is missing or invalid (zero size).- Return type:
QuoteTick or
None
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- ts_last¶
int
Return the UNIX timestamp (nanoseconds) when the order book was last updated.
- Return type:
int
- Type:
- update(self, BookOrder order, uint64_t ts_event, uint8_t flags=0, uint64_t sequence=0) void¶
Update the given order in the book.
- Parameters:
order (Order) – The order to update.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the book event occurred.
flags (uint8_t, default 0) – The record flags bit field, indicating event end and data information.
sequence (uint64_t, default 0) – The unique sequence number for the update. If default 0 then will increment the sequence.
- update_count¶
int
Return the books update count.
- Return type:
int
- Type:
- class OrderBookDelta¶
Bases:
DataOrderBookDelta(InstrumentId instrument_id, BookAction action, BookOrder order: BookOrder | None, uint8_t flags, uint64_t sequence, uint64_t ts_event, uint64_t ts_init) -> None
Represents a single update/difference on an OrderBook.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the book.
action (BookAction {
ADD,UPDATE,DELETE,CLEAR}) – The order book delta action.order (BookOrder or
None) – The book order for the delta.flags (uint8_t) – The record flags bit field, indicating event end and data information. A value of zero indicates no flags.
sequence (uint64_t) – The unique sequence number for the update. If no sequence number provided in the source data then use a value of zero.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the data event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
- Raises:
ValueError – If action is ADD or UPDATE and order.size is not positive (> 0).
- action¶
BookAction
Return the deltas book action {
ADD,UPDATE,DELETE,CLEAR}- Return type:
BookAction
- Type:
- static capsule_from_list(list items)¶
- static clear(InstrumentId instrument_id, uint64_t sequence, uint64_t ts_event, uint64_t ts_init)¶
Return an order book delta which acts as an initial
CLEAR.- Return type:
- flags¶
uint8_t
Return the flags for the delta.
- Return type:
uint8_t
- Type:
- static from_dict(dict values) OrderBookDelta¶
Return an order book delta from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_delta) OrderBookDelta¶
Return a legacy Cython order book delta converted from the given pyo3 Rust object.
- Parameters:
pyo3_delta (nautilus_pyo3.OrderBookDelta) – The pyo3 Rust order book delta to convert from.
- Return type:
- static from_pyo3_list(list pyo3_deltas) list[OrderBookDelta]¶
Return legacy Cython order book deltas converted from the given pyo3 Rust objects.
- Parameters:
pyo3_deltas (list[nautilus_pyo3.OrderBookDelta]) – The pyo3 Rust order book deltas to convert from.
- Return type:
list[OrderBookDelta]
- static from_raw(InstrumentId instrument_id, BookAction action, OrderSide side, PriceRaw price_raw, uint8_t price_prec, QuantityRaw size_raw, uint8_t size_prec, uint64_t order_id, uint8_t flags, uint64_t sequence, uint64_t ts_event, uint64_t ts_init) OrderBookDelta¶
Return an order book delta from the given raw values.
Warning
This method is primarily for internal use. Most users should use other higher-level construction methods instead.
All raw price/size values must be valid multiples of the scale factor for the given precision. Invalid raw values will raise a
ValueError. See: https://nautilustrader.io/docs/nightly/concepts/data#fixed-point-precision-and-raw-values- Parameters:
instrument_id (InstrumentId) – The trade instrument ID.
action (BookAction {
ADD,UPDATE,DELETE,CLEAR}) – The order book delta action.side (OrderSide {
BUY,SELL}) – The order side.price_raw (int) – The order raw price (as a scaled fixed-point integer).
price_prec (uint8_t) – The order price precision.
size_raw (int) – The order raw size (as a scaled fixed-point integer).
size_prec (uint8_t) – The order size precision.
order_id (uint64_t) – The order ID.
flags (uint8_t) – The record flags bit field, indicating event end and data information. A value of zero indicates no flags.
sequence (uint64_t) – The unique sequence number for the update. If no sequence number provided in the source data then use a value of zero.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the tick event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
- Return type:
- instrument_id¶
InstrumentId
Return the deltas book instrument ID.
- Return type:
- Type:
- is_add¶
BookAction
If the deltas book action is an
ADD.- Return type:
bool
- Type:
- is_clear¶
BookAction
If the deltas book action is a
CLEAR.- Return type:
bool
- Type:
- is_delete¶
BookAction
If the deltas book action is a
DELETE.- Return type:
bool
- Type:
- is_update¶
BookAction
If the deltas book action is an
UPDATE.- Return type:
bool
- Type:
- static list_from_capsule(capsule) list[OrderBookDelta]¶
- order¶
BookOrder | None
Return the deltas book order for the action.
- Return type:
- Type:
- sequence¶
uint64_t
Return the sequence number for the delta.
- Return type:
uint64_t
- Type:
- static to_dict(OrderBookDelta obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- static to_pyo3_list(list deltas) list[nautilus_pyo3.OrderBookDelta]¶
Return pyo3 Rust order book deltas converted from the given legacy Cython objects.
- Parameters:
pyo3_deltas (list[OrderBookDelta]) – The pyo3 Rust order book deltas to convert from.
- Return type:
list[nautilus_pyo3.OrderBookDelta]
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- class OrderBookDeltas¶
Bases:
DataOrderBookDeltas(InstrumentId instrument_id, list deltas) -> None
Represents a batch of OrderBookDelta updates for an OrderBook.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the book.
deltas (list[OrderBookDelta]) – The batch of order book changes.
- Raises:
ValueError – If deltas is an empty list.
- static batch(list data: list[OrderBookDelta]) list[OrderBookDeltas]¶
Groups the given list of OrderBookDelta records into batches, creating OrderBookDeltas objects when an F_LAST flag is encountered.
The method iterates through the data list and appends each OrderBookDelta to the current batch. When an F_LAST flag is found, it indicates the end of a batch. The batch is then appended to the list of completed batches and a new batch is started.
- Return type:
list[OrderBookDeltas]
- Raises:
ValueError – If data is empty.
TypeError – If data is not a list of OrderBookDelta.
Warning
- UserWarning
If there are remaining deltas in the final batch after the last F_LAST flag.
- deltas¶
list[OrderBookDelta]
Return the contained deltas.
- Return type:
list[OrderBookDeltas]
- Type:
- flags¶
uint8_t
Return the flags for the last delta.
- Return type:
uint8_t
- Type:
- static from_dict(dict values) OrderBookDeltas¶
Return order book deltas from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_deltas) OrderBookDeltas¶
Return legacy Cython orderbook deltas converted from the given pyo3 Rust object.
- Parameters:
pyo3_deltas (nautilus_pyo3.OrderBookDeltas) – The pyo3 Rust orderbook deltas to convert from.
- Return type:
- instrument_id¶
InstrumentId
Return the deltas book instrument ID.
- Return type:
- Type:
- is_snapshot¶
bool
If the deltas is a snapshot.
- Return type:
bool
- Type:
- sequence¶
uint64_t
Return the sequence number for the last delta.
- Return type:
uint64_t
- Type:
- to_capsule(self)¶
- static to_dict(OrderBookDeltas obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- to_pyo3(self)¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.OrderBookDeltas
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- class OrderBookDepth10¶
Bases:
DataOrderBookDepth10(InstrumentId instrument_id, list bids, list asks, list bid_counts, list ask_counts, uint8_t flags, uint64_t sequence, uint64_t ts_event, uint64_t ts_init) -> None
Represents a self-contained order book update with a fixed depth of 10 levels per side.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the book.
bids (list[BookOrder]) – The bid side orders for the update.
asks (list[BookOrder]) – The ask side orders for the update.
bid_counts (list[uint32_t]) – The count of bid orders per level for the update. Can be zeros if data not available.
ask_counts (list[uint32_t]) – The count of ask orders per level for the update. Can be zeros if data not available.
flags (uint8_t) – The record flags bit field, indicating event end and data information. A value of zero indicates no flags.
sequence (uint64_t) – The unique sequence number for the update. If no sequence number provided in the source data then use a value of zero.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the tick event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
- Raises:
ValueError – If bids, asks, bid_counts, ask_counts lengths are greater than 10.
ValueError – If bids, asks, bid_counts, ask_counts lengths are not equal.
- ask_counts¶
list[uint32_t]
Return the count of ask orders level for the update.
- Return type:
list[uint32_t]
- Type:
- bid_counts¶
list[uint32_t]
Return the count of bid orders per level for the update.
- Return type:
list[uint32_t]
- Type:
- static capsule_from_list(list items)¶
- flags¶
uint8_t
Return the flags for the depth update.
- Return type:
uint8_t
- Type:
- static from_dict(dict values) OrderBookDepth10¶
Return order book depth from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_depth) OrderBookDepth10¶
Return a legacy Cython order book depth converted from the given pyo3 Rust object.
- Parameters:
pyo3_depth (nautilus_pyo3.OrderBookDepth10) – The pyo3 Rust order book depth to convert from.
- Return type:
- static from_pyo3_list(pyo3_depths) list[OrderBookDepth10]¶
Return legacy Cython order book depths converted from the given pyo3 Rust objects.
- Parameters:
pyo3_depths (nautilus_pyo3.OrderBookDepth10) – The pyo3 Rust order book depths to convert from.
- Return type:
list[OrderBookDepth10]
- instrument_id¶
InstrumentId
Return the depth updates book instrument ID.
- Return type:
- Type:
- static list_from_capsule(capsule) list[OrderBookDepth10]¶
- sequence¶
uint64_t
Return the sequence number for the depth update.
- Return type:
uint64_t
- Type:
- static to_dict(OrderBookDepth10 obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- to_quote_tick(self) QuoteTick¶
Return a QuoteTick created from the top of book levels.
Returns
Nonewhen the top-of-book bid or ask is missing or invalid (NULL order or zero size).- Return type:
QuoteTick or
None
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- class OrderListId¶
Bases:
IdentifierOrderListId(str value) -> None
Represents a valid order list ID (assigned by the Nautilus system).
- Parameters:
value (str) – The order list ID value.
- Raises:
ValueError – If value is not a valid string.
- class Position¶
Bases:
objectPosition(Instrument instrument, OrderFilled fill) -> None
Represents 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.
- Parameters:
instrument (Instrument) – The trading instrument for the position.
fill (OrderFilled) – The order fill event which opened the position.
- Raises:
ValueError – If instrument.id is not equal to fill.instrument_id.
ValueError – If fill.position_id is
None.
- account_id¶
The account ID associated with the position.
- Returns:
AccountId
- adjustments¶
Return the position adjustment events.
- Return type:
list[PositionAdjusted]
- apply(self, OrderFilled fill) void¶
Applies the given order fill event to the position.
If the position is FLAT prior to applying fill, the position state is reset (clearing existing events, commissions, etc.) before processing the new fill.
- Parameters:
fill (OrderFilled) – The order fill event to apply.
- Raises:
KeyError – If fill.trade_id already applied to the position.
- apply_adjustment(self, PositionAdjusted adjustment) void¶
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.
- Parameters:
adjustment (PositionAdjusted) – The position adjustment event to apply.
- avg_px_close¶
The average close price.
- Returns:
double
- avg_px_open¶
The average open price.
- Returns:
double
- base_currency¶
The position base currency (if applicable).
- Returns:
Currency or
None
- calculate_pnl(self, double avg_px_open, double avg_px_close, Quantity quantity) Money¶
Return a calculated PnL in the instrument’s settlement currency.
- client_order_ids¶
Return the client order IDs associated with the position.
- Return type:
list[ClientOrderId]
Notes
Guaranteed not to contain duplicate IDs.
- closing_order_id¶
The client order ID for the order which closed the position.
- Returns:
ClientOrderId or
None
- closing_order_side(self) OrderSide¶
Return the closing order side for the position.
If the position is
FLATthen will returnNO_ORDER_SIDE.- Return type:
OrderSide
- commissions(self) list¶
Return the total commissions generated by the position.
- Return type:
list[Money]
- cross_notional_value(self, Price price, Price quote_price, Price base_price, Currency target_currency) Money¶
Return the current notional value of the position in a cross/target currency.
The quote_price is the Quote/Target conversion price, and base_price is the Base/Target conversion price.
- duration_ns¶
The total open duration in nanoseconds (zero unless closed).
- Returns:
uint64_t
- entry¶
The position entry order side.
- Returns:
OrderSide
- event_count¶
Return the count of order fill events applied to the position.
- Return type:
int
- id¶
The position ID.
- Returns:
PositionId
- info(self) str¶
Return a summary description of the position.
- Return type:
str
- instrument_class¶
The position instrument class.
- Returns:
InstrumentClass
- instrument_id¶
The position instrument ID.
- Returns:
InstrumentId
- is_closed¶
Return whether the position side is
FLAT.- Return type:
bool
- is_inverse¶
If the quantity is expressed in quote currency.
- Returns:
bool
- is_long¶
Return whether the position side is
LONG.- Return type:
bool
- is_open¶
Return whether the position side is not
FLAT.- Return type:
bool
- is_opposite_side(self, OrderSide side) bool¶
Return a value indicating whether the given order side is opposite to the current position side.
- Parameters:
side (OrderSide {
BUY,SELL})- Returns:
True if side is opposite, else False.
- Return type:
bool
- is_short¶
Return whether the position side is
SHORT.- Return type:
bool
- is_spot_currency¶
If the instrument is a spot currency pair.
- Returns:
bool
- last_event¶
Return the last order fill event (if any after purging).
- Return type:
OrderFilled or
None
- last_trade_id¶
Return the last trade match ID for the position (if any after purging).
- Return type:
TradeId or
None
- multiplier¶
The multiplier for the positions instrument.
- Returns:
Quantity
- notional_value(self, Price price, Currency target_currency=None, Price conversion_price=None) Money¶
Return the current notional value of the position, using a reference price for the calculation (e.g., bid, ask, mid, last, or mark).
For a standard (non-inverse) instrument, the notional is returned in the quote currency.
For an inverse instrument, the notional is returned in the base currency, with the calculation scaled by 1 / price.
If target_currency and conversion_price are provided, the notional value will be converted to the target currency.
- Parameters:
price (Price) – The reference price for the calculation. This could be the last, mid, bid, ask, a mark-to-market price, or any other suitably representative value.
target_currency (Currency, optional) – The target currency for conversion.
conversion_price (Price, optional) – The price to use for currency conversion.
- Returns:
Denominated in quote currency for standard instruments, or base currency if inverse.
- Return type:
- opening_order_id¶
The client order ID for the order which opened the position.
- Returns:
ClientOrderId
- peak_qty¶
The peak directional quantity reached by the position.
- Returns:
Quantity
- price_precision¶
The price precision for the position.
- Returns:
uint8
- purge_events_for_order(self, ClientOrderId client_order_id) None¶
Purge all order events for the given client order ID.
After purging, the position is rebuilt from remaining fills. If no fills remain, the position is reset to an empty shell with all history cleared (including timestamps), making it eligible for immediate cache cleanup.
- Parameters:
client_order_id (ClientOrderId) – The client order ID for the events to purge.
- quantity¶
The current open quantity.
- Returns:
Quantity
- quote_currency¶
The position quote currency.
- Returns:
Currency
- realized_pnl¶
The current realized PnL for the position (including commissions).
- Returns:
Money or
None
- realized_return¶
The current realized return for the position.
- Returns:
double
- settlement_currency¶
The position settlement currency (for PnL).
- Returns:
Currency
- side¶
The current position side.
- Returns:
PositionSide
- static side_from_order_side(OrderSide side)¶
Return the position side resulting from the given order side (from
FLAT).- Parameters:
side (OrderSide {
BUY,SELL}) – The order side- Return type:
PositionSide
- signed_decimal_qty(self)¶
Return a signed decimal representation of the position quantity.
If the position is LONG, the value is positive (e.g. Decimal(‘10.25’))
If the position is SHORT, the value is negative (e.g. Decimal(‘-10.25’))
If the position is FLAT, the value is zero (e.g. Decimal(‘0’))
- Return type:
Decimal
- signed_qty¶
The current signed quantity (positive for position side
LONG, negative forSHORT).- Returns:
double
- size_precision¶
The size precision for the position.
- Returns:
uint8
- strategy_id¶
The strategy ID associated with the position.
- Returns:
StrategyId
- to_dict(self) dict¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- total_pnl(self, Price price) Money¶
Return the total PnL for the position, using a reference price for the calculation (e.g., bid, ask, mid, last, or mark).
- trader_id¶
The trader ID associated with the position.
- Returns:
TraderId
- ts_closed¶
UNIX timestamp (nanoseconds) when the position was closed (zero unless closed).
- Returns:
uint64_t
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- ts_last¶
UNIX timestamp (nanoseconds) when the last event occurred.
- Returns:
uint64_t
- ts_opened¶
UNIX timestamp (nanoseconds) when the position was opened.
- Returns:
uint64_t
- unrealized_pnl(self, Price price) Money¶
Return the unrealized PnL for the position, using a reference price for the calculation (e.g., bid, ask, mid, last, or mark).
- venue_order_ids¶
Return the venue order IDs associated with the position.
- Return type:
list[VenueOrderId]
Notes
Guaranteed not to contain duplicate IDs.
- class PositionId¶
Bases:
IdentifierPositionId(str value) -> None
Represents a valid position ID.
- Parameters:
value (str) – The position ID value.
- Raises:
ValueError – If value is not a valid string containing a hyphen.
- class Price¶
Bases:
objectPrice(double value, uint8_t precision) -> None
Represents a price in a market.
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 16 decimals of precision (in high-precision mode).
PRICE_MAX= 17_014_118_346_046PRICE_MIN= -17_014_118_346_046
- Parameters:
value (integer, float, string or Decimal) – The value of the price.
precision (uint8_t) – The precision for the price. Use a precision of 0 for whole numbers (no fractional units).
- Raises:
ValueError – If value is greater than 17_014_118_346_046.
ValueError – If value is less than -17_014_118_346_046.
ValueError – If precision is greater than 16.
OverflowError – If precision is negative (< 0).
- as_decimal(self)¶
Return the value as a built-in Decimal.
- Return type:
Decimal
- as_double(self) double¶
Return the value as a double.
- Return type:
double
- static from_decimal(value: decimal.Decimal) Price¶
Return a price from the given Decimal value.
Handles up to 16 decimals of precision (in high-precision mode).
- Parameters:
value (Decimal) – The Decimal value for the price.
- Return type:
- Raises:
ValueError – If inferred precision is greater than 16.
ValueError – If raw value is outside the valid representable range [PRICE_RAW_MIN, PRICE_RAW_MAX].
OverflowError – If inferred precision is negative (< 0).
Warning
The decimal precision will be inferred from the number of digits following the ‘.’ point (if no point then precision zero).
- static from_int(int value: int) Price¶
Return a price from the given integer value.
A precision of zero will be inferred.
- Parameters:
value (int) – The value for the price.
- Return type:
- static from_raw(int raw: int, uint8_t precision) Price¶
Return a price from the given raw fixed-point integer and precision.
Handles up to 16 decimals of precision (in high-precision mode).
Warning
This method is primarily for internal use and advanced scenarios. Most users should use the standard constructor or
from_str()instead.The raw value must be a valid multiple of the scale factor for the given precision (divisible by 10^(FIXED_PRECISION - precision)). See the documentation for details: https://nautilustrader.io/docs/nightly/concepts/data#fixed-point-precision-and-raw-values
- Parameters:
raw (int) – The raw fixed-point price value. Must be a valid multiple of the scale factor for the given precision.
precision (uint8_t) – The precision for the price. Use a precision of 0 for whole numbers (no fractional units).
- Return type:
- Raises:
ValueError – If precision is greater than 16.
OverflowError – If precision is negative (< 0).
Warning
Small raw values can produce a zero price depending on the precision.
- static from_str(str value) Price¶
Return a price parsed from the given string.
Handles up to 16 decimals of precision (in high-precision mode).
- Parameters:
value (str) – The value to parse.
- Return type:
Warning
The decimal precision will be inferred from the number of digits following the ‘.’ point (if no point then precision zero).
- Raises:
ValueError – If inferred precision is greater than 16.
ValueError – If raw value is outside the valid representable range [PRICE_RAW_MIN, PRICE_RAW_MAX].
OverflowError – If inferred precision is negative (< 0).
- precision¶
int
Return the precision for the price.
- Return type:
uint8_t
- Type:
- raw¶
PriceRaw
Return the raw memory representation of the price value.
- Return type:
int
- Type:
- to_formatted_str(self) str¶
Return the formatted string representation of the price.
- Return type:
str
- class Quantity¶
Bases:
objectQuantity(double value, uint8_t precision) -> None
Represents a quantity with a non-negative value.
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 16 decimals of precision (in high-precision mode).
QUANTITY_MAX= 34_028_236_692_093QUANTITY_MIN= 0
- Parameters:
value (integer, float, string, Decimal) – The value of the quantity.
precision (uint8_t) – The precision for the quantity. Use a precision of 0 for whole numbers (no fractional units).
- Raises:
ValueError – If value is greater than 34_028_236_692_093.
ValueError – If value is negative (< 0).
ValueError – If precision is greater than 16.
OverflowError – If precision is negative (< 0).
- as_decimal(self)¶
Return the value as a built-in Decimal.
- Return type:
Decimal
- as_double(self) double¶
Return the value as a double.
- Return type:
double
- static from_decimal(value: decimal.Decimal) Quantity¶
Return a quantity from the given Decimal value.
Handles up to 16 decimals of precision (in high-precision mode).
- Parameters:
value (Decimal) – The Decimal value for the quantity.
- Return type:
- Raises:
ValueError – If inferred precision is greater than 16.
ValueError – If raw value is outside the valid representable range [0, QUANTITY_RAW_MAX].
OverflowError – If inferred precision is negative (< 0).
Warning
The decimal precision will be inferred from the number of digits following the ‘.’ point (if no point then precision zero).
- static from_int(int value: int) Quantity¶
Return a quantity from the given integer value.
A precision of zero will be inferred.
- Parameters:
value (int) – The value for the quantity.
- Return type:
- static from_raw(int raw: int, uint8_t precision) Quantity¶
Return a quantity from the given raw fixed-point integer and precision.
Handles up to 16 decimals of precision (in high-precision mode).
Warning
This method is primarily for internal use and advanced scenarios. Most users should use the standard constructor,
from_str(), orfrom_int()instead.The raw value must be a valid multiple of the scale factor for the given precision (divisible by 10^(FIXED_PRECISION - precision)). See the documentation for details: https://nautilustrader.io/docs/nightly/concepts/data#fixed-point-precision-and-raw-values
- Parameters:
raw (int) – The raw fixed-point quantity value. Must be a valid multiple of the scale factor for the given precision.
precision (uint8_t) – The precision for the quantity. Use a precision of 0 for whole numbers (no fractional units).
- Return type:
- Raises:
ValueError – If precision is greater than 16.
OverflowError – If precision is negative (< 0).
Warning
Small raw values can produce a zero quantity depending on the precision.
- static from_str(str value) Quantity¶
Return a quantity parsed from the given string.
Handles up to 16 decimals of precision (in high-precision mode).
- Parameters:
value (str) – The value to parse.
- Return type:
- Raises:
ValueError – If inferred precision is greater than 16.
ValueError – If raw value is outside the valid representable range [0, QUANTITY_RAW_MAX].
OverflowError – If inferred precision is negative (< 0).
Warning
The decimal precision will be inferred from the number of digits following the ‘.’ point (if no point then precision zero).
- precision¶
int
Return the precision for the quantity.
- Return type:
uint8_t
- Type:
- raw¶
QuantityRaw
Return the raw memory representation of the quantity value.
- Return type:
int
- Type:
- static raw_to_f64(raw) float¶
- to_formatted_str(self) str¶
Return the formatted string representation of the quantity.
- Return type:
str
- class QuoteTick¶
Bases:
DataQuoteTick(InstrumentId instrument_id, Price bid_price, Price ask_price, Quantity bid_size, Quantity ask_size, uint64_t ts_event, uint64_t ts_init) -> None
Represents a single quote tick in a market.
Contains information about the best top-of-book bid and ask.
- Parameters:
instrument_id (InstrumentId) – The quotes instrument ID.
bid_price (Price) – The top-of-book bid price.
ask_price (Price) – The top-of-book ask price.
bid_size (Quantity) – The top-of-book bid size.
ask_size (Quantity) – The top-of-book ask size.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the tick event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
- Raises:
ValueError – If bid.precision != ask.precision.
ValueError – If bid_size.precision != ask_size.precision.
- ask_price¶
Price
Return the top-of-book ask price.
- Return type:
- Type:
- ask_size¶
Quantity
Return the top-of-book ask size.
- Return type:
- Type:
- bid_price¶
Price
Return the top-of-book bid price.
- Return type:
- Type:
- bid_size¶
Quantity
Return the top-of-book bid size.
- Return type:
- Type:
- static capsule_from_list(list items)¶
- extract_price(self, PriceType price_type) Price¶
Extract the price for the given price type.
- Parameters:
price_type (PriceType) – The price type to extract.
- Return type:
- extract_size(self, PriceType price_type) Quantity¶
Extract the size for the given price type.
- Parameters:
price_type (PriceType) – The price type to extract.
- Return type:
- static from_dict(dict values) QuoteTick¶
Return a quote tick parsed from the given values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_quote) QuoteTick¶
Return a legacy Cython quote tick converted from the given pyo3 Rust object.
- Parameters:
pyo3_quote (nautilus_pyo3.QuoteTick) – The pyo3 Rust quote tick to convert from.
- Return type:
- static from_pyo3_list(list pyo3_quotes) list[QuoteTick]¶
Return legacy Cython quotes converted from the given pyo3 Rust objects.
- Parameters:
pyo3_quotes (list[nautilus_pyo3.QuoteTick]) – The pyo3 Rust quotes to convert from.
- Return type:
list[QuoteTick]
- static from_raw(InstrumentId instrument_id, PriceRaw bid_price_raw, PriceRaw ask_price_raw, uint8_t bid_price_prec, uint8_t ask_price_prec, QuantityRaw bid_size_raw, QuantityRaw ask_size_raw, uint8_t bid_size_prec, uint8_t ask_size_prec, uint64_t ts_event, uint64_t ts_init) QuoteTick¶
Return a quote tick from the given raw values.
Warning
This method is primarily for internal use. Most users should use the regular constructor or
from_dictinstead.All raw price/size values must be valid multiples of the scale factor for the given precision. Invalid raw values will raise a
ValueError. See: https://nautilustrader.io/docs/nightly/concepts/data#fixed-point-precision-and-raw-values- Parameters:
instrument_id (InstrumentId) – The quotes instrument ID.
bid_price_raw (int) – The raw top-of-book bid price (as a scaled fixed-point integer).
ask_price_raw (int) – The raw top-of-book ask price (as a scaled fixed-point integer).
bid_price_prec (uint8_t) – The bid price precision.
ask_price_prec (uint8_t) – The ask price precision.
bid_size_raw (int) – The raw top-of-book bid size (as a scaled fixed-point integer).
ask_size_raw (int) – The raw top-of-book ask size (as a scaled fixed-point integer).
bid_size_prec (uint8_t) – The bid size precision.
ask_size_prec (uint8_t) – The ask size precision.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the tick event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
- Return type:
- Raises:
ValueError – If bid_price_prec != ask_price_prec.
ValueError – If bid_size_prec != ask_size_prec.
ValueError – If any raw price/size value is invalid for the given precision.
- static from_raw_arrays_to_list(InstrumentId instrument_id: InstrumentId, int price_prec: int, int size_prec: int, bid_prices_raw: np.ndarray, ask_prices_raw: np.ndarray, bid_sizes_raw: np.ndarray, ask_sizes_raw: np.ndarray, ts_events: np.ndarray, ts_inits: np.ndarray) list[QuoteTick]¶
- instrument_id¶
InstrumentId
Return the tick instrument ID.
- Return type:
- Type:
- static to_dict(QuoteTick obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- to_pyo3(self) nautilus_pyo3.QuoteTick¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.QuoteTick
- static to_pyo3_list(list quotes) list[nautilus_pyo3.QuoteTick]¶
Return pyo3 Rust quotes converted from the given legacy Cython objects.
- Parameters:
quotes (list[QuoteTick]) – The legacy Cython quotes to convert from.
- Return type:
list[nautilus_pyo3.QuoteTick]
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- class StrategyId¶
Bases:
IdentifierStrategyId(str value) -> None
Represents a valid strategy ID.
Must be correctly formatted with two valid strings either side of a hyphen. It is expected a strategy ID is the class name of the strategy, with an order ID tag number separated by a hyphen.
Example: “EMACross-001”.
The reason for the numerical component of the ID is so that order and position IDs do not collide with those from another strategy within the node instance.
- Parameters:
value (str) – The strategy ID value.
- Raises:
ValueError – If value is not a valid string containing a hyphen.
Warning
The name and tag combination must be unique at the trader level.
- get_tag(self) str¶
Return the order ID tag value for this ID.
- Return type:
str
- is_external(self) bool¶
If the strategy ID is the global ‘external’ strategy. This represents the strategy for all orders interacting with this instance of the system which did not originate from any strategy being managed by the system.
- Return type:
bool
- class Symbol¶
Bases:
IdentifierSymbol(str value) -> None
Represents a valid ticker symbol ID for a tradable instrument.
- Parameters:
value (str) – The ticker symbol ID value.
- Raises:
ValueError – If value is not a valid string.
Warning
The ID value must be unique for a trading venue.
References
- is_composite(self) bool¶
Returns true if the symbol string contains a period (‘.’).
- Return type:
str
- root(self) str¶
Return 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.
- Return type:
str
- topic(self) str¶
Return 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.
- Return type:
str
- class TradeId¶
Bases:
IdentifierTradeId(str value) -> None
Represents a valid trade match ID (assigned by a trading venue).
Maximum length is 36 characters. Can correspond to the TradeID <1003> field of the FIX protocol.
The unique ID assigned to the trade entity once it is received or matched by the exchange or central counterparty.
- Parameters:
value (str) – The trade match ID value.
- Raises:
ValueError – If value is not a valid string.
ValueError – If value length exceeds maximum 36 characters.
- class TradeTick¶
Bases:
DataTradeTick(InstrumentId instrument_id, Price price, Quantity size, AggressorSide aggressor_side, TradeId trade_id, uint64_t ts_event, uint64_t ts_init) -> None
Represents a single trade tick in a market.
Contains information about a single unique trade which matched buyer and seller counterparties.
- Parameters:
instrument_id (InstrumentId) – The trade instrument ID.
price (Price) – The traded price.
size (Quantity) – The traded size.
aggressor_side (AggressorSide) – The trade aggressor side.
trade_id (TradeId) – The trade match ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the tick event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
- Raises:
ValueError – If trade_id is not a valid string.
ValueError – If size is not positive (> 0).
- aggressor_side¶
AggressorSide
Return the ticks aggressor side.
- Return type:
AggressorSide
- Type:
- static capsule_from_list(items)¶
- static from_dict(dict values) TradeTick¶
Return a trade tick from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- static from_pyo3(pyo3_trade) TradeTick¶
Return a legacy Cython trade tick converted from the given pyo3 Rust object.
- Parameters:
pyo3_trade (nautilus_pyo3.TradeTick) – The pyo3 Rust trade tick to convert from.
- Return type:
- static from_pyo3_list(list pyo3_trades) list[TradeTick]¶
Return legacy Cython trades converted from the given pyo3 Rust objects.
- Parameters:
pyo3_trades (list[nautilus_pyo3.TradeTick]) – The pyo3 Rust trades to convert from.
- Return type:
list[TradeTick]
- static from_raw(InstrumentId instrument_id, PriceRaw price_raw, uint8_t price_prec, QuantityRaw size_raw, uint8_t size_prec, AggressorSide aggressor_side, TradeId trade_id, uint64_t ts_event, uint64_t ts_init) TradeTick¶
Return a trade tick from the given raw values.
Warning
This method is primarily for internal use. Most users should use the regular constructor or
from_dictinstead.All raw price/size values must be valid multiples of the scale factor for the given precision. Invalid raw values will raise a
ValueError. See: https://nautilustrader.io/docs/nightly/concepts/data#fixed-point-precision-and-raw-values- Parameters:
instrument_id (InstrumentId) – The trade instrument ID.
price_raw (int) – The traded raw price (as a scaled fixed-point integer).
price_prec (uint8_t) – The traded price precision.
size_raw (int) – The traded raw size (as a scaled fixed-point integer).
size_prec (uint8_t) – The traded size precision.
aggressor_side (AggressorSide) – The trade aggressor side.
trade_id (TradeId) – The trade match ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the tick event occurred.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the data object was initialized.
- Return type:
- Raises:
ValueError – If any raw price/size value is invalid for the given precision.
- static from_raw_arrays_to_list(InstrumentId instrument_id, uint8_t price_prec, uint8_t size_prec, double[: ] prices_raw, double[: ] sizes_raw, uint8_t[: ] aggressor_sides, list trade_ids, uint64_t[: ] ts_events, uint64_t[: ] ts_inits) list[TradeTick]¶
- instrument_id¶
InstrumentId
Return the ticks instrument ID.
- Return type:
- Type:
- price¶
Price
Return the ticks price.
- Return type:
- Type:
- size¶
Quantity
Return the ticks size.
- Return type:
- Type:
- static to_dict(TradeTick obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- to_pyo3(self) nautilus_pyo3.TradeTick¶
Return a pyo3 object from this legacy Cython instance.
- Return type:
nautilus_pyo3.TradeTick
- static to_pyo3_list(list trades) list[nautilus_pyo3.TradeTick]¶
Return pyo3 Rust trades converted from the given legacy Cython objects.
- Parameters:
ticks (list[TradeTick]) – The legacy Cython Rust trades to convert from.
- Return type:
list[nautilus_pyo3.TradeTick]
- trade_id¶
InstrumentId
Return the ticks trade match ID.
- Return type:
- Type:
- ts_event¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- ts_init¶
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- Type:
- class TraderId¶
Bases:
IdentifierTraderId(str value) -> None
Represents a valid trader ID.
Must be correctly formatted with two valid strings either side of a hyphen. It is expected a trader ID is the abbreviated name of the trader with an order ID tag number separated by a hyphen.
Example: “TESTER-001”.
The reason for the numerical component of the ID is so that order and position IDs do not collide with those from another node instance.
- Parameters:
value (str) – The trader ID value.
- Raises:
ValueError – If value is not a valid string containing a hyphen.
Warning
The name and tag combination ID value must be unique at the firm level.
- get_tag(self) str¶
Return the order ID tag value for this ID.
- Return type:
str
- class Venue¶
Bases:
IdentifierVenue(str name) -> None
Represents a valid trading venue ID.
- Parameters:
name (str) – The venue ID value.
- Raises:
ValueError – If name is not a valid string.
- static from_code(str code)¶
Return the venue with the given code from the built-in internal map (if found).
Currency only supports CME Globex exchange ISO 10383 MIC codes.
- Parameters:
code (str) – The code of the venue.
- Return type:
Venue or
None
- is_synthetic(self) bool¶
Return whether the venue is synthetic (‘SYNTH’).
- Return type:
bool
- class VenueOrderId¶
Bases:
IdentifierVenueOrderId(str value) -> None
Represents a valid venue order ID (assigned by a trading venue).
- Parameters:
value (str) – The venue assigned order ID value.
- Raises:
ValueError – If value is not a valid string.