Betfair

Provides an API integration for the Betfair spots betting exchange.

Data

class BetfairDataClient ( loop : asyncio.events.AbstractEventLoop , client : nautilus_trader.adapters.betfair.client.core.BetfairClient , msgbus : nautilus_trader.msgbus.bus.MessageBus , cache : nautilus_trader.cache.cache.Cache , clock : nautilus_trader.common.clock.LiveClock , logger : nautilus_trader.common.logging.Logger , market_filter : Dict , instrument_provider : Optional [ nautilus_trader.adapters.betfair.providers.BetfairInstrumentProvider ] = None , strict_handling : bool = False )

Bases: nautilus_trader.live.data_client.LiveMarketDataClient

Provides 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.

  • logger ( Logger ) – The logger for the client.

  • market_filter ( dict ) – The market filter.

  • instrument_provider ( BetfairInstrumentProvider , optional ) – The instrument provider.

  • strict_handling ( bool ) – If strict handling mode is enabled.

connect ( self ) None

Connect the client.

disconnect ( self ) None

Disconnect the client.

request ( self , DataType data_type , UUID4 correlation_id ) void

Request data for the given data type.

Parameters
  • data_type ( DataType ) – The data type for the subscription.

  • correlation_id ( UUID4 ) – The correlation ID for the response.

subscribe_order_book_deltas ( self , InstrumentId instrument_id , BookType book_type , int depth=0 , dict kwargs=None ) 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_TBBO , L2_MBP , L3_MBO }) – The order book type.

  • depth ( int , optional , default None ) – The maximum depth for the subscription.

  • kwargs ( dict , optional ) – The keyword arguments for exchange specific parameters.

subscribe_trade_ticks ( self , InstrumentId instrument_id ) void

Subscribe to TradeTick data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

subscribe_instrument ( self , InstrumentId instrument_id ) void

Subscribe to the Instrument with the given instrument ID.

subscribe_instrument_status_updates ( self , InstrumentId instrument_id ) void

Subscribe to InstrumentStatusUpdates data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

subscribe_instrument_close_prices ( self , InstrumentId instrument_id ) void

Subscribe to InstrumentClosePrice data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

unsubscribe_order_book_snapshots ( self , InstrumentId instrument_id ) void

Unsubscribe from OrderBookSnapshot data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The order book instrument to unsubscribe from.

unsubscribe_order_book_deltas ( self , InstrumentId instrument_id ) void

Unsubscribe from OrderBookDeltas data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The order book instrument to unsubscribe from.

degrade ( self ) void

Degrade the component.

While executing on_degrade() , any exception will be logged and reraised. The component will remain in a DEGRADING state.

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.

dispose ( self ) void

Dispose of the component.

While executing on_dispose() , any exception will be logged and reraised. The component will remain in a DISPOSING state.

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.

This method is idempotent and irreversible. No other methods should be called after faulting.

While executing on_fault() , any exception will be logged and reraised. The component will remain in a FAULTING state.

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 ( type cls ) str

Return the fully qualified name for the components class.

Returns

str

References

https://www.python.org/dev/peps/pep-3155/

id

The components ID.

Returns

ComponentId

is_connected

If the client is connected.

Returns

bool

is_degraded

Return whether the current component state is DEGRADED .

Returns

bool

is_disposed

Return whether the current component state is DISPOSED .

Returns

bool

is_faulted

Return whether the current component state is FAULTED .

Returns

bool

is_initialized

Return whether the component has been initialized (component.state >= INITIALIZED ).

Returns

bool

is_running

Return whether the current component state is RUNNING .

Returns

bool

is_stopped

Return whether the current component state is STOPPED .

Returns

bool

request_bars ( self , BarType bar_type , datetime from_datetime , datetime to_datetime , int limit , UUID4 correlation_id ) void

Request historical Bar data.

Parameters
  • bar_type ( BarType ) – The bar type for the request.

  • from_datetime ( datetime , optional ) – The specified from datetime for the data.

  • to_datetime ( datetime , optional ) – The specified to datetime for the data. If None then will default to the current datetime.

  • limit ( int ) – The limit for the number of returned bars.

  • correlation_id ( UUID4 ) – The correlation ID for the request.

