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: object
AccountBalance(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: AccountBalance
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: AccountBalance
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: Identifier
AccountId(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: Data
Bar(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: BarType
- Type: Bar.bar_type
close
Price
Return the close price of the bar.
- Return type: Price
- Type: Bar.close
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: Bar
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: Bar
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
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]
high
Price
Return the high price of the bar.
- Return type: Price
- Type: Bar.high
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
low
Price
Return the low price of the bar.
- Return type: Price
- Type: Bar.low
open
Price
Return the open price of the bar.
- Return type: Price
- Type: Bar.open
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: Bar.ts_event
ts_init
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type: int
- Type: Bar.ts_init
volume
Quantity
Return the volume of the bar.
- Return type: Quantity
- Type: Bar.volume
class BarSpecification
Bases: object
BarSpecification(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)
- step (int) – The step size for bar aggregation. Must be positive.
- Raises: ValueError – If step is not valid or if invalid aggregation/price_type combinations
aggregation
BarAggregation
Return the aggregation for the specification.
- Return type: BarAggregation
- Type: BarSpecification.aggregation
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 occurVOLUME_RUNS
: Bars created when runs of volume patterns occurVALUE_RUNS
: Bars created when runs of value patterns occur
Runs 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
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 thresholdVOLUME
: Bars created after N units of volume are tradedVOLUME_IMBALANCE
: Bars created when volume imbalance reaches thresholdVALUE
: Bars created after N units of notional value are tradedVALUE_IMBALANCE
: Bars created when value imbalance reaches threshold
This 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
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 millisecondsSECOND
: Bars created every N secondsMINUTE
: Bars created every N minutesHOUR
: Bars created every N hoursDAY
: 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
static from_str(str value) → BarSpecification
Return a bar specification parsed from the given string.
-
Parameters: value (str) – The bar specification string to parse.
-
Return type: BarSpecification
-
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.
-
Return type: BarSpecification
-
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 MONTH or YEAR (since months and years have variable lengths 28-31 days or 365-366 days, making fixed nanosecond conversion impossible). If the aggregation is not a time-based aggregation.
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 clusteringVALUE_RUNS
: Bars based on runs of notional value patterns
A “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)
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 imbalancesVOLUME_IMBALANCE
: Bars based on cumulative volume imbalancesVALUE_IMBALANCE
: Bars based on cumulative value flow imbalances
Threshold-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_aggregated
: Static method for threshold aggregation checking
is_time_aggregated
: Check for time-based aggregation
is_information_aggregated
: Check for information-based aggregation
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_aggregated
: Check for threshold-based aggregation
is_information_aggregated
: Check for information-based aggregation
price_type
PriceType
Return the price type for the specification.
- Return type: PriceType
- Type: BarSpecification.price_type
step
int
Return the step size for the specification.
- Return type: int
- Type: BarSpecification.step
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: BarSpecification.timedelta
class BarType
Bases: object
BarType(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
INTERNAL
the DataEngine will subscribe to the necessary ticks and aggregate bars accordingly. Else ifEXTERNAL
then bars will be subscribed to directly from the venue / data provider.
aggregation_source
AggregationSource
Return the aggregation source for the bar type.
- Return type: AggregationSource
- Type: BarType.aggregation_source
composite(self) → BarType
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: BarType
- Raises: ValueError – If value is not a valid string.
instrument_id
InstrumentId
Return the instrument ID for the bar type.
- Return type: InstrumentId
- Type: BarType.instrument_id
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: BarSpecification
- Type: BarType.spec
standard(self) → BarType
class BookLevel
Bases: object
Represents 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
orders(self) → list
Return the orders for the level.
- Return type: list[BookOrder]
price
Price
Return the price for the level.
- Return type: Price
- Type: BookLevel.price
side
OrderSide
Return the side for the level.
- Return type: OrderSide
- Type: BookLevel.side
size(self) → double
Return the size at this level.
- Return type: double
class BookOrder
Bases: object
BookOrder(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: BookOrder
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 an book order from the given 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.
- side (OrderSide {
- Return type: BookOrder
order_id
uint64_t
Return the book orders side.
- Return type: uint64_t
- Type: BookOrder.order_id
price
Price
Return the book orders price.
- Return type: Price
- Type: BookOrder.price
side
OrderSide
Return the book orders side.
- Return type: OrderSide
- Type: BookOrder.side
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: Quantity
- Type: BookOrder.size
static to_dict(BookOrder obj)
Return a dictionary representation of this object.
- Return type: dict[str, object]
class ClientId
Bases: Identifier
ClientId(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: Identifier
ClientOrderId(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: Identifier
ComponentId(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: object
Currency(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.code
currency_type
CurrencyType
Return the currency type.
- Return type: CurrencyType
- Type: Currency.currency_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: Currency.iso4217
name
str
Return the currency name.
- Return type: str
- Type: Currency.name
precision
int
Return the currency decimal precision.
- Return type: uint8
- Type: Currency.precision
static register(Currency currency, bool overwrite=False)
Register the given currency.
Will override the internal currency map.
- Parameters:
- currency (Currency) – The currency to register
- overwrite (bool) – If the currency in the internal currency map should be overwritten.
class CustomData
Bases: Data
CustomData(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: CustomData.ts_event
ts_init
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type: int
- Type: CustomData.ts_init
class DataType
Bases: object
DataType(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.