Betfair¶
Betfair sports betting exchange integration adapter.
This subpackage provides an instrument provider, data and execution clients, configurations, data types and constants for connecting to and interacting with Betfairs’s API.
For convenience, the most commonly used symbols are re-exported at the
subpackage’s top level, so downstream code can simply import from
nautilus_trader.adapters.betfair.
- class BetfairDataClientConfig¶
Bases:
LiveDataClientConfigConfiguration for
BetfairDataClientinstances.- Parameters:
account_currency (str) – The currency for the Betfair account.
username (str, optional) – The Betfair account username.
password (str, optional) – The Betfair account password.
app_key (str, optional) – The Betfair application key.
certs_dir (str, optional) – The local directory that contains the Betfair SSL certificates.
instrument_config (BetfairInstrumentProviderConfig, None) – The Betfair instrument provider config.
subscription_delay_secs (PositiveInt, default 3) – The delay (seconds) before sending the initial subscription message.
keep_alive_secs (PositiveInt, default 36_000 (10 hours)) – The keep alive interval (seconds) for the HTTP client.
subscribe_race_data (bool, default False) – If True, sends a
raceSubscriptionon the stream to receive Race Change Messages (RCM) with live GPS tracking data (Total Performance Data).stream_conflate_ms (PositiveInt, optional) – The Betfair data stream conflation setting. Default of None means no explicit value is set for the conflation interval. Betfair interprets this as using its default behaviour for conflation. The default typically applies conflation, so you need to ensure stream_conflate_ms=0 is explicitly set to guarantee no conflation.
stream_heartbeat_ms (PositiveInt, default 5000) – The Betfair stream heartbeat interval (milliseconds). Betfair will send heartbeat messages at this interval during quiet periods, preventing silent connection drops. Valid range is 500-5000. Set to None to omit.
proxy_url (str, optional) – The proxy URL for HTTP requests.
- account_currency: str¶
- username: str | None¶
- password: str | None¶
- app_key: str | None¶
- certs_dir: str | None¶
- instrument_config: BetfairInstrumentProviderConfig | None¶
- subscription_delay_secs: Annotated[int, msgspec.Meta(gt=0)] | None¶
- keep_alive_secs: Annotated[int, msgspec.Meta(gt=0)]¶
- subscribe_race_data: bool¶
- stream_conflate_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- stream_heartbeat_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- proxy_url: str | None¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- handle_revised_bars: bool¶
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- instrument_provider: InstrumentProviderConfig¶
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- routing: RoutingConfig¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class BetfairExecClientConfig¶
Bases:
LiveExecClientConfigConfiguration for
BetfairExecClientinstances.- Parameters:
account_currency (str) – The currency for the Betfair account.
username (str, optional) – The Betfair account username.
password (str, optional) – The Betfair account password.
app_key (str, optional) – The Betfair application key.
certs_dir (str, optional) – The local directory that contains the Betfair SSL certificates.
instrument_config (BetfairInstrumentProviderConfig, None) – The Betfair instrument provider config.
calculate_account_state (bool, default True) – If the Betfair account state should be calculated from events.
request_account_state_secs (NonNegativeInt, default 300 (5 minutes)) – The request interval (seconds) for account state checks. If zero, then will not request account state from Betfair.
reconcile_market_ids_only (bool, default False) – If True, reconciliation only requests orders matching the market IDs listed in the instrument_config. If False, all orders are reconciled.
stream_market_ids_filter (list[str], optional) – If provided, only process order stream updates for these market IDs. Updates for other markets are silently skipped. Useful to reduce warning spam when sharing a Betfair account across multiple trading nodes.
ignore_external_orders (bool, default False) – If True, orders received over the stream that aren’t found in the cache will be silently ignored. This is useful when multiple trading nodes share the same Betfair account across different markets.
use_market_version (bool, default False) – If True, automatically attach the latest market version to placeOrders and replaceOrders requests. When the market version has advanced beyond the version sent with the order, Betfair will lapse the bet rather than matching it against a changed book. This provides price protection by preventing orders from being matched when the market has moved.
order_request_rate_per_second (PositiveInt, default 20) – The rate limit (requests/second) for order endpoints (placeOrders, replaceOrders, cancelOrders). Order endpoints use a separate rate limit bucket from general API endpoints (5/sec) so order placement is not throttled by account state polling or reconciliation queries.
stream_heartbeat_ms (PositiveInt, default 5000) – The Betfair order stream heartbeat interval (milliseconds). Betfair will send heartbeat messages at this interval during quiet periods, preventing silent connection drops. Valid range is 500-5000. Set to None to omit.
proxy_url (str, optional) – The proxy URL for HTTP requests.
- account_currency: str¶
- username: str | None¶
- password: str | None¶
- app_key: str | None¶
- certs_dir: str | None¶
- instrument_config: BetfairInstrumentProviderConfig | None¶
- calculate_account_state: bool¶
- request_account_state_secs: Annotated[int, msgspec.Meta(ge=0)]¶
- reconcile_market_ids_only: bool¶
- stream_market_ids_filter: list[str] | None¶
- ignore_external_orders: bool¶
- use_market_version: bool¶
- order_request_rate_per_second: Annotated[int, msgspec.Meta(gt=0)]¶
- stream_heartbeat_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- proxy_url: str | None¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- instrument_provider: InstrumentProviderConfig¶
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- routing: RoutingConfig¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class BetfairInstrumentProvider¶
Bases:
InstrumentProviderProvides a means of loading BettingInstruments from the Betfair APIClient.
- Parameters:
client (BetfairHttpClient) – The Betfair HTTP client for the provider.
config (InstrumentProviderConfig) – The configuration for the provider.
- async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
The default implementation calls
load_all_async(since many venue APIs only support bulk fetches) and then filters the provider to retain only the requested instruments plus any previously loaded ones.Subclasses with per-instrument fetch capability should override this method.
- Parameters:
instrument_ids (list[InstrumentId]) – The instrument IDs to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- async load_async(instrument_id: InstrumentId, filters: dict | None = None)¶
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
The default implementation delegates to
load_ids_async. Subclasses with per-instrument fetch capability should override this method.- Parameters:
instrument_id (InstrumentId) – The instrument ID to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- async load_all_async(filters: dict | None = None)¶
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
- async get_account_currency() str¶
- add(instrument: Instrument) None¶
Add the given instrument to the provider.
- Parameters:
instrument (Instrument) – The instrument to add.
- add_bulk(instruments: list[Instrument]) None¶
Add the given instruments bulk to the provider.
- Parameters:
instruments (list[Instrument]) – The instruments to add.
- add_currency(currency: Currency) None¶
Add the given currency to the provider.
- Parameters:
currency (Currency) – The currency to add.
- property count: int¶
Return the count of instruments held by the provider.
- Return type:
int
- currencies() dict[str, Currency]¶
Return all currencies held by the instrument provider.
- Return type:
dict[str, Currency]
- currency(code: str) Currency | None¶
Return the currency with the given code (if found).
- Parameters:
code (str) – The currency code.
- Return type:
Currency or
None- Raises:
ValueError – If code is not a valid string.
- find(instrument_id: InstrumentId) Instrument | None¶
Return the instrument for the given instrument ID (if found).
- Parameters:
instrument_id (InstrumentId) – The ID for the instrument
- Return type:
Instrument or
None
- get_all() dict[InstrumentId, Instrument]¶
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type:
dict[InstrumentId, Instrument]
- async initialize(reload: bool = False) None¶
Initialize the instrument provider.
- Parameters:
reload (bool, default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
- list_all() list[Instrument]¶
Return all loaded instruments.
- Return type:
list[Instrument]
- load(instrument_id: InstrumentId, filters: dict | None = None) None¶
Load the instrument for the given ID into the provider, optionally applying the given filters.
- Parameters:
instrument_id (InstrumentId) – The instrument ID to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- load_all(filters: dict | None = None) None¶
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters:
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
instrument_ids (list[InstrumentId]) – The instrument IDs to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- class BetfairInstrumentProviderConfig¶
Bases:
InstrumentProviderConfigConfiguration for
BetfairInstrumentProviderinstances.- Parameters:
account_currency (str) – The Betfair account currency.
default_min_notional (PositiveFloat, optional) – The default minimum notional value for instrument definitions (in account currency).
event_type_ids (list[int], optional) – The event type IDs to filter for.
event_ids (list[int], optional) – The event IDs to filter for.
market_ids (list[str], optional) – The market IDs to filter for.
country_codes (list[str], optional) – The country codes to filter for.
market_types (list[str], optional) – The market types to filter for.
min_market_start_time (pd.Timestamp, optional) – The minimum market start time (UTC) to filter from (date granularity only).
max_market_start_time (pd.Timestamp, optional) – The maximum market start time (UTC) to filter to (date granularity only).
Notes
For each filter parameter, if not provided (None), then no filtering is done on that attribute.
- account_currency: str¶
- default_min_notional: Annotated[float, msgspec.Meta(gt=0.0)] | None¶
- event_type_ids: list[int] | None¶
- event_ids: list[int] | None¶
- market_ids: list[str] | None¶
- country_codes: list[str] | None¶
- market_types: list[str] | None¶
- event_type_names: list[str] | None¶
- min_market_start_time: Timestamp | None¶
- max_market_start_time: Timestamp | None¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- filter_callable: str | None¶
- filters: dict[str, Any] | None¶
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- load_all: bool¶
- load_ids: frozenset[InstrumentId] | None¶
- log_warnings: bool¶
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- use_gamma_markets: bool¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class BetfairLiveDataClientFactory¶
Bases:
LiveDataClientFactoryProvides a Betfair live data client factory.
- static create(loop: AbstractEventLoop, name: str, config: BetfairDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock)¶
Create a new Betfair data client.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
name (str) – The custom client ID.
config (dict[str, Any]) – The configuration dictionary.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the client.
- Return type:
- class BetfairLiveExecClientFactory¶
Bases:
LiveExecClientFactoryProvides data and execution clients for Betfair.
- static create(loop: AbstractEventLoop, name: str, config: BetfairExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock)¶
Create a new Betfair execution client.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
name (str) – The custom client ID.
config (dict[str, Any]) – The configuration for the client.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the client.
- Return type:
- class BetfairParser¶
Bases:
objectStateful parser that keeps market definition.
- parse(mcm: MCM, ts_init: int | None = None, min_notional: Money | None = None) list[InstrumentStatus | InstrumentClose | OrderBookDeltas | TradeTick | BetfairTicker | BSPOrderBookDelta | BetfairStartingPrice]¶
- get_cached_betfair_client(username: str | None = None, password: str | None = None, app_key: str | None = None, proxy_url: str | None = None, request_rate_per_second: int = 5, order_request_rate_per_second: int = 20) BetfairHttpClient¶
Cache and return a Betfair HTTP client with the given credentials.
If a cached client with matching parameters already exists, then that cached client will be returned. The cache key includes credentials and rate limit settings. With default rate limits, data and execution factories share a single client instance.
- Parameters:
username (str, optional) – The API username for the client. If None then will source from the BETFAIR_USERNAME env var.
password (str, optional) – The API password for the client. If None then will source from the BETFAIR_PASSWORD env var.
app_key (str, optional) – The API application key for the client. If None then will source from the BETFAIR_APP_KEY env var.
proxy_url (str, optional) – The proxy URL for HTTP requests.
request_rate_per_second (int, default 5) – The rate limit (requests/second) for general API endpoints.
order_request_rate_per_second (int, default 20) – The rate limit (requests/second) for order endpoints (placeOrders, replaceOrders, cancelOrders).
- Return type:
- get_cached_betfair_instrument_provider(client: BetfairHttpClient, config: BetfairInstrumentProviderConfig) BetfairInstrumentProvider¶
Cache and return a BetfairInstrumentProvider.
If a cached provider already exists, then that cached provider will be returned.
- Parameters:
client (BinanceHttpClient) – The client for the instrument provider.
config (BetfairInstrumentProviderConfig) – The config for the instrument provider.
- Return type:
Client¶
- class BetfairHttpClient¶
Bases:
objectProvides a HTTP client for Betfair.
- Parameters:
username (str) – The Betfair account username.
password (str) – The Betfair account password.
app_key (str) – The Betfair application key.
proxy_url (str, optional) – The proxy URL for HTTP requests.
ratelimiter_default_quota (Quota, optional) – The default rate limiter quota for requests.
ratelimiter_keyed_quotas (list[tuple[str, Quota]], optional) – Per-key rate limiter quotas (e.g. separate quota for order endpoints).
- property session_token: str | None¶
- update_headers(login_resp: LoginResponse) None¶
- reset_headers() None¶
- async connect() None¶
- async reconnect() None¶
- async disconnect() None¶
- async keep_alive() None¶
Renew authentication.
List the tree (navigation) of all betfair markets.
- async list_market_catalogue(filter_: MarketFilter, market_projection: list[MarketProjection] | None = None, sort: MarketSort | None = None, max_results: int = 1000, locale: str | None = None) list[MarketCatalogue]¶
Return specific data about markets.
- async get_account_details() AccountDetailsResponse¶
- async get_account_funds(wallet: str | None = None) AccountFundsResponse¶
- async place_orders(request: PlaceOrders) PlaceExecutionReport¶
- async replace_orders(request: ReplaceOrders) ReplaceExecutionReport¶
- async cancel_orders(request: CancelOrders) CancelExecutionReport¶
- async list_current_orders(bet_ids: set[Annotated[int, msgspec.Meta(ge=0, title='IDType', description='integer data, but defined and encoded as string'), msgspec.Meta(title='BetId')]] | None = None, market_ids: set[str] | None = None, order_projection: OrderProjection | None = None, customer_order_refs: set[Annotated[str, msgspec.Meta(title='CustomerOrderRef')]] | None = None, customer_strategy_refs: set[Annotated[str, msgspec.Meta(title='CustomerStrategyRef')]] | None = None, date_range: TimeRange | None = None, order_by: OrderBy | None = None, sort_dir: SortDir | None = None, from_record: int | None = None, record_count: int | None = None, include_item_description: bool | None = None) list[CurrentOrderSummary]¶
- async list_cleared_orders(bet_status: BetStatus, event_type_ids: set[Annotated[int, msgspec.Meta(ge=0, title='IDType', description='integer data, but defined and encoded as string'), msgspec.Meta(title='EventTypeId')]] | None = None, event_ids: set[Annotated[int, msgspec.Meta(ge=0, title='IDType', description='integer data, but defined and encoded as string'), msgspec.Meta(title='EventId')]] | None = None, market_ids: set[Annotated[str, msgspec.Meta(title='MarketId')]] | None = None, runner_ids: set[RunnerId] | None = None, bet_ids: set[Annotated[int, msgspec.Meta(ge=0, title='IDType', description='integer data, but defined and encoded as string'), msgspec.Meta(title='BetId')]] | None = None, customer_order_refs: set[Annotated[str, msgspec.Meta(title='CustomerOrderRef')]] | None = None, customer_strategy_refs: set[Annotated[str, msgspec.Meta(title='CustomerStrategyRef')]] | None = None, side: Side | None = None, settled_date_range: TimeRange | None = None, group_by: GroupBy | None = None, include_item_description: bool | None = None, locale: str | None = None, from_record: int | None = None, record_count: int | None = None) list[ClearedOrderSummary]¶
Common¶
- class OrderSideParser¶
Bases:
object- BACKS = (Side.BACK, 'B')¶
- LAYS = (Side.LAY, 'L')¶
- classmethod to_nautilus(side: Side | str) OrderSide¶
- static to_betfair(order_side: OrderSide) Side¶
- is_session_error(error: BetfairError) bool¶
Check if a BetfairError is a session expiry error.
Session errors (NO_SESSION, INVALID_SESSION_INFORMATION) are expected to occur every 12-24 hours and should trigger automatic reconnection.
This also handles errors from betfair-parser when it can’t parse undocumented error codes like -32099 (JSON-RPC server errors).
- Parameters:
error (BetfairError) – The error to check.
- Returns:
True if the error is a session expiry error.
- Return type:
bool
- is_rate_limit_error(error: BetfairError) bool¶
Check if a BetfairError is a rate limit error.
- Parameters:
error (BetfairError) – The error to check.
- Returns:
True if the error is a rate limit error.
- Return type:
bool
Config¶
- class BetfairDataClientConfig¶
Bases:
LiveDataClientConfigConfiguration for
BetfairDataClientinstances.- Parameters:
account_currency (str) – The currency for the Betfair account.
username (str, optional) – The Betfair account username.
password (str, optional) – The Betfair account password.
app_key (str, optional) – The Betfair application key.
certs_dir (str, optional) – The local directory that contains the Betfair SSL certificates.
instrument_config (BetfairInstrumentProviderConfig, None) – The Betfair instrument provider config.
subscription_delay_secs (PositiveInt, default 3) – The delay (seconds) before sending the initial subscription message.
keep_alive_secs (PositiveInt, default 36_000 (10 hours)) – The keep alive interval (seconds) for the HTTP client.
subscribe_race_data (bool, default False) – If True, sends a
raceSubscriptionon the stream to receive Race Change Messages (RCM) with live GPS tracking data (Total Performance Data).stream_conflate_ms (PositiveInt, optional) – The Betfair data stream conflation setting. Default of None means no explicit value is set for the conflation interval. Betfair interprets this as using its default behaviour for conflation. The default typically applies conflation, so you need to ensure stream_conflate_ms=0 is explicitly set to guarantee no conflation.
stream_heartbeat_ms (PositiveInt, default 5000) – The Betfair stream heartbeat interval (milliseconds). Betfair will send heartbeat messages at this interval during quiet periods, preventing silent connection drops. Valid range is 500-5000. Set to None to omit.
proxy_url (str, optional) – The proxy URL for HTTP requests.
- account_currency: str¶
- username: str | None¶
- password: str | None¶
- app_key: str | None¶
- certs_dir: str | None¶
- instrument_config: BetfairInstrumentProviderConfig | None¶
- subscription_delay_secs: Annotated[int, msgspec.Meta(gt=0)] | None¶
- keep_alive_secs: Annotated[int, msgspec.Meta(gt=0)]¶
- subscribe_race_data: bool¶
- stream_conflate_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- stream_heartbeat_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- proxy_url: str | None¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- handle_revised_bars: bool¶
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- instrument_provider: InstrumentProviderConfig¶
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- routing: RoutingConfig¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class BetfairExecClientConfig¶
Bases:
LiveExecClientConfigConfiguration for
BetfairExecClientinstances.- Parameters:
account_currency (str) – The currency for the Betfair account.
username (str, optional) – The Betfair account username.
password (str, optional) – The Betfair account password.
app_key (str, optional) – The Betfair application key.
certs_dir (str, optional) – The local directory that contains the Betfair SSL certificates.
instrument_config (BetfairInstrumentProviderConfig, None) – The Betfair instrument provider config.
calculate_account_state (bool, default True) – If the Betfair account state should be calculated from events.
request_account_state_secs (NonNegativeInt, default 300 (5 minutes)) – The request interval (seconds) for account state checks. If zero, then will not request account state from Betfair.
reconcile_market_ids_only (bool, default False) – If True, reconciliation only requests orders matching the market IDs listed in the instrument_config. If False, all orders are reconciled.
stream_market_ids_filter (list[str], optional) – If provided, only process order stream updates for these market IDs. Updates for other markets are silently skipped. Useful to reduce warning spam when sharing a Betfair account across multiple trading nodes.
ignore_external_orders (bool, default False) – If True, orders received over the stream that aren’t found in the cache will be silently ignored. This is useful when multiple trading nodes share the same Betfair account across different markets.
use_market_version (bool, default False) – If True, automatically attach the latest market version to placeOrders and replaceOrders requests. When the market version has advanced beyond the version sent with the order, Betfair will lapse the bet rather than matching it against a changed book. This provides price protection by preventing orders from being matched when the market has moved.
order_request_rate_per_second (PositiveInt, default 20) – The rate limit (requests/second) for order endpoints (placeOrders, replaceOrders, cancelOrders). Order endpoints use a separate rate limit bucket from general API endpoints (5/sec) so order placement is not throttled by account state polling or reconciliation queries.
stream_heartbeat_ms (PositiveInt, default 5000) – The Betfair order stream heartbeat interval (milliseconds). Betfair will send heartbeat messages at this interval during quiet periods, preventing silent connection drops. Valid range is 500-5000. Set to None to omit.
proxy_url (str, optional) – The proxy URL for HTTP requests.
- account_currency: str¶
- username: str | None¶
- password: str | None¶
- app_key: str | None¶
- certs_dir: str | None¶
- instrument_config: BetfairInstrumentProviderConfig | None¶
- calculate_account_state: bool¶
- request_account_state_secs: Annotated[int, msgspec.Meta(ge=0)]¶
- reconcile_market_ids_only: bool¶
- stream_market_ids_filter: list[str] | None¶
- ignore_external_orders: bool¶
- use_market_version: bool¶
- order_request_rate_per_second: Annotated[int, msgspec.Meta(gt=0)]¶
- stream_heartbeat_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- proxy_url: str | None¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- instrument_provider: InstrumentProviderConfig¶
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- routing: RoutingConfig¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
Data¶
- class BetfairDataClient¶
Bases:
LiveMarketDataClientProvides a data client for the Betfair API.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
client (BetfairClient) – The Betfair HttpClient
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the client.
instrument_provider (BetfairInstrumentProvider, optional) – The instrument provider.
config (BetfairDataClientConfig) – The configuration for the client.
- property instrument_provider: BetfairInstrumentProvider¶
Return the instrument provider for the client.
- Return type:
- async stream_subscribe()¶
- on_market_update(raw: bytes) None¶
Handle an update from the market stream socket.
- on_race_stream_update(raw: bytes) None¶
Handle an update from the race stream socket.
Isolated from market stream status handling so race failures do not trigger reconnection of the market stream.
- async cancel_pending_tasks(timeout_secs: float = 5.0) None¶
Cancel all pending tasks and await their cancellation.
- Parameters:
timeout_secs (float, default 5.0) – The timeout in seconds to wait for tasks to cancel.
- connect() None¶
Connect the client.
- create_task(coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = <LogColor.NORMAL: 0>) Task | None¶
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
coro (Coroutine) – The coroutine to run.
log_msg (str, optional) – The log message for the task.
actions (Callable, optional) – The actions callback to run when the coroutine is done.
success_msg (str, optional) – The log message to write on actions success.
success_color (LogColor, default
NORMAL) – The log message color for actions success.
- Return type:
asyncio.Task
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- disconnect() None¶
Disconnect the client.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- id¶
The components ID.
- Returns:
ComponentId
- is_connected¶
If the client is connected.
- Returns:
bool
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- request(self, RequestData request) void¶
Request data for the given data type.
- Parameters:
request (RequestData) – The message for the data request.
- request_bars(self, RequestBars request) void¶
Request historical Bar data. To load historical data from a catalog, you can pass a list[DataCatalogConfig] to the TradingNodeConfig or the BacktestEngineConfig.
- Parameters:
request (RequestBars) – The message for the data request.
- request_funding_rates(self, RequestFundingRates request) void¶
Request historical FundingRateUpdate data.
- Parameters:
request (RequestFundingRates) – The message for the data request.
- request_instrument(self, RequestInstrument request) void¶
Request Instrument data for the given instrument ID.
- Parameters:
request (RequestInstrument) – The message for the data request.
- request_instruments(self, RequestInstruments request) void¶
Request all Instrument data for the given venue.
- Parameters:
request (RequestInstruments) – The message for the data request.
- request_order_book_deltas(self, RequestOrderBookDeltas request) void¶
Request historical OrderBookDeltas data.
- Parameters:
request (RequestOrderBookDeltas) – The message for the data request.
- request_order_book_depth(request: RequestOrderBookDepth) None¶
- request_order_book_snapshot(self, RequestOrderBookSnapshot request) void¶
Request order book snapshot data.
- Parameters:
request (RequestOrderBookSnapshot) – The message for the data request.
- request_quote_ticks(self, RequestQuoteTicks request) void¶
Request historical QuoteTick data.
- Parameters:
request (RequestQuoteTicks) – The message for the data request.
- request_trade_ticks(self, RequestTradeTicks request) void¶
Request historical TradeTick data.
- Parameters:
request (RequestTradeTicks) – The message for the data request.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- resume(self) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- async run_after_delay(delay: float, coro: Coroutine) None¶
Run the given coroutine after a delay.
- Parameters:
delay (float) – The delay (seconds) before running the coroutine.
coro (Coroutine) – The coroutine to run after the initial delay.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- subscribe(self, SubscribeData command) void¶
Subscribe to data for the given data type.
- Parameters:
data_type (DataType) – The data type for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_bars(self, SubscribeBars command) void¶
Subscribe to Bar data for the given bar type.
- Parameters:
bar_type (BarType) – The bar type to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_funding_rates(self, SubscribeFundingRates command) void¶
Subscribe to FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_index_prices(self, SubscribeIndexPrices command) void¶
Subscribe to IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument(self, SubscribeInstrument command) void¶
Subscribe to the Instrument with the given instrument ID.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument_close(self, SubscribeInstrumentClose command) void¶
Subscribe to InstrumentClose updates for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument_status(self, SubscribeInstrumentStatus command) void¶
Subscribe to InstrumentStatus data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instruments(self, SubscribeInstruments command) void¶
Subscribe to all Instrument data.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_mark_prices(self, SubscribeMarkPrices command) void¶
Subscribe to MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_order_book_deltas(self, SubscribeOrderBook command) void¶
Subscribe to OrderBookDeltas data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.depth (int, optional, default None) – The maximum depth for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_order_book_depth(self, SubscribeOrderBook command) void¶
Subscribe to OrderBookDepth10 data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
depth (int, optional) – The maximum depth for the order book (defaults to 10).
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_quote_ticks(self, SubscribeQuoteTicks command) void¶
Subscribe to QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_trade_ticks(self, SubscribeTradeTicks command) void¶
Subscribe to TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribed_custom_data(self) list¶
Return the custom data types subscribed to.
- Return type:
list[DataType]
- subscribed_funding_rates(self) list¶
Return the funding rate update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_index_prices(self) list¶
Return the index price update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instrument_close(self) list¶
Return the instrument closes subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instrument_status(self) list¶
Return the status update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instruments(self) list¶
Return the instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_mark_prices(self) list¶
Return the mark price update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_order_book_deltas(self) list¶
Return the order book delta instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_order_book_depth(self) list¶
Return the order book depth instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_quote_ticks(self) list¶
Return the quote tick instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_trade_ticks(self) list¶
Return the trade tick instruments subscribed to.
- Return type:
list[InstrumentId]
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- unsubscribe(self, UnsubscribeData command) void¶
Unsubscribe from data for the given data type.
- Parameters:
data_type (DataType) – The data type for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_bars(self, UnsubscribeBars command) void¶
Unsubscribe from Bar data for the given bar type.
- Parameters:
bar_type (BarType) – The bar type to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_funding_rates(self, UnsubscribeFundingRates command) void¶
Unsubscribe from FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_index_prices(self, UnsubscribeIndexPrices command) void¶
Unsubscribe from IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument(self, UnsubscribeInstrument command) void¶
Unsubscribe from Instrument data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument_close(self, UnsubscribeInstrumentClose command) void¶
Unsubscribe from InstrumentClose data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument_status(self, UnsubscribeInstrumentStatus command) void¶
Unsubscribe from InstrumentStatus data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument status updates to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instruments(self, UnsubscribeInstruments command) void¶
Unsubscribe from all Instrument data.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_mark_prices(self, UnsubscribeMarkPrices command) void¶
Unsubscribe from MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_order_book_deltas(self, UnsubscribeOrderBook command) void¶
Unsubscribe from OrderBookDeltas data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_order_book_depth(self, UnsubscribeOrderBook command) void¶
Unsubscribe from OrderBookDepth10 data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_quote_ticks(self, UnsubscribeQuoteTicks command) void¶
Unsubscribe from QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_trade_ticks(self, UnsubscribeTradeTicks command) void¶
Unsubscribe from TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- venue¶
The clients venue ID (if applicable).
- Returns:
Venue or
None
Data Types¶
- class SubscriptionStatus¶
Bases:
EnumRepresents a Betfair subscription status.
- UNSUBSCRIBED = 0¶
- PENDING_STARTUP = 1¶
- RUNNING = 2¶
- SUBSCRIBED = 3¶
- class BSPOrderBookDelta¶
Bases:
OrderBookDelta- static from_batch(batch: RecordBatch) list[BSPOrderBookDelta]¶
- static to_batch(obj: BSPOrderBookDelta) RecordBatch¶
- classmethod schema() Schema¶
- 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:
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- 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:
- classmethod is_signal(cls, str name='') bool¶
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters:
name (str, optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns:
True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type:
bool
- 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 BetfairTicker¶
Bases:
DataRepresents a Betfair ticker.
- property ts_event: int¶
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- property ts_init: int¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- classmethod schema()¶
- classmethod from_dict(values: dict)¶
- static to_dict(obj: BetfairTicker)¶
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- classmethod is_signal(cls, str name='') bool¶
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters:
name (str, optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns:
True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type:
bool
- class BetfairStartingPrice¶
Bases:
DataRepresents the realized Betfair Starting Price.
- instrument_id: InstrumentId¶
- property ts_event: int¶
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- property ts_init: int¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- classmethod schema()¶
- classmethod from_dict(values: dict)¶
- static to_dict(obj)¶
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- classmethod is_signal(cls, str name='') bool¶
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters:
name (str, optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns:
True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type:
bool
- class BetfairRaceRunnerData¶
Bases:
DataRepresents Betfair TPD race runner GPS data.
Individual horse tracking data from the race stream (rrc - Race Runner Changes).
- property ts_event: int¶
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- property ts_init: int¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- classmethod schema()¶
- classmethod from_dict(values: dict)¶
- static to_dict(obj: BetfairRaceRunnerData)¶
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- classmethod is_signal(cls, str name='') bool¶
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters:
name (str, optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns:
True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type:
bool
- class BetfairRaceProgress¶
Bases:
DataRepresents Betfair TPD race progress data.
Overall race summary data from the race stream (rpc - Race Progress Changes).
- property ts_event: int¶
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- property ts_init: int¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- classmethod schema()¶
- classmethod from_dict(values: dict)¶
- static to_dict(obj: BetfairRaceProgress)¶
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- classmethod is_signal(cls, str name='') bool¶
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters:
name (str, optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns:
True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type:
bool
- class BetfairOrderVoided¶
Bases:
DataRepresents a Betfair order void event (e.g., VAR void).
Published when a matched bet is retroactively voided by Betfair, such as when a goal is disallowed following a VAR review.
- property ts_event: int¶
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- property ts_init: int¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type:
int
- classmethod schema()¶
- classmethod from_dict(values: dict)¶
- static to_dict(obj: BetfairOrderVoided)¶
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- classmethod is_signal(cls, str name='') bool¶
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters:
name (str, optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns:
True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type:
bool
- class BetfairSequenceCompleted¶
Bases:
DataBetfairSequenceCompleted()
- fields_init() None¶
- fields_repr()¶
- classmethod from_arrow(table: Table) BetfairSequenceCompleted¶
- classmethod from_bytes(data: bytes) BetfairSequenceCompleted¶
- classmethod from_dict(data: dict[str, Any]) BetfairSequenceCompleted¶
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the Data class.
- Return type:
str
References
- classmethod is_signal(cls, str name='') bool¶
Determine if the current class is a signal type, optionally checking for a specific signal name.
- Parameters:
name (str, optional) – The specific signal name to check. If name not provided or if an empty string is passed, the method checks whether the class name indicates a general signal type. If name is provided, the method checks if the class name corresponds to that specific signal.
- Returns:
True if the class name matches the signal type or the specific signal name, otherwise False.
- Return type:
bool
- to_arrow() RecordBatch¶
- to_bytes() bytes¶
- to_dict() dict[str, Any]¶
- property ts_event: int¶
int
UNIX timestamp (nanoseconds) when the data event occurred.
- Return type:
int
- Type:
- property ts_init: int¶
int
UNIX timestamp (nanoseconds) when the instance was created.
- Return type:
int
- Type:
Execution¶
- class BetfairExecutionClient¶
Bases:
LiveExecutionClientProvides an execution client for Betfair.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
client (BetfairHttpClient) – The Betfair HttpClient.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the client.
instrument_provider (BetfairInstrumentProvider) – The instrument provider.
config (BetfairExecClientConfig) – The configuration for the client.
- property instrument_provider: BetfairInstrumentProvider¶
Return the instrument provider for the client.
- Return type:
- async on_api_exception(error: BetfairError) None¶
- async request_account_state() AccountState¶
- async generate_order_status_report(command: GenerateOrderStatusReport) OrderStatusReport | None¶
Generate an OrderStatusReport for the given order identifier parameter(s).
If the order is not found, or an error occurs, then logs and returns
None.- Parameters:
command (GenerateOrderStatusReport) – The command to generate the report.
- Return type:
OrderStatusReport or
None- Raises:
ValueError – If both the client_order_id and venue_order_id are
None.
- async generate_order_status_reports(command: GenerateOrderStatusReports) list[OrderStatusReport]¶
Generate a list of `OrderStatusReport`s with optional query filters.
The returned list may be empty if no orders match the given parameters.
- Parameters:
command (GenerateOrderStatusReports) – The command for generating the reports.
- Return type:
list[OrderStatusReport]
- async generate_fill_reports(command: GenerateFillReports) list[FillReport]¶
Generate a list of `FillReport`s with optional query filters.
The returned list may be empty if no trades match the given parameters.
- Parameters:
command (GenerateFillReports) – The command for generating the reports.
- Return type:
list[FillReport]
- async generate_position_status_reports(command: GeneratePositionStatusReports) list[PositionStatusReport]¶
Generate a list of `PositionStatusReport`s with optional query filters.
The returned list may be empty if no positions match the given parameters.
- Parameters:
command (GeneratePositionStatusReports) – The command for generating the position status reports.
- Return type:
list[PositionStatusReport]
- handle_order_stream_update(raw: bytes) None¶
Handle an update from the order stream socket.
- check_cache_against_order_image(order_change_message: OCM) None¶
- account_id¶
The clients account ID.
- Returns:
AccountId or
None
- account_type¶
The clients account type.
- Returns:
AccountType
- base_currency¶
The clients account base currency (None for multi-currency accounts).
- Returns:
Currency or
None
- batch_cancel_orders(self, BatchCancelOrders command) void¶
Batch cancel orders for the instrument ID contained in the given command.
- Parameters:
command (BatchCancelOrders) – The command to execute.
- cancel_all_orders(self, CancelAllOrders command) void¶
Cancel all orders for the instrument ID contained in the given command.
- Parameters:
command (CancelAllOrders) – The command to execute.
- cancel_order(self, CancelOrder command) void¶
Cancel the order with the client order ID contained in the given command.
- Parameters:
command (CancelOrder) – The command to execute.
- async cancel_pending_tasks(timeout_secs: float = 5.0) None¶
Cancel all pending tasks and await their cancellation.
- Parameters:
timeout_secs (float, default 5.0) – The timeout in seconds to wait for tasks to cancel.
- connect() None¶
Connect the client.
- create_task(coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = <LogColor.NORMAL: 0>) Task¶
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
coro (Coroutine) – The coroutine to run.
log_msg (str, optional) – The log message for the task.
actions (Callable, optional) – The actions callback to run when the coroutine is done.
success_msg (str, optional) – The log message to write on actions success.
success_color (str, default
NORMAL) – The log message color for actions success.
- Return type:
asyncio.Task
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- disconnect() None¶
Disconnect the client.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- generate_account_state(self, list balances, list margins, bool reported, uint64_t ts_event, dict info=None) void¶
Generate an AccountState event and publish on the message bus.
- Parameters:
balances (list[AccountBalance]) – The account balances.
margins (list[MarginBalance]) – The margin balances.
reported (bool) – If the balances are reported directly from the exchange.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the account state event occurred.
info (dict [str, object]) – The additional implementation specific account information.
- async generate_mass_status(lookback_mins: int | None = None) ExecutionMassStatus | None¶
Generate an ExecutionMassStatus report.
- Parameters:
lookback_mins (int, optional) – The maximum lookback for querying closed orders, trades and positions.
- Return type:
ExecutionMassStatus or
None
- generate_order_accepted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderAccepted event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order accepted event occurred.
- generate_order_cancel_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderCancelRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
reason (str) – The order cancel rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.
- generate_order_canceled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderCanceled event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when order canceled event occurred.
- generate_order_denied(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderDenied event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
reason (str) – The order denied reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order denied event occurred.
- generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderExpired event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order expired event occurred.
- generate_order_filled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, PositionId venue_position_id: PositionId | None, TradeId trade_id, OrderSide order_side, OrderType order_type, Quantity last_qty, Price last_px, Currency quote_currency, Money commission, LiquiditySide liquidity_side, uint64_t ts_event, dict info=None) void¶
Generate an OrderFilled event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
trade_id (TradeId) – The trade ID.
venue_position_id (PositionId or
None) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise passNoneand the execution engine OMS will handle position ID resolution.order_side (OrderSide {
BUY,SELL}) – The execution order side.order_type (OrderType) – The execution order type.
last_qty (Quantity) – The fill quantity for this execution.
last_px (Price) – The fill price for this execution (not average price).
quote_currency (Currency) – The currency of the price.
commission (Money) – The fill commission.
liquidity_side (LiquiditySide {
NO_LIQUIDITY_SIDE,MAKER,TAKER}) – The execution liquidity side.ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order filled event occurred.
info (dict[str, object], optional) – The additional fill information.
- generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderModifyRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
reason (str) – The order update rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update rejection event occurred.
- generate_order_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event, bool due_post_only=False) void¶
Generate an OrderRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
reason (datetime) – The order rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order rejected event occurred.
due_post_only (bool, default False) – If the order was rejected because it was post-only and would execute immediately as a taker.
- generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event) void¶
Generate an OrderSubmitted event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order submitted event occurred.
- generate_order_triggered(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderTriggered event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order triggered event occurred.
- generate_order_updated(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, Quantity quantity, Price price, Price trigger_price, uint64_t ts_event, bool venue_order_id_modified=False) void¶
Generate an OrderUpdated event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
quantity (Quantity) – The orders current quantity.
price (Price) – The orders current price.
trigger_price (Price or
None) – The orders current trigger price.ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update event occurred.
venue_order_id_modified (bool) – If the ID was modified for this event.
- get_account(self) Account¶
Return the account for the client (if registered).
- Return type:
Account or
None
- id¶
The components ID.
- Returns:
ComponentId
- is_connected¶
If the client is connected.
- Returns:
bool
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- modify_order(self, ModifyOrder command) void¶
Modify the order with parameters contained in the command.
- Parameters:
command (ModifyOrder) – The command to execute.
- oms_type¶
The venues order management system type.
- Returns:
OmsType
- query_account(self, QueryAccount command) void¶
Query the account specified by the command which will generate an AccountState event.
- Parameters:
command (QueryAccount) – The command to execute.
- query_order(self, QueryOrder command) void¶
Initiate a reconciliation for the queried order which will generate an OrderStatusReport.
- Parameters:
command (QueryOrder) – The command to execute.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- resume(self) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- async run_after_delay(delay: float, coro: Coroutine) None¶
Run the given coroutine after a delay.
- Parameters:
delay (float) – The delay (seconds) before running the coroutine.
coro (Coroutine) – The coroutine to run after the initial delay.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- submit_order(self, SubmitOrder command) void¶
Submit the order contained in the given command for execution.
- Parameters:
command (SubmitOrder) – The command to execute.
- submit_order_list(self, SubmitOrderList command) void¶
Submit the order list contained in the given command for execution.
- Parameters:
command (SubmitOrderList) – The command to execute.
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- venue¶
The clients venue ID (if not a routing client).
- Returns:
Venue or
None
Factories¶
- get_cached_betfair_client(username: str | None = None, password: str | None = None, app_key: str | None = None, proxy_url: str | None = None, request_rate_per_second: int = 5, order_request_rate_per_second: int = 20) BetfairHttpClient¶
Cache and return a Betfair HTTP client with the given credentials.
If a cached client with matching parameters already exists, then that cached client will be returned. The cache key includes credentials and rate limit settings. With default rate limits, data and execution factories share a single client instance.
- Parameters:
username (str, optional) – The API username for the client. If None then will source from the BETFAIR_USERNAME env var.
password (str, optional) – The API password for the client. If None then will source from the BETFAIR_PASSWORD env var.
app_key (str, optional) – The API application key for the client. If None then will source from the BETFAIR_APP_KEY env var.
proxy_url (str, optional) – The proxy URL for HTTP requests.
request_rate_per_second (int, default 5) – The rate limit (requests/second) for general API endpoints.
order_request_rate_per_second (int, default 20) – The rate limit (requests/second) for order endpoints (placeOrders, replaceOrders, cancelOrders).
- Return type:
- get_cached_betfair_instrument_provider(client: BetfairHttpClient, config: BetfairInstrumentProviderConfig) BetfairInstrumentProvider¶
Cache and return a BetfairInstrumentProvider.
If a cached provider already exists, then that cached provider will be returned.
- Parameters:
client (BinanceHttpClient) – The client for the instrument provider.
config (BetfairInstrumentProviderConfig) – The config for the instrument provider.
- Return type:
- class BetfairLiveDataClientFactory¶
Bases:
LiveDataClientFactoryProvides a Betfair live data client factory.
- static create(loop: AbstractEventLoop, name: str, config: BetfairDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock)¶
Create a new Betfair data client.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
name (str) – The custom client ID.
config (dict[str, Any]) – The configuration dictionary.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the client.
- Return type:
- class BetfairLiveExecClientFactory¶
Bases:
LiveExecClientFactoryProvides data and execution clients for Betfair.
- static create(loop: AbstractEventLoop, name: str, config: BetfairExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock)¶
Create a new Betfair execution client.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
name (str) – The custom client ID.
config (dict[str, Any]) – The configuration for the client.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the client.
- Return type:
OrderBook¶
Providers¶
- class BetfairInstrumentProviderConfig¶
Bases:
InstrumentProviderConfigConfiguration for
BetfairInstrumentProviderinstances.- Parameters:
account_currency (str) – The Betfair account currency.
default_min_notional (PositiveFloat, optional) – The default minimum notional value for instrument definitions (in account currency).
event_type_ids (list[int], optional) – The event type IDs to filter for.
event_ids (list[int], optional) – The event IDs to filter for.
market_ids (list[str], optional) – The market IDs to filter for.
country_codes (list[str], optional) – The country codes to filter for.
market_types (list[str], optional) – The market types to filter for.
min_market_start_time (pd.Timestamp, optional) – The minimum market start time (UTC) to filter from (date granularity only).
max_market_start_time (pd.Timestamp, optional) – The maximum market start time (UTC) to filter to (date granularity only).
Notes
For each filter parameter, if not provided (None), then no filtering is done on that attribute.
- account_currency: str¶
- default_min_notional: Annotated[float, msgspec.Meta(gt=0.0)] | None¶
- event_type_ids: list[int] | None¶
- event_ids: list[int] | None¶
- market_ids: list[str] | None¶
- country_codes: list[str] | None¶
- market_types: list[str] | None¶
- event_type_names: list[str] | None¶
- min_market_start_time: Timestamp | None¶
- max_market_start_time: Timestamp | None¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- filter_callable: str | None¶
- filters: dict[str, Any] | None¶
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- load_all: bool¶
- load_ids: frozenset[InstrumentId] | None¶
- log_warnings: bool¶
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- use_gamma_markets: bool¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class BetfairInstrumentProvider¶
Bases:
InstrumentProviderProvides a means of loading BettingInstruments from the Betfair APIClient.
- Parameters:
client (BetfairHttpClient) – The Betfair HTTP client for the provider.
config (InstrumentProviderConfig) – The configuration for the provider.
- config: BetfairInstrumentProviderConfig¶
- async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
The default implementation calls
load_all_async(since many venue APIs only support bulk fetches) and then filters the provider to retain only the requested instruments plus any previously loaded ones.Subclasses with per-instrument fetch capability should override this method.
- Parameters:
instrument_ids (list[InstrumentId]) – The instrument IDs to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- async load_async(instrument_id: InstrumentId, filters: dict | None = None)¶
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
The default implementation delegates to
load_ids_async. Subclasses with per-instrument fetch capability should override this method.- Parameters:
instrument_id (InstrumentId) – The instrument ID to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- async load_all_async(filters: dict | None = None)¶
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
- async get_account_currency() str¶
- add(instrument: Instrument) None¶
Add the given instrument to the provider.
- Parameters:
instrument (Instrument) – The instrument to add.
- add_bulk(instruments: list[Instrument]) None¶
Add the given instruments bulk to the provider.
- Parameters:
instruments (list[Instrument]) – The instruments to add.
- add_currency(currency: Currency) None¶
Add the given currency to the provider.
- Parameters:
currency (Currency) – The currency to add.
- property count: int¶
Return the count of instruments held by the provider.
- Return type:
int
- currencies() dict[str, Currency]¶
Return all currencies held by the instrument provider.
- Return type:
dict[str, Currency]
- currency(code: str) Currency | None¶
Return the currency with the given code (if found).
- Parameters:
code (str) – The currency code.
- Return type:
Currency or
None- Raises:
ValueError – If code is not a valid string.
- find(instrument_id: InstrumentId) Instrument | None¶
Return the instrument for the given instrument ID (if found).
- Parameters:
instrument_id (InstrumentId) – The ID for the instrument
- Return type:
Instrument or
None
- get_all() dict[InstrumentId, Instrument]¶
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type:
dict[InstrumentId, Instrument]
- async initialize(reload: bool = False) None¶
Initialize the instrument provider.
- Parameters:
reload (bool, default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
- list_all() list[Instrument]¶
Return all loaded instruments.
- Return type:
list[Instrument]
- load(instrument_id: InstrumentId, filters: dict | None = None) None¶
Load the instrument for the given ID into the provider, optionally applying the given filters.
- Parameters:
instrument_id (InstrumentId) – The instrument ID to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- load_all(filters: dict | None = None) None¶
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters:
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
instrument_ids (list[InstrumentId]) – The instrument IDs to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- market_catalog_to_instruments(market_catalog: MarketCatalogue, currency: str, ts_event: int, ts_init: int, min_notional: Money | None) list[BettingInstrument]¶
- market_definition_to_instruments(market_definition: MarketDefinition, currency: str, ts_event: int, ts_init: int, min_notional: Money | None) list[BettingInstrument]¶
- make_instruments(market: MarketCatalogue | MarketDefinition, currency: str, ts_event: int, ts_init: int, min_notional: Money | None = None) list[BettingInstrument]¶
- check_market_filter_keys(keys: Iterable[str]) None¶
- async load_markets(client: BetfairHttpClient, event_type_ids: list[int] | None = None, event_ids: list[int] | None = None, market_ids: list[str] | None = None, event_country_codes: list[str] | None = None, market_market_types: list[str] | None = None, event_type_names: list[str] | None = None) list[FlattenedMarket]¶
- parse_market_catalog(catalog: list[dict]) list[MarketCatalogue]¶
- async load_markets_metadata(client: BetfairHttpClient, markets: list[FlattenedMarket], min_market_start_time: Timestamp | None = None, max_market_start_time: Timestamp | None = None) list[MarketCatalogue]¶
- get_market_book(client, market_ids)¶
Sockets¶
- class BetfairStreamClient¶
Bases:
objectProvides a streaming client for Betfair.
- async connect()¶
- async reconnect()¶
- async disconnect()¶
- is_active() bool¶
Check whether the client connection is active.
- Return type:
bool
- is_reconnecting() bool¶
Check whether the client is reconnecting.
- Return type:
bool
- is_disconnecting() bool¶
Check whether the client is disconnecting.
- Return type:
bool
- is_closed() bool¶
Check whether the client is closed.
- Return type:
bool
- post_connection() None¶
Actions to be performed post connection.
- post_reconnection() None¶
Actions to be performed post connection.
- post_disconnection() None¶
Actions to be performed post disconnection.
- async send(message: bytes) None¶
- auth_message()¶
- class BetfairOrderStreamClient¶
Bases:
BetfairStreamClientProvides an order stream client for Betfair.
- post_connection()¶
Actions to be performed post connection.
- post_reconnection()¶
Actions to be performed post connection.
- auth_message()¶
- async connect()¶
- async disconnect()¶
- is_active() bool¶
Check whether the client connection is active.
- Return type:
bool
- is_closed() bool¶
Check whether the client is closed.
- Return type:
bool
- is_disconnecting() bool¶
Check whether the client is disconnecting.
- Return type:
bool
- is_reconnecting() bool¶
Check whether the client is reconnecting.
- Return type:
bool
- post_disconnection() None¶
Actions to be performed post disconnection.
- async reconnect()¶
- async send(message: bytes) None¶
- class BetfairMarketStreamClient¶
Bases:
BetfairStreamClientProvides a Betfair market stream client.
- async send_subscription_message(market_ids: list | None = None, betting_types: list | None = None, event_type_ids: list | None = None, event_ids: list | None = None, turn_in_play_enabled: bool | None = None, market_types: list | None = None, venues: list | None = None, country_codes: list | None = None, race_types: list | None = None, initial_clk: str | None = None, clk: str | None = None, conflate_ms: int | None = None, heartbeat_ms: int | None = None, segmentation_enabled: bool = True, subscribe_book_updates=True, subscribe_trade_updates=True, subscribe_market_definitions=True, subscribe_ticker=True, subscribe_bsp_updates=True, subscribe_bsp_projected=True) None¶
- post_connection() None¶
Actions to be performed post connection.
- post_reconnection() None¶
Actions to be performed post connection.
- auth_message()¶
- async connect()¶
- async disconnect()¶
- is_active() bool¶
Check whether the client connection is active.
- Return type:
bool
- is_closed() bool¶
Check whether the client is closed.
- Return type:
bool
- is_disconnecting() bool¶
Check whether the client is disconnecting.
- Return type:
bool
- is_reconnecting() bool¶
Check whether the client is reconnecting.
- Return type:
bool
- post_disconnection() None¶
Actions to be performed post disconnection.
- async reconnect()¶
- async send(message: bytes) None¶
- class BetfairRaceStreamClient¶
Bases:
BetfairStreamClientProvides a Betfair race stream client for Total Performance Data (TPD).
Connects to sports-data-stream-api.betfair.com and subscribes to Race Change Messages (RCM) with live GPS tracking data.
- post_connection() None¶
Actions to be performed post connection.
- post_reconnection() None¶
Actions to be performed post connection.
- auth_message()¶
- async connect()¶
- async disconnect()¶
- is_active() bool¶
Check whether the client connection is active.
- Return type:
bool
- is_closed() bool¶
Check whether the client is closed.
- Return type:
bool
- is_disconnecting() bool¶
Check whether the client is disconnecting.
- Return type:
bool
- is_reconnecting() bool¶
Check whether the client is reconnecting.
- Return type:
bool
- post_disconnection() None¶
Actions to be performed post disconnection.
- async reconnect()¶
- async send(message: bytes) None¶