request_instrument ( self , InstrumentId instrument_id , UUID4 correlation_id ) void

Request Instrument data for the given instrument ID.

Parameters
  • instrument_id ( InstrumentId ) – The instrument ID for the request.

  • correlation_id ( UUID4 ) – The correlation ID for the request.

request_quote_ticks ( self , InstrumentId instrument_id , datetime from_datetime , datetime to_datetime , int limit , UUID4 correlation_id ) void

Request historical QuoteTick data.

Parameters
  • instrument_id ( InstrumentId ) – The tick instrument ID for the request.

  • from_datetime ( datetime , optional ) – The specified from datetime for the data.

  • to_datetime ( datetime , optional ) – The specified to datetime for the data. If None then will default to the current datetime.

  • limit ( int ) – The limit for the number of returned ticks.

  • correlation_id ( UUID4 ) – The correlation ID for the request.

request_trade_ticks ( self , InstrumentId instrument_id , datetime from_datetime , datetime to_datetime , int limit , UUID4 correlation_id ) void

Request historical TradeTick data.

Parameters
  • instrument_id ( InstrumentId ) – The tick instrument ID for the request.

  • from_datetime ( datetime , optional ) – The specified from datetime for the data.

  • to_datetime ( datetime , optional ) – The specified to datetime for the data. If None then will default to the current datetime.

  • limit ( int ) – The limit for the number of returned ticks.

  • correlation_id ( UUID4 ) – The correlation ID for the 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. The component will remain in a RESETTING state.

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. The component will remain in a RESUMING state.

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.

run_after_delay ( self , delay , coro ) None
sleep0 ( self ) None
start ( self ) void

Start the component.

While executing on_start() , any exception will be logged and reraised. The component will remain in a STARTING state.

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

Return the components current state.

Returns

ComponentState

stop ( self ) void

Stop the component.

While executing on_stop() , any exception will be logged and reraised. The component will remain in a STOPPING state.

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 , DataType data_type ) void

Subscribe to data for the given data type.

Parameters

data_type ( DataType ) – The data type for the subscription.

subscribe_bars ( self , BarType bar_type ) void

Subscribe to Bar data for the given bar type.

Parameters

bar_type ( BarType ) – The bar type to subscribe to.

subscribe_instruments ( self ) void

Subscribe to all Instrument data.

subscribe_order_book_snapshots ( self , InstrumentId instrument_id , BookType book_type , int depth=0 , dict kwargs=None ) void

Subscribe to OrderBookSnapshot data for the given instrument ID.

Parameters
  • instrument_id ( InstrumentId ) – The order book instrument to subscribe to.

  • book_type (BookType { L1_TBBO , L2_MBP , L3_MBO }) – The order book level.

  • depth ( int , optional ) – The maximum depth for the order book. A depth of 0 is maximum depth.

  • kwargs ( dict , optional ) – The keyword arguments for exchange specific parameters.

subscribe_quote_ticks ( self , InstrumentId instrument_id ) void

Subscribe to QuoteTick data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

subscribe_ticker ( self , InstrumentId instrument_id ) void

Subscribe to Ticker data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The ticker instrument to subscribe to.

subscribed_bars ( self ) list

Return the bar types subscribed to.

Returns

list[BarType]

subscribed_generic_data ( self ) list

Return the generic data types subscribed to.

Returns

list[DataType]

subscribed_instrument_close_prices ( self ) list

Return the close price instruments subscribed to.

Returns

list[InstrumentId]

subscribed_instrument_status_updates ( self ) list

Return the status update instruments subscribed to.

Returns

list[InstrumentId]

subscribed_instruments ( self ) list

Return the instruments subscribed to.

Returns

list[InstrumentId]

subscribed_order_book_deltas ( self ) list

Return the order book delta instruments subscribed to.

Returns

list[InstrumentId]

subscribed_order_book_snapshots ( self ) list

Return the order book snapshot instruments subscribed to.

Returns

list[InstrumentId]

subscribed_quote_ticks ( self ) list

Return the quote tick instruments subscribed to.

Returns

list[InstrumentId]

subscribed_tickers ( self ) list

Return the ticker instruments subscribed to.

Returns

list[InstrumentId]

subscribed_trade_ticks ( self ) list

Return the trade tick instruments subscribed to.

Returns

list[InstrumentId]

trader_id

The trader ID associated with the component.

Returns

TraderId

type

The components type.

Returns

type

unsubscribe ( self , DataType data_type ) void

Unsubscribe from data for the given data type.

Parameters

data_type ( DataType ) – The data type for the subscription.

unsubscribe_bars ( self , BarType bar_type ) void

Unsubscribe from Bar data for the given bar type.

Parameters

bar_type ( BarType ) – The bar type to unsubscribe from.

unsubscribe_instrument ( self , InstrumentId instrument_id ) void

Unsubscribe from Instrument data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The instrument to unsubscribe from.

unsubscribe_instrument_close_prices ( self , InstrumentId instrument_id ) void

Unsubscribe from InstrumentClosePrice data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The tick instrument to unsubscribe from.

unsubscribe_instrument_status_updates ( self , InstrumentId instrument_id ) void

Unsubscribe from InstrumentStatusUpdates data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The tick instrument to unsubscribe from.

unsubscribe_instruments ( self ) void

Unsubscribe from all Instrument data.

unsubscribe_quote_ticks ( self , InstrumentId instrument_id ) void

Unsubscribe from QuoteTick data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The tick instrument to unsubscribe from.

unsubscribe_ticker ( self , InstrumentId instrument_id ) void

Unsubscribe from Ticker data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The ticker instrument to unsubscribe from.

unsubscribe_trade_ticks ( self , InstrumentId instrument_id ) void

Unsubscribe from TradeTick data for the given instrument ID.

Parameters

instrument_id ( InstrumentId ) – The tick instrument to unsubscribe from.

venue

The clients venue ID (if not a routing client).

Returns

Venue or None

Data Types

class SubscriptionStatus ( value )

Bases: enum.Enum

Represents a Betfair subscription status.

class InstrumentSearch ( instruments , ts_event , ts_init )

Bases: nautilus_trader.core.data.Data

Represents a Betfair instrument search.

classmethod fully_qualified_name ( type cls ) str

Return the fully qualified name for the Data class.

Returns

str

References

https://www.python.org/dev/peps/pep-3155/

ts_event

The UNIX timestamp (nanoseconds) when the data event occurred.

Returns

uint64_t

ts_init

The UNIX timestamp (nanoseconds) when the object was initialized.

Returns

uint64_t

class BSPOrderBookDelta

Bases: nautilus_trader.model.orderbook.data.OrderBookDelta

Represents a Betfair BSP order book delta.

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.

Returns

OrderBookDelta

static to_dict ( OrderBookDelta obj )

Return a dictionary representation of this object.

Returns

dict[str, object]

action

The order book delta action { ADD , UPDATED , DELETE , CLEAR }.

Returns

BookAction

book_type

The order book type (L1_TBBO, L2_MBP, L3_MBO).

Returns

BookType

classmethod fully_qualified_name ( type cls ) str

Return the fully qualified name for the Data class.

Returns

str

References

https://www.python.org/dev/peps/pep-3155/

instrument_id

The instrument ID for the order book.

Returns

InstrumentId

order

The order to apply.

Returns

Order

ts_event

The UNIX timestamp (nanoseconds) when the data event occurred.

Returns

uint64_t

ts_init

The UNIX timestamp (nanoseconds) when the object was initialized.

Returns

uint64_t

update_id

The update ID.

Returns

uint64

class BetfairTicker ( instrument_id : nautilus_trader.model.identifiers.InstrumentId , ts_event : int , ts_init : int , last_traded_price : Optional [ nautilus_trader.model.objects.Price ] = None , traded_volume : Optional [ nautilus_trader.model.objects.Quantity ] = None )

Bases: nautilus_trader.model.data.ticker.Ticker

Represents a Betfair ticker.

static from_dict ( dict values ) Ticker

Return a ticker from the given dict values.

Parameters

values ( dict [ str , object ] ) – The values for initialization.

Returns

Ticker

classmethod fully_qualified_name ( type cls ) str

Return the fully qualified name for the Data class.

Returns

str

References

https://www.python.org/dev/peps/pep-3155/

instrument_id

The ticker instrument ID.

Returns

InstrumentId

static to_dict ( Ticker obj )

Return a dictionary representation of this object.

Returns

dict[str, object]

ts_event

The UNIX timestamp (nanoseconds) when the data event occurred.

Returns

uint64_t

ts_init

The UNIX timestamp (nanoseconds) when the object was initialized.

Returns

uint64_t

Execution

class BetfairExecutionClient ( loop : asyncio.events.AbstractEventLoop , client : nautilus_trader.adapters.betfair.client.core.BetfairClient , base_currency : nautilus_trader.model.currency.Currency , msgbus : nautilus_trader.msgbus.bus.MessageBus , cache : nautilus_trader.cache.cache.Cache , clock : nautilus_trader.common.clock.LiveClock , logger : nautilus_trader.common.logging.Logger , market_filter : Dict , instrument_provider : nautilus_trader.adapters.betfair.providers.BetfairInstrumentProvider )

Bases: nautilus_trader.live.execution_client.LiveExecutionClient

Provides an execution client for Betfair.

Parameters
  • loop ( asyncio.AbstractEventLoop ) – The event loop for the client.

  • client ( BetfairClient ) – The Betfair HttpClient.

  • base_currency ( Currency ) – The account base currency 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.

  • logger ( Logger ) – The logger for the client.

  • market_filter ( dict ) – The market filter.

  • instrument_provider ( BetfairInstrumentProvider , optional ) – The instrument provider.

connect ( self ) None

Abstract method (implement in subclass).

disconnect ( self ) None

Abstract method (implement in subclass).

async watch_stream ( )

Ensure socket stream is connected

async generate_order_status_report ( self , InstrumentId instrument_id: InstrumentId , client_order_id: Optional[ClientOrderId] = None , venue_order_id: Optional[VenueOrderId] = None )

Generate an order status report for the given order identifier parameter(s).

If the order is not found, or an error occurs, then logs and returns None .

Parameters
  • instrument_id ( InstrumentId ) – The instrument ID for the report.

  • client_order_id ( ClientOrderId , optional ) – The client order ID for the report.

  • venue_order_id ( VenueOrderId , optional ) – The venue order ID for the report.

Returns

OrderStatusReport or None

Raises

ValueError – If both the client_order_id and venue_order_id are None .

async generate_order_status_reports ( self , InstrumentId instrument_id=None , datetime start=None , datetime end=None , bool open_only=False )

Generate a list of order status reports with optional query filters.

The returned list may be empty if no orders match the given parameters.

Parameters
  • instrument_id ( InstrumentId , optional ) – The instrument ID query filter.

  • start ( datetime , optional ) – The start datetime query filter.

  • end ( datetime , optional ) – The end datetime query filter.

  • open_only ( bool , default False ) – If the query is for open orders only.

Returns

list[OrderStatusReport]

async generate_trade_reports ( self , InstrumentId instrument_id=None , VenueOrderId venue_order_id=None , datetime start=None , datetime end=None )

Generate a list of trade reports with optional query filters.

The returned list may be empty if no trades match the given parameters.

Parameters
  • instrument_id ( InstrumentId , optional ) – The instrument ID query filter.

  • venue_order_id ( VenueOrderId , optional ) – The venue order ID (assigned by the venue) query filter.

  • start ( datetime , optional ) – The start datetime query filter.

  • end ( datetime , optional ) – The end datetime query filter.

Returns

list[TradeReport]

async generate_position_status_reports ( self , InstrumentId instrument_id=None , datetime start=None , datetime end=None )

Generate a list of position status reports with optional query filters.

The returned list may be empty if no positions match the given parameters.

Parameters
  • instrument_id ( InstrumentId , optional ) – The instrument ID query filter.

  • start ( datetime , optional ) – The start datetime query filter.

  • end ( datetime , optional ) – The end datetime query filter.

Returns

list[PositionStatusReport]

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.

modify_order ( self , ModifyOrder command ) void

Modify the order with parameters contained in the command.

Parameters

command ( ModifyOrder ) – 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.

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.

async check_account_currency ( )

Check account currency against BetfairClient

handle_order_stream_update ( raw : bytes ) None

Handle an update from the order stream socket

async wait_for_order ( venue_order_id : nautilus_trader.model.identifiers.VenueOrderId , timeout_seconds = 10.0 ) Optional [ nautilus_trader.model.identifiers.ClientOrderId ]

We may get an order update from the socket before our submit_order response has come back (with our betId).

As a precaution, wait up to timeout_seconds for the betId to be added to self.order_id_to_client_order_id .

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

degrade ( self ) void

Degrade the component.

While executing on_degrade() , any exception will be logged and reraised. The component will remain in a DEGRADING state.

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.

dispose ( self ) void

Dispose of the component.

While executing on_dispose() , any exception will be logged and reraised. The component will remain in a DISPOSING state.

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.

This method is idempotent and irreversible. No other methods should be called after faulting.

While executing on_fault() , any exception will be logged and reraised. The component will remain in a FAULTING state.

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 ( type cls ) str

Return the fully qualified name for the components class.

Returns

str

References

https://www.python.org/dev/peps/pep-3155/

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 ) – The UNIX timestamp (nanoseconds) when the account state event occurred.

  • info ( dict [ str , object ] ) – The additional implementation specific account information.

generate_mass_status ( self , lookback_mins : Optional [ int ] )

Generate an execution mass status report.

Parameters

lookback_mins ( int , optional ) – The maximum lookback for querying closed orders, trades and positions.

Returns

ExecutionMassStatus

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 ) – The 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 , unicode 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 ) – The 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 ) – The UNIX timestamp (nanoseconds) when order canceled 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 ) – The 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: Optional[PositionId], 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 ) 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 , optional ) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise pass None and 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 { NONE , MAKER , TAKER }) – The execution liquidity side.

  • ts_event ( uint64_t ) – The UNIX timestamp (nanoseconds) when the order filled event occurred.

generate_order_modify_rejected ( self , StrategyId strategy_id , InstrumentId instrument_id , ClientOrderId client_order_id , VenueOrderId venue_order_id , unicode 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 ) – The UNIX timestamp (nanoseconds) when the order update rejection event occurred.

generate_order_pending_cancel ( self , StrategyId strategy_id , InstrumentId instrument_id , ClientOrderId client_order_id , VenueOrderId venue_order_id , uint64_t ts_event ) void

Generate an OrderPendingCancel 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 ) – The UNIX timestamp (nanoseconds) when the order pending cancel event occurred.

generate_order_pending_update ( self , StrategyId strategy_id , InstrumentId instrument_id , ClientOrderId client_order_id , VenueOrderId venue_order_id , uint64_t ts_event ) void

Generate an OrderPendingUpdate 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 ) – The UNIX timestamp (nanoseconds) when the order pending update event occurred.

generate_order_rejected ( self , StrategyId strategy_id , InstrumentId instrument_id , ClientOrderId client_order_id , unicode reason , uint64_t ts_event ) 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 ) – The UNIX timestamp (nanoseconds) when the order rejected event occurred.

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 ) – The 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 ) – The 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 , optional ) – The orders current trigger price.

  • ts_event ( uint64_t ) – The 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).

Returns

Account or None

id

The components ID.

Returns

ComponentId

is_connected

If the client is connected.

Returns

bool

is_degraded

Return whether the current component state is DEGRADED .

Returns

bool

is_disposed

Return whether the current component state is DISPOSED .

Returns

bool

is_faulted

Return whether the current component state is FAULTED .

Returns

bool

is_initialized

Return whether the component has been initialized (component.state >= INITIALIZED ).

Returns

bool

is_running

Return whether the current component state is RUNNING .

Returns

bool

is_stopped

Return whether the current component state is STOPPED .

Returns

bool

oms_type

The venues order management system type.

Returns

OMSType

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. The component will remain in a RESETTING state.

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. The component will remain in a RESUMING state.

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.

run_after_delay ( self , double delay: float , coro ) None
sleep0 ( self ) None
start ( self ) void

Start the component.

While executing on_start() , any exception will be logged and reraised. The component will remain in a STARTING state.

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

Return the components current state.

Returns

ComponentState

stop ( self ) void

Stop the component.

While executing on_stop() , any exception will be logged and reraised. The component will remain in a STOPPING state.

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.

sync_order_status ( self , QueryOrder command ) void

Request a reconciliation for the queried order which will generate an OrderStatusReport

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 : Optional [ str ] , password : Optional [ str ] , app_key : Optional [ str ] , cert_dir : Optional [ str ] , loop : asyncio.events.AbstractEventLoop , logger : nautilus_trader.common.logging.Logger ) nautilus_trader.adapters.betfair.client.core.BetfairClient

Cache and return a Betfair HTTP client with the given credentials.

If a cached client with matching credentials already exists, then that cached client will be returned.

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.

  • cert_dir ( str , optional ) – The API SSL certificate directory for the client. If None then will source from the BETFAIR_CERT_DIR env var.

  • loop ( asyncio.AbstractEventLoop ) – The event loop for the client.

  • logger ( Logger ) – The logger for the client.

Returns

BetfairClient

get_cached_betfair_instrument_provider ( client : nautilus_trader.adapters.betfair.client.core.BetfairClient , logger : nautilus_trader.common.logging.Logger , market_filter : tuple ) nautilus_trader.adapters.betfair.providers.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.

  • logger ( Logger ) – The logger for the instrument provider.

  • market_filter ( tuple ) – The market filter to load into the instrument provider.

Returns

BinanceInstrumentProvider

class BetfairLiveDataClientFactory

Bases: nautilus_trader.live.factories.LiveDataClientFactory

Provides a Betfair live data client factory.

static create ( loop : asyncio.events.AbstractEventLoop , name : str , config : nautilus_trader.adapters.betfair.config.BetfairDataClientConfig , msgbus : nautilus_trader.msgbus.bus.MessageBus , cache : nautilus_trader.cache.cache.Cache , clock : nautilus_trader.common.clock.LiveClock , logger : nautilus_trader.common.logging.LiveLogger ) nautilus_trader.adapters.betfair.data.BetfairDataClient

Create a new Betfair data client.

Parameters
  • loop ( asyncio.AbstractEventLoop ) – The event loop for the client.

  • name ( str ) – The client name.

  • 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.

  • logger ( LiveLogger ) – The logger for the client.

Returns

BetfairDataClient

class BetfairLiveExecClientFactory

Bases: nautilus_trader.live.factories.LiveExecClientFactory

Provides data and execution clients for Betfair.

static create ( loop : asyncio.events.AbstractEventLoop , name : str , config : nautilus_trader.adapters.betfair.config.BetfairExecClientConfig , msgbus : nautilus_trader.msgbus.bus.MessageBus , cache : nautilus_trader.cache.cache.Cache , clock : nautilus_trader.common.clock.LiveClock , logger : nautilus_trader.common.logging.LiveLogger ) nautilus_trader.adapters.betfair.execution.BetfairExecutionClient

Create a new Betfair execution client.

Parameters
  • loop ( asyncio.AbstractEventLoop ) – The event loop for the client.

  • name ( str ) – The client name.

  • 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.

  • logger ( LiveLogger ) – The logger for the client.

Returns

BetfairExecutionClient

Parsing

determine_order_price ( order : Union [ nautilus_trader.model.orders.limit.LimitOrder , nautilus_trader.model.orders.market.MarketOrder ] )

Determine the correct price to send for a given order. Betfair doesn’t support market orders, so if this order is a MarketOrder, we generate a MIN/MAX price based on the side :param order: :return:

order_submit_to_betfair ( command : nautilus_trader.execution.messages.SubmitOrder , instrument : nautilus_trader.model.instruments.betting.BettingInstrument ) Dict

Convert a SubmitOrder command into the data required by BetfairClient.

order_update_to_betfair ( command : nautilus_trader.execution.messages.ModifyOrder , venue_order_id : nautilus_trader.model.identifiers.VenueOrderId , side : importlib._bootstrap.OrderSide , instrument : nautilus_trader.model.instruments.betting.BettingInstrument )

Convert an ModifyOrder command into the data required by BetfairClient.

order_cancel_to_betfair ( command : nautilus_trader.execution.messages.CancelOrder , instrument : nautilus_trader.model.instruments.betting.BettingInstrument )

Convert a CancelOrder command into the data required by BetfairClient.

order_cancel_all_to_betfair ( instrument : nautilus_trader.model.instruments.betting.BettingInstrument )

Convert a CancelAllOrders command into the data required by BetfairClient.

parse_handicap ( x ) str

Ensure consistent parsing of the various handicap sources we get.

Providers

class BetfairInstrumentProvider ( client : nautilus_trader.adapters.betfair.client.core.BetfairClient , logger : nautilus_trader.common.logging.Logger , filters : Optional [ Dict ] = None , config : Optional [ nautilus_trader.config.common.InstrumentProviderConfig ] = None )

Bases: nautilus_trader.common.providers.InstrumentProvider

Provides a means of loading BettingInstruments from the Betfair APIClient.

Parameters
  • client ( APIClient ) – The client for the provider.

  • logger ( Logger ) – The logger for the provider.

  • config ( InstrumentProviderConfig , optional ) – The configuration for the provider.

async load_all_async ( market_filter = None )

Load the latest instruments into the provider asynchronously, optionally applying the given filters.

load_markets ( market_filter = None )

Search for betfair markets. Useful for debugging / interactive use

search_instruments ( instrument_filter = None )

Search for instruments within the cache. Useful for debugging / interactive use

get_betting_instrument ( market_id : str , selection_id : str , handicap : str ) nautilus_trader.model.instruments.betting.BettingInstrument

Return a betting instrument with performance friendly lookup.

add ( instrument : nautilus_trader.model.instruments.base.Instrument ) None

Add the given instrument to the provider.

Parameters

instrument ( Instrument ) – The instrument to add.

add_bulk ( instruments : List [ nautilus_trader.model.instruments.base.Instrument ] ) None

Add the given instruments bulk to the provider.

Parameters

instruments ( list [ Instrument ] ) – The instruments to add.

add_currency ( currency : nautilus_trader.model.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.

Returns

int

currencies ( ) Dict [ str , nautilus_trader.model.currency.Currency ]

Return all currencies held by the instrument provider.

Returns

dict[str, Currency]

currency ( code : str ) Optional [ nautilus_trader.model.currency.Currency ]

Return the currency with the given code (if found).

Parameters

code ( str ) – The currency code.

Returns

Currency or None

Raises

ValueError – If code is not a valid string.

find ( instrument_id : nautilus_trader.model.identifiers.InstrumentId ) Optional [ nautilus_trader.model.instruments.base.Instrument ]

Return the instrument for the given instrument ID (if found).

Parameters

instrument_id ( InstrumentId ) – The ID for the instrument

Returns

Instrument or None

get_all ( ) Dict [ nautilus_trader.model.identifiers.InstrumentId , nautilus_trader.model.instruments.base.Instrument ]

Return all loaded instruments as a map keyed by instrument ID.

If no instruments loaded, will return an empty dict.

Returns

dict[InstrumentId, Instrument]

async initialize ( ) None

Initialize the instrument provider.

If initialize() then will immediately return.

list_all ( ) List [ nautilus_trader.model.instruments.base.Instrument ]

Return all loaded instruments.

Returns

list[Instrument]

load ( instrument_id : nautilus_trader.model.identifiers.InstrumentId , filters : Optional [ Dict ] = 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 ( Dict , optional ) – The venue specific instrument loading filters to apply.

load_all ( filters : Optional [ Dict ] = None ) None

Load the latest instruments into the provider, optionally applying the given filters.

Parameters

filters ( Dict , optional ) – The venue specific instrument loading filters to apply.

async load_async ( instrument_id : nautilus_trader.model.identifiers.InstrumentId , filters : Optional [ Dict ] = None )

Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.

Parameters
  • instrument_id ( InstrumentId ) – The instrument ID to load.

  • filters ( Dict , optional ) – The venue specific instrument loading filters to apply.

Raises

ValueError – If instrument_id.venue is not equal to self.venue .

load_ids ( instrument_ids : List [ nautilus_trader.model.identifiers.InstrumentId ] , filters : Optional [ Dict ] = 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 ( Dict , optional ) – The venue specific instrument loading filters to apply.

async load_ids_async ( instrument_ids : List [ nautilus_trader.model.identifiers.InstrumentId ] , filters : Optional [ Dict ] = 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 ( Dict , optional ) – The venue specific instrument loading filters to apply.

Raises

ValueError – If any instrument_id.venue is not equal to self.venue .

property venue : nautilus_trader.model.identifiers.Venue

Return the providers venue.

Returns

Venue

Sockets

class BetfairStreamClient ( client : nautilus_trader.adapters.betfair.client.core.BetfairClient , logger_adapter : nautilus_trader.common.logging.LoggerAdapter , message_handler , loop = None , host = None , port = None , crlf = None , encoding = None )

Bases: nautilus_trader.network.socket.SocketClient

Provides a streaming client for Betfair .

connect ( self )
disconnect ( self )
host

The host for the socket client.

Returns

str

is_connected

If the socket is connected.

Returns

bool

port

The port for the socket client.

Returns

int

post_connection ( self )

The actions to perform post-connection. i.e. sending further connection messages.

reconnect ( self )
send ( self , bytes raw )
ssl

If the socket client is using SSL.

Returns

bool

start ( self )
stop ( self )
class BetfairOrderStreamClient ( client : nautilus_trader.adapters.betfair.client.core.BetfairClient , logger : nautilus_trader.common.logging.Logger , message_handler , partition_matched_by_strategy_ref = True , include_overall_position = None , customer_strategy_refs = None , ** kwargs )

Bases: nautilus_trader.adapters.betfair.sockets.BetfairStreamClient

Provides an order stream client for Betfair .

async post_connection ( self )

The actions to perform post-connection. i.e. sending further connection messages.

connect ( self )
disconnect ( self )
host

The host for the socket client.

Returns

str

is_connected

If the socket is connected.

Returns

bool

port

The port for the socket client.

Returns

int

reconnect ( self )
send ( self , bytes raw )
ssl

If the socket client is using SSL.

Returns

bool

start ( self )
stop ( self )
class BetfairMarketStreamClient ( client : nautilus_trader.adapters.betfair.client.core.BetfairClient , logger : nautilus_trader.common.logging.Logger , message_handler : Callable , ** kwargs )

Bases: nautilus_trader.adapters.betfair.sockets.BetfairStreamClient

Provides a Betfair market stream client.

async post_connection ( self )

The actions to perform post-connection. i.e. sending further connection messages.

connect ( self )
disconnect ( self )
host

The host for the socket client.

Returns

str

is_connected

If the socket is connected.

Returns

bool

port

The port for the socket client.

Returns

int

reconnect ( self )
send ( self , bytes raw )
ssl

If the socket client is using SSL.

Returns

bool

start ( self )
stop ( self )

Utility

flatten_tree ( y : Dict , ** filters )

Flatten a nested dict into a list of dicts with each nested level combined into a single dict.

chunk ( list_like , n )

Yield successive n-sized chunks from l.