Common

The common subpackage provides generic/common parts for assembling the frameworks various components.

More domain specific concepts are introduced above the core base layer. The ID cache is implemented, a base Clock with Test and Live implementations which can control many Timer instances.

Trading domain specific components for generating Order and Identifier objects. Common logging components. A high performance Queue . Common UUID4 factory.

Actor

The Actor class allows traders to implement their own customized components.

A user can inherit from Actor and optionally override any of the “on” named event methods. The class is not entirely initialized in a stand-alone way, the intended usage is to pass actors to a Trader so that they can be fully “wired” into the platform. Exceptions will be raised if an Actor attempts to operate without a managing Trader instance.

class Actor ( config : Optional [ ActorConfig ] = None )

Bases: Component

The base class for all actor components.

Parameters :

config ( ActorConfig , optional ) – The actor configuration.

Raises :

TypeError – If config is not of type ActorConfig .

Warning

This class should not be used directly, but through a concrete subclass.

cache

The read-only cache for the actor.

Returns :

CacheFacade

clock

The actors clock.

Returns :

Clock

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.

deregister_warning_event ( self , type event ) void

Deregister the given event type from warning log levels.

Parameters :

event ( type ) – The event class to deregister.

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/

handle_bar ( self , Bar bar ) void

Handle the given bar data.

If state is RUNNING then passes to on_bar .

Parameters :

bar ( Bar ) – The bar received.

Warning

System method (not intended to be called by user code).

handle_bars ( self , list bars ) void

Handle the given historical bar data by handling each bar individually.

Parameters :

bars ( list [ Bar ] ) – The bars to handle.

Warning

System method (not intended to be called by user code).

handle_data ( self , Data data ) void

Handle the given data.

If state is RUNNING then passes to on_data .

Parameters :

data ( Data ) – The data received.

Warning

System method (not intended to be called by user code).

handle_event ( self , Event event ) void

Handle the given event.

If state is RUNNING then passes to on_event .

Parameters :

event ( Event ) – The event received.

Warning

System method (not intended to be called by user code).

handle_historical_data ( self , Data data ) void

Handle the given historical data.

If state is RUNNING then passes to on_historical_data .

Parameters :

data ( Data ) – The historical data received.

Warning

System method (not intended to be called by user code).

handle_instrument ( self , Instrument instrument ) void

Handle the given instrument.

Passes to on_instrument if state is RUNNING .

Parameters :

instrument ( Instrument ) – The instrument received.

Warning

System method (not intended to be called by user code).

handle_instrument_close_price ( self , InstrumentClosePrice update ) void

Handle the given instrument close price update.

If state is RUNNING then passes to on_instrument_close_price .

Parameters :

update ( InstrumentClosePrice ) – The update received.

Warning

System method (not intended to be called by user code).

handle_instrument_status_update ( self , InstrumentStatusUpdate update ) void

Handle the given instrument status update.

If state is RUNNING then passes to on_instrument_status_update .

Parameters :

update ( InstrumentStatusUpdate ) – The update received.

Warning

System method (not intended to be called by user code).

handle_instruments ( self , list instruments ) void

Handle the given instruments data by handling each instrument individually.

Parameters :

instruments ( list [ Instrument ] ) – The instruments received.

Warning

System method (not intended to be called by user code).

handle_order_book ( self , OrderBook order_book ) void

Handle the given order book snapshot.

Passes to on_order_book if state is RUNNING .

Parameters :

order_book ( OrderBook ) – The order book received.

Warning

System method (not intended to be called by user code).

handle_order_book_delta ( self , OrderBookData delta ) void

Handle the given order book data.

Passes to on_order_book_delta if state is RUNNING .

Parameters :

delta ( OrderBookDelta , OrderBookDeltas , OrderBookSnapshot ) – The order book delta received.

Warning

System method (not intended to be called by user code).

handle_quote_tick ( self , QuoteTick tick ) void

Handle the given quote tick.

If state is RUNNING then passes to on_quote_tick .

Parameters :

tick ( QuoteTick ) – The tick received.

Warning

System method (not intended to be called by user code).

handle_quote_ticks ( self , list ticks ) void

Handle the given historical quote tick data by handling each tick individually.

Parameters :

ticks ( list [ QuoteTick ] ) – The ticks received.

Warning

System method (not intended to be called by user code).

handle_ticker ( self , Ticker ticker ) void

Handle the given ticker.

If state is RUNNING then passes to on_ticker .

Parameters :

ticker ( Ticker ) – The ticker received.

Warning

System method (not intended to be called by user code).

handle_trade_tick ( self , TradeTick tick ) void

Handle the given trade tick.

If state is RUNNING then passes to on_trade_tick .

Parameters :

tick ( TradeTick ) – The tick received.

Warning

System method (not intended to be called by user code).

handle_trade_ticks ( self , list ticks ) void

Handle the given tick data by handling each tick individually.

Parameters :

ticks ( list [ TradeTick ] ) – The ticks received.

Warning

System method (not intended to be called by user code).

handle_venue_status_update ( self , VenueStatusUpdate update ) void

Handle the given venue status update.

If state is RUNNING then passes to on_venue_status_update .

Parameters :

update ( VenueStatusUpdate ) – The update received.

Warning

System method (not intended to be called by user code).

id

The components ID.

Returns :

ComponentId

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

log

The actors logger.

Returns :

LoggerAdapter

msgbus

The message bus for the actor (if registered).

Returns :

MessageBus or None

on_bar ( self , Bar bar ) void

Actions to be performed when running and receives a bar.

Parameters :

bar ( Bar ) – The bar received.

Warning

System method (not intended to be called by user code).

on_data ( self , Data data ) void

Actions to be performed when running and receives generic data.

Parameters :

data ( Data ) – The data received.

Warning

System method (not intended to be called by user code).

on_degrade ( self ) void

Actions to be performed on degrade.

Warning

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_dispose ( self ) void

Actions to be performed on dispose.

Cleanup any resources used here.

Warning

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_event ( self , Event event ) void

Actions to be performed running and receives an event.

Parameters :

event ( Event ) – The event received.

Warning

System method (not intended to be called by user code).

on_fault ( self ) void

Actions to be performed on fault.

Cleanup any resources used by the actor here.

Warning

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_historical_data ( self , Data data ) void

Actions to be performed when running and receives historical data.

Parameters :

data ( Data ) – The historical data received.

Warning

System method (not intended to be called by user code).

on_instrument ( self , Instrument instrument ) void

Actions to be performed when running and receives an instrument.

Parameters :

instrument ( Instrument ) – The instrument received.

Warning

System method (not intended to be called by user code).

on_instrument_close_price ( self , InstrumentClosePrice update ) void

Actions to be performed when running and receives an instrument close price update.

Parameters :

update ( InstrumentClosePrice ) – The update received.

Warning

System method (not intended to be called by user code).

on_instrument_status_update ( self , InstrumentStatusUpdate update ) void

Actions to be performed when running and receives an instrument status update.

Parameters :

update ( InstrumentStatusUpdate ) – The update received.

Warning

System method (not intended to be called by user code).

on_order_book ( self , OrderBook order_book ) void

Actions to be performed when running and receives an order book snapshot.

Parameters :

order_book ( OrderBook ) – The order book received.

Warning

System method (not intended to be called by user code).

on_order_book_delta ( self , OrderBookData delta ) void

Actions to be performed when running and receives an order book delta.

Parameters :

delta ( OrderBookDelta , OrderBookDeltas , OrderBookSnapshot ) – The order book delta received.

Warning

System method (not intended to be called by user code).

on_quote_tick ( self , QuoteTick tick ) void

Actions to be performed when running and receives a quote tick.

Parameters :

tick ( QuoteTick ) – The tick received.

Warning

System method (not intended to be called by user code).

on_reset ( self ) void

Actions to be performed on reset.

Warning

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_resume ( self ) void

Actions to be performed on resume.

Warning

System method (not intended to be called by user code).

on_start ( self ) void

Actions to be performed on start.

The intent is that this method is called once per trading session, when initially starting.

It is recommended to subscribe/request for data here.

Warning

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_stop ( self ) void

Actions to be performed on stop.

The intent is that this method is called to pause, or when done for day.

Warning

System method (not intended to be called by user code).

Should be overridden in the actor implementation.

on_ticker ( self , Ticker ticker ) void

Actions to be performed when running and receives a ticker.

Parameters :

ticker ( Ticker ) – The ticker received.

Warning

System method (not intended to be called by user code).

on_trade_tick ( self , TradeTick tick ) void

Actions to be performed when running and receives a trade tick.

Parameters :

tick ( TradeTick ) – The tick received.

Warning

System method (not intended to be called by user code).

on_venue_status_update ( self , VenueStatusUpdate update ) void

Actions to be performed when running and receives a venue status update.

Parameters :

update ( VenueStatusUpdate ) – The update received.

Warning

System method (not intended to be called by user code).

publish_data ( self , DataType data_type , Data data ) void

Publish the given data to the message bus.

Parameters :
  • data_type ( DataType ) – The data type being published.

  • data ( Data ) – The data to publish.

publish_signal ( self , unicode name , value , uint64_t ts_event=0 ) void

Publish the given value as a signal to the message bus. Optionally setup persistence for this signal .

Parameters :
  • name ( str ) – The name of the signal being published.

  • value ( object ) – The signal data to publish.

  • ts_event ( uint64_t , optional ) – The UNIX timestamp (nanoseconds) when the signal event occurred. If None then will timestamp current time.

register_base ( self , TraderId trader_id , MessageBus msgbus , CacheFacade cache , Clock clock , Logger logger ) void

Register with a trader.

Parameters :
  • trader_id ( TraderId ) – The trader ID for the actor.

  • msgbus ( MessageBus ) – The message bus for the actor.

  • cache ( CacheFacade ) – The read-only cache for the actor.

  • clock ( Clock ) – The clock for the actor.

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

Warning

System method (not intended to be called by user code).

register_warning_event ( self , type event ) void

Register the given event type for warning log levels.

Parameters :

event ( type ) – The event class to register.

request_bars ( self , BarType bar_type , datetime from_datetime=None , datetime to_datetime=None , ClientId client_id=None ) void

Request historical Bar data.

If to_datetime is None then will request up to the most recent 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.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

Raises :

ValueError – If from_datetime is not less than to_datetime .

Notes

Always limited to the bar capacity of the DataEngine cache.

request_data ( self , ClientId client_id , DataType data_type ) void

Request custom data for the given data type from the given data client.

Parameters :
  • client_id ( ClientId ) – The data client ID.

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

request_instrument ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Request Instrument data for the given instrument ID.

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

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

request_instruments ( self , Venue venue , ClientId client_id=None ) void

Request all Instrument data for the given venue.

Parameters :
  • venue ( Venue ) – The venue for the request.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

request_quote_ticks ( self , InstrumentId instrument_id , datetime from_datetime=None , datetime to_datetime=None , ClientId client_id=None ) void

Request historical QuoteTick data.

If to_datetime is None then will request up to the most recent 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.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

Notes

Always limited to the tick capacity of the DataEngine cache.

request_trade_ticks ( self , InstrumentId instrument_id , datetime from_datetime=None , datetime to_datetime=None , ClientId client_id=None ) void

Request historical TradeTick data.

If to_datetime is None then will request up to the most recent 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.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

Notes

Always limited to the tick capacity of the DataEngine cache.

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.

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_bars ( self , BarType bar_type , ClientId client_id=None ) void

Subscribe to streaming Bar data for the given bar type.

Parameters :
  • bar_type ( BarType ) – The bar type to subscribe to.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_data ( self , DataType data_type , ClientId client_id=None ) void

Subscribe to data of the given data type.

Parameters :
  • data_type ( DataType ) – The data type to subscribe to.

  • client_id ( ClientId , optional ) – The data client ID. If supplied then a Subscribe command will be sent to the corresponding data client.

subscribe_instrument ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Subscribe to update Instrument data for the given instrument ID.

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

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instrument_close_prices ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Subscribe to closing prices for the given instrument id.

Parameters :
  • instrument_id ( InstrumentId ) – The instrument to subscribe to status updates for.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instrument_status_updates ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Subscribe to status updates of the given instrument id.

Parameters :
  • instrument_id ( InstrumentId ) – The instrument to subscribe to status updates for.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_instruments ( self , Venue venue , ClientId client_id=None ) void

Subscribe to update Instrument data for the given venue.

Parameters :
  • venue ( Venue ) – The venue for the subscription.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue.

subscribe_order_book_deltas ( self , InstrumentId instrument_id , BookType book_type=BookType.L2_MBP , int depth=0 , dict kwargs=None , ClientId client_id=None ) void

Subscribe to the order book deltas stream, being a snapshot then deltas OrderBookData for the given instrument ID.

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

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

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

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_order_book_snapshots ( self , InstrumentId instrument_id , BookType book_type=BookType.L2_MBP , int depth=0 , int interval_ms=1000 , dict kwargs=None , ClientId client_id=None ) void

Subscribe to OrderBook snapshots for the given instrument ID.

The DataEngine will only maintain one order book for each instrument. Because of this - the level, depth and kwargs for the stream will be set as per the last subscription request (this will also affect all subscribers).

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

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

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

  • interval_ms ( int ) – The order book snapshot interval in milliseconds.

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

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

Raises :
  • ValueError – If depth is negative (< 0).

  • ValueError – If interval_ms is not positive (> 0).

subscribe_quote_ticks ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Subscribe to streaming QuoteTick data for the given instrument ID.

Parameters :
  • instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_ticker ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Subscribe to streaming Ticker data for the given instrument ID.

Parameters :
  • instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_trade_ticks ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Subscribe to streaming TradeTick data for the given instrument ID.

Parameters :
  • instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

subscribe_venue_status_updates ( self , Venue venue , ClientId client_id=None ) void

Subscribe to status updates of the given venue.

Parameters :
  • venue ( Venue ) – The venue to subscribe to.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue.

to_importable_config ( self ) ImportableActorConfig

Returns an importable configuration for this actor.

Returns :

ImportableActorConfig

trader_id

The trader ID associated with the component.

Returns :

TraderId

type

The components type.

Returns :

type

unsubscribe_bars ( self , BarType bar_type , ClientId client_id=None ) void

Unsubscribe from streaming Bar data for the given bar type.

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

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_data ( self , DataType data_type , ClientId client_id=None ) void

Unsubscribe from data of the given data type.

Parameters :
  • data_type ( DataType ) – The data type to unsubscribe from.

  • client_id ( ClientId , optional ) – The data client ID. If supplied then an Unsubscribe command will be sent to the data client.

unsubscribe_instrument ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Unsubscribe from update Instrument data for the given instrument ID.

Parameters :
  • instrument_id ( InstrumentId ) – The instrument to unsubscribe from.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_instruments ( self , Venue venue , ClientId client_id=None ) void

Unsubscribe from update Instrument data for the given venue.

Parameters :
  • venue ( Venue ) – The venue for the subscription.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue.

unsubscribe_order_book_deltas ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Unsubscribe the order book deltas stream for the given instrument ID.

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

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_order_book_snapshots ( self , InstrumentId instrument_id , int interval_ms=1000 , ClientId client_id=None ) void

Unsubscribe from order book snapshots for the given instrument ID.

The interval must match the previously subscribed interval.

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

  • interval_ms ( int ) – The order book snapshot interval in milliseconds.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_quote_ticks ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Unsubscribe from streaming QuoteTick data for the given instrument ID.

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

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_ticker ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Unsubscribe from streaming Ticker data for the given instrument ID.

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

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_trade_ticks ( self , InstrumentId instrument_id , ClientId client_id=None ) void

Unsubscribe from streaming TradeTick data for the given instrument ID.

Parameters :
  • instrument_id ( InstrumentId ) – The tick instrument ID to unsubscribe from.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.

unsubscribe_venue_status_updates ( self , Venue venue , ClientId client_id=None ) void

Unsubscribe to status updates of the given venue.

Parameters :
  • venue ( Venue ) – The venue to subscribe to.

  • client_id ( ClientId , optional ) – The specific client ID for the command. If None then will be inferred from the venue.

Clock

class Clock

Bases: object

The abstract base class for all clocks.

Notes

An active timer is one which has not expired.

Warning

This class should not be used directly, but through a concrete subclass.

cancel_timer ( self , unicode name ) void

Cancel the timer corresponding to the given label.

Parameters :

name ( str ) – The name for the timer to cancel.

Notes

Logs a warning if a timer with the given name is not found (it may have already been canceled).

cancel_timers ( self ) void

Cancel all timers.

local_now ( self , tzinfo tz=None ) datetime

Return the current datetime of the clock in the given local timezone.

Parameters :

tz ( tzinfo , optional ) – The local timezone (if None the system local timezone is assumed for the target timezone).

Returns :

datetime – tz-aware in local timezone.

next_time_ns ( self , unicode name ) uint64_t

Find a particular timer.

Parameters :

name ( str ) – The name of the timer.

Returns :

uint64_t

Raises :

ValueError – If name is not a valid string.

register_default_handler ( self , handler : Callable [ [ TimeEvent ] , None ] ) void

Register the given handler as the clocks default handler.

handler Callable[[TimeEvent], None]

The handler to register.

Raises :

TypeError – If handler is not of type Callable .

set_time_alert ( self, unicode name, datetime alert_time, callback: Callable[[TimeEvent], None] = None ) void

Set a time alert for the given time.

When the time is reached the handler will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent .

Parameters :
  • name ( str ) – The name for the alert (must be unique for this clock).

  • alert_time ( datetime ) – The time for the alert.

  • callback ( Callable [ [ TimeEvent ] , None ] , optional ) – The callback to receive time events.

Raises :
  • ValueError – If name is not unique for this clock.

  • ValueError – If alert_time is not >= the clocks current time.

  • TypeError – If handler is not of type Callable or None .

  • ValueError – If handler is None and no default handler is registered.

set_time_alert_ns ( self, unicode name, uint64_t alert_time_ns, callback: Callable[[TimeEvent], None] = None ) void

Set a time alert for the given time.

When the time is reached the handler will be passed the TimeEvent containing the timers unique name. If no callback is passed then the default handler (if registered) will receive the TimeEvent .

Parameters :
  • name ( str ) – The name for the alert (must be unique for this clock).

  • alert_time_ns ( uint64_t ) – The UNIX time (nanoseconds) for the alert.

  • callback ( Callable [ [ TimeEvent ] , None ] , optional ) – The callback to receive time events.

Raises :
  • ValueError – If name is not unique for this clock.

  • ValueError – If alert_time is not >= the clocks current time.

  • TypeError – If callback is not of type Callable or None .

  • ValueError – If callback is None and no default handler is registered.

set_timer ( self, unicode name, timedelta interval, datetime start_time=None, datetime stop_time=None, callback: Optional[Callable[[TimeEvent], None]] = None ) void

Set a timer to run.

The timer will run from the start time (optionally until the stop time). When the intervals are reached the handlers will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent .

Parameters :
  • name ( str ) – The name for the timer (must be unique for this clock).

  • interval ( timedelta ) – The time interval for the timer.

  • start_time ( datetime , optional ) – The start time for the timer (if None then starts immediately).

  • stop_time ( datetime , optional ) – The stop time for the timer (if None then repeats indefinitely).

  • callback ( Callable [ [ TimeEvent ] , None ] , optional ) – The callback to receive time events.

Raises :
  • ValueError – If name is not unique for this clock.

  • ValueError – If interval is not positive (> 0).

  • ValueError – If stop_time is not None and stop_time < time now.

  • ValueError – If stop_time is not None and start_time + interval > stop_time .

  • TypeError – If handler is not of type Callable or None .

  • ValueError – If handler is None and no default handler is registered.

set_timer_ns ( self, unicode name, uint64_t interval_ns, uint64_t start_time_ns, uint64_t stop_time_ns, callback: Optional[Callable[[TimeEvent], None]] = None ) void

Set a timer to run.

The timer will run from the start time until the stop time. When the intervals are reached the handlers will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent .

Parameters :
  • name ( str ) – The name for the timer (must be unique for this clock).

  • interval_ns ( uint64_t ) – The time interval (nanoseconds) for the timer.

  • start_time_ns ( uint64_t ) – The start UNIX time (nanoseconds) for the timer.

  • stop_time_ns ( uint64_t ) – The stop UNIX time (nanoseconds) for the timer.

  • callback ( Callable [ [ TimeEvent ] , None ] , optional ) – The callback to receive time events.

Raises :
  • ValueError – If name is not unique for this clock.

  • ValueError – If interval is not positive (> 0).

  • ValueError – If stop_time is not None and stop_time < time now.

  • ValueError – If stop_time is not None and start_time + interval > stop_time .

  • TypeError – If callback is not of type Callable or None .

  • ValueError – If callback is None and no default handler is registered.

timer_count

Return the count of active timers running in the clock.

Returns :

int

timer_names

Return the names of active timers running in the clock.

Returns :

list[str]

timestamp ( self ) double

Return the current UNIX time in seconds.

Returns :

double

References

https://en.wikipedia.org/wiki/Unix_time

timestamp_ms ( self ) uint64_t

Return the current UNIX time in milliseconds (ms).

Returns :

uint64_t

References

https://en.wikipedia.org/wiki/Unix_time

timestamp_ns ( self ) uint64_t

Return the current UNIX time in nanoseconds (ns).

Returns :

uint64_t

References

https://en.wikipedia.org/wiki/Unix_time

utc_now ( self ) datetime

Return the current time (UTC).

Returns :

datetime – The current tz-aware UTC time of the clock.

class LiveClock ( loop : Optional [ asyncio.AbstractEventLoop ] = None )

Bases: Clock

Provides a monotonic clock for live trading. All times are timezone aware UTC.

Parameters :

loop ( asyncio.AbstractEventLoop ) – The event loop for the clocks timers.

cancel_timer ( self , unicode name ) void
cancel_timers ( self ) void
local_now ( self , tzinfo tz=None ) datetime

Return the current datetime of the clock in the given local timezone.

Parameters :

tz ( tzinfo , optional ) – The local timezone (if None the system local timezone is assumed for the target timezone).

Returns :

datetime – tz-aware in local timezone.

next_time_ns ( self , unicode name ) uint64_t
register_default_handler ( self , handler : Callable [ [ TimeEvent ] , None ] ) void

Register the given handler as the clocks default handler.

handler Callable[[TimeEvent], None]

The handler to register.

Raises :

TypeError – If handler is not of type Callable .

set_offset ( self , int64_t offset_ns ) void

Set the offset (nanoseconds) for the clock.

The offset will then be added to all subsequent timestamps.

Warning

It shouldn’t be necessary for a user to call this method.

set_time_alert ( self, unicode name, datetime alert_time, callback: Callable[[TimeEvent], None] = None ) void

Set a time alert for the given time.

When the time is reached the handler will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent .

Parameters :
  • name ( str ) – The name for the alert (must be unique for this clock).

  • alert_time ( datetime ) – The time for the alert.

  • callback ( Callable [ [ TimeEvent ] , None ] , optional ) – The callback to receive time events.

Raises :
  • ValueError – If name is not unique for this clock.

  • ValueError – If alert_time is not >= the clocks current time.

  • TypeError – If handler is not of type Callable or None .

  • ValueError – If handler is None and no default handler is registered.

set_time_alert_ns ( self, unicode name, uint64_t alert_time_ns, callback: Optional[Callable[[TimeEvent], None]] = None ) void
set_timer ( self, unicode name, timedelta interval, datetime start_time=None, datetime stop_time=None, callback: Optional[Callable[[TimeEvent], None]] = None ) void

Set a timer to run.

The timer will run from the start time (optionally until the stop time). When the intervals are reached the handlers will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent .

Parameters :
  • name ( str ) – The name for the timer (must be unique for this clock).

  • interval ( timedelta ) – The time interval for the timer.

  • start_time ( datetime , optional ) – The start time for the timer (if None then starts immediately).

  • stop_time ( datetime , optional ) – The stop time for the timer (if None then repeats indefinitely).

  • callback ( Callable [ [ TimeEvent ] , None ] , optional ) – The callback to receive time events.

Raises :
  • ValueError – If name is not unique for this clock.

  • ValueError – If interval is not positive (> 0).

  • ValueError – If stop_time is not None and stop_time < time now.

  • ValueError – If stop_time is not None and start_time + interval > stop_time .

  • TypeError – If handler is not of type Callable or None .

  • ValueError – If handler is None and no default handler is registered.

set_timer_ns ( self, unicode name, uint64_t interval_ns, uint64_t start_time_ns, uint64_t stop_time_ns, callback: Optional[Callable[[TimeEvent], None]] = None ) void
timer_count
timer_names
timestamp ( self ) double
timestamp_ms ( self ) uint64_t
timestamp_ns ( self ) uint64_t
utc_now ( self ) datetime

Return the current time (UTC).

Returns :

datetime – The current tz-aware UTC time of the clock.

class TestClock

Bases: Clock

Provides a monotonic clock for backtesting and unit testing.

advance_time ( self , uint64_t to_time_ns , bool set_time=True ) list

Advance the clocks time to the given to_time_ns .

Parameters :
  • to_time_ns ( uint64_t ) – The UNIX time (nanoseconds) to advance the clock to.

  • set_time ( bool ) – If the clock should also be set to the given to_time_ns .

Returns :

list[TimeEventHandler] – Sorted chronologically.

Raises :

ValueError – If to_time_ns is < the clocks current time.

cancel_timer ( self , unicode name ) void
cancel_timers ( self ) void
local_now ( self , tzinfo tz=None ) datetime

Return the current datetime of the clock in the given local timezone.

Parameters :

tz ( tzinfo , optional ) – The local timezone (if None the system local timezone is assumed for the target timezone).

Returns :

datetime – tz-aware in local timezone.

next_time_ns ( self , unicode name ) uint64_t
register_default_handler ( self , handler : Callable [ [ TimeEvent ] , None ] ) void

Register the given handler as the clocks default handler.

handler Callable[[TimeEvent], None]

The handler to register.

Raises :

TypeError – If handler is not of type Callable .

set_time ( self , uint64_t to_time_ns ) void

Set the clocks datetime to the given time (UTC).

Parameters :

to_time_ns ( uint64_t ) – The UNIX time (nanoseconds) to set.

set_time_alert ( self, unicode name, datetime alert_time, callback: Callable[[TimeEvent], None] = None ) void

Set a time alert for the given time.

When the time is reached the handler will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent .

Parameters :
  • name ( str ) – The name for the alert (must be unique for this clock).

  • alert_time ( datetime ) – The time for the alert.

  • callback ( Callable [ [ TimeEvent ] , None ] , optional ) – The callback to receive time events.

Raises :
  • ValueError – If name is not unique for this clock.

  • ValueError – If alert_time is not >= the clocks current time.

  • TypeError – If handler is not of type Callable or None .

  • ValueError – If handler is None and no default handler is registered.

set_time_alert_ns ( self, unicode name, uint64_t alert_time_ns, callback: Optional[Callable[[TimeEvent], None]] = None ) void
set_timer ( self, unicode name, timedelta interval, datetime start_time=None, datetime stop_time=None, callback: Optional[Callable[[TimeEvent], None]] = None ) void

Set a timer to run.

The timer will run from the start time (optionally until the stop time). When the intervals are reached the handlers will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent .

Parameters :
  • name ( str ) – The name for the timer (must be unique for this clock).

  • interval ( timedelta ) – The time interval for the timer.

  • start_time ( datetime , optional ) – The start time for the timer (if None then starts immediately).

  • stop_time ( datetime , optional ) – The stop time for the timer (if None then repeats indefinitely).

  • callback ( Callable [ [ TimeEvent ] , None ] , optional ) – The callback to receive time events.

Raises :
  • ValueError – If name is not unique for this clock.

  • ValueError – If interval is not positive (> 0).

  • ValueError – If stop_time is not None and stop_time < time now.

  • ValueError – If stop_time is not None and start_time + interval > stop_time .

  • TypeError – If handler is not of type Callable or None .

  • ValueError – If handler is None and no default handler is registered.

set_timer_ns ( self, unicode name, uint64_t interval_ns, uint64_t start_time_ns, uint64_t stop_time_ns, callback: Optional[Callable[[TimeEvent], None]] = None ) void
timer_count
timer_names
timestamp ( self ) double
timestamp_ms ( self ) uint64_t
timestamp_ns ( self ) uint64_t
utc_now ( self ) datetime

Return the current time (UTC).

Returns :

datetime – The current tz-aware UTC time of the clock.

Component

class Component ( Clock clock , Logger logger , TraderId trader_id=None , ComponentId component_id=None , unicode component_name=None , MessageBus msgbus=None , dict config=None )

Bases: object

The base class for all system components.

A component is not considered initialized until a message bus is registered (this either happens when one is passed to the constructor, or when registered with a trader).

Thus, if the component does not receive a message bus through the constructor, then it will be in a PRE_INITIALIZED state, otherwise if one is passed then it will be in an INITIALIZED state.

Parameters :
  • clock ( Clock ) – The clock for the component.

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

  • trader_id ( TraderId , optional ) – The trader ID associated with the component.

  • component_id ( ComponentId , optional ) – The component ID. If None is passed then the identifier will be taken from type(self).__name__ .

  • component_name ( str , optional ) – The custom component name.

  • msgbus ( MessageBus , optional ) – The message bus for the component (required before initialized).

  • config ( dict [ str , Any ] , optional ) – The configuration for the component.

Raises :

ValueError – If component_name is not a valid string.

Warning

This class should not be used directly, but through a concrete subclass.

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_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

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.

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.

trader_id

The trader ID associated with the component.

Returns :

TraderId

type

The components type.

Returns :

type

class ComponentFSMFactory

Bases: object

Provides a generic component Finite-State Machine.

static get_state_transition_table ( ) dict

The default state transition table.

Returns :

dict[int, int] – C Enums.

Enums

Defines system level enums for use with framework components.

Component State

Represents a discrete component state.

>>> from nautilus_trader.common.enums import ComponentState
>>> ComponentState.PRE_INITIALIZED
<ComponentState.PRE_INITIALIZED: 0>
>>> ComponentState.INITIALIZED
<ComponentState.INITIALIZED: 1>
>>> ComponentState.STARTING
<ComponentState.STARTING: 2>
>>> ComponentState.RUNNING
<ComponentState.RUNNING: 3>
>>> ComponentState.STOPPING
<ComponentState.STOPPING: 4>
>>> ComponentState.STOPPED
<ComponentState.STOPPED: 5>
>>> ComponentState.RESUMING
<ComponentState.RESUMING: 6>
>>> ComponentState.RESETTING
<ComponentState.RESETTING: 7>
>>> ComponentState.DISPOSING
<ComponentState.DISPOSING: 8>
>>> ComponentState.DISPOSED
<ComponentState.DISPOSED: 9>
>>> ComponentState.DEGRADING
<ComponentState.DEGRADING: 10>
>>> ComponentState.DEGRADED
<ComponentState.DEGRADED: 11>
>>> ComponentState.FAULTING
<ComponentState.FAULTING: 12>
>>> ComponentState.FAULTED
<ComponentState.FAULTED: 13>
>>> ComponentState.FAULTED
<ComponentState.FAULTED: 13>

Component Trigger

Represents a trigger event which will cause a component state transition.

>>> from nautilus_trader.common.enums import ComponentTrigger
>>> ComponentTrigger.INITIALIZE
<ComponentTrigger.INITIALIZE: 1>
>>> ComponentTrigger.START
<ComponentTrigger.START: 2>
>>> ComponentTrigger.RUNNING
<ComponentTrigger.RUNNING: 3>
>>> ComponentTrigger.STOP
<ComponentTrigger.STOP: 4>
>>> ComponentTrigger.STOPPED
<ComponentTrigger.STOPPED: 5>
>>> ComponentTrigger.RESUME
<ComponentTrigger.RESUME: 6>
>>> ComponentTrigger.RESET
<ComponentTrigger.RESET: 7>
>>> ComponentTrigger.DISPOSE
<ComponentTrigger.DISPOSE: 8>
>>> ComponentTrigger.DISPOSED
<ComponentTrigger.DISPOSED: 9>
>>> ComponentTrigger.DEGRADE
<ComponentTrigger.DEGRADE: 10>
>>> ComponentTrigger.DEGRADED
<ComponentTrigger.DEGRADED: 11>
>>> ComponentTrigger.FAULT
<ComponentTrigger.FAULT: 12>
>>> ComponentTrigger.FAULTED
<ComponentTrigger.FAULTED: 13>

Log Level

Represents a log level threshold for configuration.

Enums values match the built-in Python LogLevel .

>>> from nautilus_trader.common.enums import LogLevel
>>> LogLevel.DEBUG
<LogLevel.DEBUG: 10>
>>> LogLevel.INFO
<LogLevel.INFO: 20>
>>> LogLevel.WARNING
<LogLevel.WARNING: 30>
>>> LogLevel.ERROR
<LogLevel.ERROR: 40>
>>> LogLevel.CRITICAL
<LogLevel.CRITICAL: 50>

Log Color

Represents log color constants.

>>> from nautilus_trader.common.enums import LogColor
>>> LogColor.NORMAL
<LogColor.NORMAL: 0>
>>> LogColor.GREEN
<LogColor.GREEN: 1>
>>> LogColor.BLUE
<LogColor.BLUE: 2>
>>> LogColor.YELLOW
<LogColor.YELLOW: 3>
>>> LogColor.RED
<LogColor.RED: 4>
class ComponentState ( value , names = None , * , module = None , qualname = None , type = None , start = 1 , boundary = None )

Bases: IntEnum

as_integer_ratio ( )

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count ( )

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length ( )

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate ( )

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes ( byteorder = 'big' , * , signed = False )

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes ( length = 1 , byteorder = 'big' , * , signed = False )

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

class ComponentTrigger ( value , names = None , * , module = None , qualname = None , type = None , start = 1 , boundary = None )

Bases: IntEnum

as_integer_ratio ( )

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count ( )

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length ( )

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate ( )

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes ( byteorder = 'big' , * , signed = False )

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes ( length = 1 , byteorder = 'big' , * , signed = False )

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

class LogColor ( value , names = None , * , module = None , qualname = None , type = None , start = 1 , boundary = None )

Bases: IntEnum

as_integer_ratio ( )

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count ( )

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length ( )

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate ( )

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes ( byteorder = 'big' , * , signed = False )

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes ( length = 1 , byteorder = 'big' , * , signed = False )

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

class LogLevel ( value , names = None , * , module = None , qualname = None , type = None , start = 1 , boundary = None )

Bases: IntEnum

as_integer_ratio ( )

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count ( )

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length ( )

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate ( )

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes ( byteorder = 'big' , * , signed = False )

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes ( length = 1 , byteorder = 'big' , * , signed = False )

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use ` sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

Factories

class OrderFactory ( TraderId trader_id , StrategyId strategy_id , Clock clock , int initial_count=0 )

Bases: object

A factory class which provides different order types.

The TraderId tag and StrategyId tag will be inserted into all IDs generated.

Parameters :
  • trader_id ( TraderId ) – The trader ID (only numerical tag sent to venue).

  • strategy_id ( StrategyId ) – The strategy ID (only numerical tag sent to venue).

  • clock ( Clock ) – The clock for the factory.

  • initial_count ( int , optional ) – The initial order count for the factory.

Raises :

ValueError – If initial_count is negative (< 0).

bracket_limit_entry ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , Price entry_price , Price sl_trigger_price , Price tp_price , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool post_only=False , TriggerType emulation_trigger=TriggerType.NONE , ContingencyType contingency_type=ContingencyType.OUO ) OrderList
Create a bracket order with the following types:
  • Limit parent entry order

  • StopMarket child stop-loss order

  • Limit child take-profit order

The bracketing stop-loss and take-profit orders will have a time in force of GTC .

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The entry orders side.

  • quantity ( Quantity ) – The entry orders quantity (> 0).

  • entry_price ( Price ) – The entry order price (LIMIT).

  • sl_trigger_price ( Price ) – The stop-loss child order trigger price (STOP).

  • tp_price ( Price ) – The take-profit child order price (LIMIT).

  • time_in_force (TimeInForce { DAY , GTC }, optional) – The entry orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • post_only ( bool , default False ) – If the entry order will only provide liquidity (make a market).

  • emulation_trigger (TriggerType, default NONE ) – The emulation trigger type for the entry, as well as the TP and SL bracket orders.

  • contingency_type (ContingencyType, default OUO ) – The contingency type for the TP and SL bracket orders.

Returns :

OrderList

Raises :
  • ValueError – If entry order_side is NONE .

  • ValueError – If tif is GTD and expire_time is None .

  • ValueError – If entry order_side is BUY and entry_price <= sl_trigger_price .

  • ValueError – If entry order_side is BUY and entry_price >= tp_price .

  • ValueError – If entry order_side is SELL and entry_price >= sl_trigger_price .

  • ValueError – If entry order_side is SELL and entry_price <= tp_price .

bracket_market_entry ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , Price sl_trigger_price , Price tp_price , TriggerType emulation_trigger=TriggerType.NONE , ContingencyType contingency_type=ContingencyType.OUO ) OrderList
Create a bracket order with the following types:
  • Market parent entry order

  • StopMarket child stop-loss order

  • Limit child take-profit order

The bracketing stop-loss and take-profit orders will have a time in force of GTC .

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The entry orders side.

  • quantity ( Quantity ) – The entry orders quantity (> 0).

  • sl_trigger_price ( Price ) – The stop-loss child order trigger price (STOP).

  • tp_price ( Price ) – The take-profit child order price (LIMIT).

  • emulation_trigger (TriggerType, default NONE ) – The emulation trigger type for the TP and SL bracket orders.

  • contingency_type (ContingencyType, default OUO ) – The contingency type for the TP and SL bracket orders.

Returns :

OrderList

Raises :
  • ValueError – If entry order_side is NONE .

  • ValueError – If entry order_side is BUY and sl_trigger_price >= tp_price .

  • ValueError – If entry order_side is SELL and sl_trigger_price <= tp_price .

bracket_stop_limit_entry_stop_limit_tp ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , Price entry_trigger_price , Price entry_price , Price sl_trigger_price , Price tp_trigger_price , Price tp_price , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool post_only=False , TriggerType emulation_trigger=TriggerType.NONE , ContingencyType contingency_type=ContingencyType.OUO ) OrderList
Create a bracket order with the following types:
  • StopLimit parent entry order

  • StopMarket child stop-loss order

  • StopLimit child take-profit order

The bracketing stop-loss and take-profit orders will have a time in force of GTC .

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The entry orders side.

  • quantity ( Quantity ) – The entry orders quantity (> 0).

  • entry_trigger_price ( Price ) – The entry order trigger price (STOP).

  • entry_price ( Price ) – The entry order price (LIMIT).

  • sl_trigger_price ( Price ) – The stop-loss child order trigger price (STOP).

  • tp_trigger_price ( Price ) – The take-profit child order trigger price (STOP).

  • tp_price ( Price ) – The take-profit child order price (LIMIT).

  • time_in_force (TimeInForce { DAY , GTC }, optional) – The entry orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • post_only ( bool , default False ) – If the entry order will only provide liquidity (make a market).

  • emulation_trigger (TriggerType, default NONE ) – The emulation trigger type for the entry, as well as the TP and SL bracket orders.

  • contingency_type (ContingencyType, default OUO ) – The contingency type for the TP and SL bracket orders.

Returns :

OrderList

Raises :
  • ValueError – If entry order_side is NONE .

  • ValueError – If tif is GTD and expire_time is None .

  • ValueError – If entry order_side is BUY and entry_price <= sl_trigger_price .

  • ValueError – If entry order_side is BUY and entry_price >= tp_price .

  • ValueError – If entry order_side is SELL and entry_price >= sl_trigger_price .

  • ValueError – If entry order_side is SELL and entry_price <= tp_price .

count

Return the count of IDs generated.

Returns :

int

limit ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , Price price , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool post_only=False , bool reduce_only=False , Quantity display_qty=None , TriggerType emulation_trigger=TriggerType.NONE , unicode tags=None ) LimitOrder

Create a new Limit order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • price ( Price ) – The orders price.

  • time_in_force (TimeInForce { GTC , IOC , FOK , GTD , DAY , AT_THE_OPEN , AT_THE_CLOSE }, default GTC ) – The orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • post_only ( bool , default False ) – If the order will only provide liquidity (make a market).

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • display_qty ( Quantity , optional ) – The quantity of the order to display on the public book (iceberg).

  • emulation_trigger (TriggerType, default NONE ) – The orders emulation trigger.

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

LimitOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.

  • ValueError – If display_qty is negative (< 0) or greater than quantity .

limit_if_touched ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , Price price , Price trigger_price , TriggerType trigger_type=TriggerType.DEFAULT , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool post_only=False , bool reduce_only=False , Quantity display_qty=None , TriggerType emulation_trigger=TriggerType.NONE , unicode tags=None ) LimitIfTouchedOrder

Create a new Limit-If-Touched (LIT) conditional order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • price ( Price ) – The orders limit price.

  • trigger_price ( Price ) – The orders trigger stop price.

  • trigger_type (TriggerType, default DEFAULT ) – The order trigger type.

  • time_in_force (TimeInForce { GTC , IOC , FOK , GTD , DAY }, default GTC ) – The orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • post_only ( bool , default False ) – If the order will only provide liquidity (make a market).

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • display_qty ( Quantity , optional ) – The quantity of the order to display on the public book (iceberg).

  • emulation_trigger (TriggerType, default NONE ) – The orders emulation trigger.

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

LimitIfTouchedOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If trigger_type is NONE .

  • ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE .

  • ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.

  • ValueError – If display_qty is negative (< 0) or greater than quantity .

market ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , TimeInForce time_in_force=TimeInForce.GTC , bool reduce_only=False , unicode tags=None ) MarketOrder

Create a new Market order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • time_in_force (TimeInForce { GTC , IOC , FOK , DAY , AT_THE_OPEN , AT_THE_CLOSE }, default GTC ) – The orders time in force. Often not applicable for market orders.

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

MarketOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If time_in_force is GTD .

market_if_touched ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , Price trigger_price , TriggerType trigger_type=TriggerType.DEFAULT , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool reduce_only=False , TriggerType emulation_trigger=TriggerType.NONE , unicode tags=None ) MarketIfTouchedOrder

Create a new Market-If-Touched (MIT) conditional order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • trigger_price ( Price ) – The orders trigger price (STOP).

  • trigger_type (TriggerType, default DEFAULT ) – The order trigger type.

  • time_in_force (TimeInForce { GTC , IOC , FOK , GTD , DAY }, default GTC ) – The orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • emulation_trigger (TriggerType, default NONE ) – The orders emulation trigger.

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

MarketIfTouchedOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If trigger_type is NONE .

  • ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE .

  • ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.

market_to_limit ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool reduce_only=False , Quantity display_qty=None , unicode tags=None ) MarketToLimitOrder

Create a new Market order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • time_in_force (TimeInForce { GTC , GTD , IOC , FOK }, default GTC ) – The orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • display_qty ( Quantity , optional ) – The quantity of the limit order to display on the public book (iceberg).

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

MarketToLimitOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE .

reset ( self ) void

Reset the order factory.

All stateful fields are reset to their initial value.

set_count ( self , int count ) void

Set the internal order ID generator count to the given count.

Parameters :

count ( int ) – The count to set.

Warning

System method (not intended to be called by user code).

stop_limit ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , Price price , Price trigger_price , TriggerType trigger_type=TriggerType.DEFAULT , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool post_only=False , bool reduce_only=False , Quantity display_qty=None , TriggerType emulation_trigger=TriggerType.NONE , unicode tags=None ) StopLimitOrder

Create a new Stop-Limit conditional order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • price ( Price ) – The orders limit price.

  • trigger_price ( Price ) – The orders trigger stop price.

  • trigger_type (TriggerType, default DEFAULT ) – The order trigger type.

  • time_in_force (TimeInForce { GTC , IOC , FOK , GTD , DAY }, default GTC ) – The orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • post_only ( bool , default False ) – If the order will only provide liquidity (make a market).

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • display_qty ( Quantity , optional ) – The quantity of the order to display on the public book (iceberg).

  • emulation_trigger (TriggerType, default NONE ) – The orders emulation trigger.

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

StopLimitOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If trigger_type is NONE .

  • ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE .

  • ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.

  • ValueError – If display_qty is negative (< 0) or greater than quantity .

stop_market ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , Price trigger_price , TriggerType trigger_type=TriggerType.DEFAULT , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool reduce_only=False , TriggerType emulation_trigger=TriggerType.NONE , unicode tags=None ) StopMarketOrder

Create a new Stop-Market conditional order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • trigger_price ( Price ) – The orders trigger price (STOP).

  • trigger_type (TriggerType, default DEFAULT ) – The order trigger type.

  • time_in_force (TimeInForce { GTC , IOC , FOK , GTD , DAY }, default GTC ) – The orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • emulation_trigger (TriggerType, default NONE ) – The orders emulation trigger.

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

StopMarketOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If trigger_type is NONE .

  • ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE .

  • ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.

strategy_id

The order factories trading strategy ID.

Returns :

StrategyId

trader_id

The order factories trader ID.

Returns :

TraderId

trailing_stop_limit ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , limit_offset: Decimal , trailing_offset: Decimal , Price price=None , Price trigger_price=None , TriggerType trigger_type=TriggerType.DEFAULT , TrailingOffsetType trailing_offset_type=TrailingOffsetType.PRICE , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool post_only=False , bool reduce_only=False , Quantity display_qty=None , TriggerType emulation_trigger=TriggerType.NONE , unicode tags=None ) TrailingStopLimitOrder

Create a new Trailing-Stop-Limit conditional order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • trailing_offset ( Decimal ) – The trailing offset for the trigger price (STOP).

  • limit_offset ( Decimal ) – The trailing offset for the order price (LIMIT).

  • price ( Price , optional ) – The order price (LIMIT). If None then will typically default to the delta of market price and limit_offset .

  • trigger_price ( Price , optional ) – The order trigger price (STOP). If None then will typically default to the delta of market price and trailing_offset .

  • trigger_type (TriggerType, default DEFAULT ) – The order trigger type.

  • trailing_offset_type (TrailingOffsetType, default PRICE ) – The order trailing offset type.

  • time_in_force (TimeInForce { GTC , IOC , FOK , GTD , DAY }, default GTC ) – The orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • post_only ( bool , default False ) – If the order will only provide liquidity (make a market).

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • display_qty ( Quantity , optional ) – The quantity of the order to display on the public book (iceberg).

  • emulation_trigger (TriggerType, default NONE ) – The orders emulation trigger.

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

TrailingStopLimitOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If trigger_type is NONE .

  • ValueError – If trailing_offset_type is NONE .

  • ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE .

  • ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.

  • ValueError – If display_qty is negative (< 0) or greater than quantity .

trailing_stop_market ( self , InstrumentId instrument_id , OrderSide order_side , Quantity quantity , trailing_offset: Decimal , Price trigger_price=None , TriggerType trigger_type=TriggerType.DEFAULT , TrailingOffsetType trailing_offset_type=TrailingOffsetType.PRICE , TimeInForce time_in_force=TimeInForce.GTC , datetime expire_time=None , bool reduce_only=False , TriggerType emulation_trigger=TriggerType.NONE , unicode tags=None ) TrailingStopMarketOrder

Create a new Trailing-Stop-Market conditional order.

Parameters :
  • instrument_id ( InstrumentId ) – The orders instrument ID.

  • order_side (OrderSide { BUY , SELL }) – The orders side.

  • quantity ( Quantity ) – The orders quantity (> 0).

  • trailing_offset ( Decimal ) – The trailing offset for the trigger price (STOP).

  • trigger_price ( Price , optional ) – The order trigger price (STOP). If None then will typically default to the delta of market price and trailing_offset .

  • trigger_type (TriggerType, default DEFAULT ) – The order trigger type.

  • trailing_offset_type (TrailingOffsetType, default PRICE ) – The order trailing offset type.

  • time_in_force (TimeInForce { GTC , IOC , FOK , GTD , DAY }, default GTC ) – The orders time in force.

  • expire_time ( datetime , optional ) – The order expiration (for GTD orders).

  • reduce_only ( bool , default False ) – If the order carries the ‘reduce-only’ execution instruction.

  • emulation_trigger (TriggerType, default NONE ) – The orders emulation trigger.

  • tags ( str , optional ) – The custom user tags for the order. These are optional and can contain any arbitrary delimiter if required.

Returns :

TrailingStopMarketOrder

Raises :
  • ValueError – If quantity is not positive (> 0).

  • ValueError – If trigger_type is NONE .

  • ValueError – If trailing_offset_type is NONE .

  • ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE .

  • ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.

Generators

class ClientOrderIdGenerator ( TraderId trader_id , StrategyId strategy_id , Clock clock , int initial_count=0 )

Bases: IdentifierGenerator

Provides a generator for unique ` ClientOrderId`(s).

Parameters :
  • trader_id ( TraderId ) – The trader ID for the generator.

  • strategy_id ( StrategyId ) – The strategy ID for the generator.

  • clock ( Clock ) – The clock for the generator.

  • initial_count ( int ) – The initial count for the generator.

Raises :

ValueError – If initial_count is negative (< 0).

count

The count of IDs generated.

Returns :

int

generate ( self ) ClientOrderId

Return a unique client order ID.

Returns :

ClientOrderId

reset ( self ) void

Reset the ID generator.

All stateful fields are reset to their initial value.

set_count ( self , int count ) void

Set the internal counter to the given count.

Parameters :

count ( int ) – The count to set.

class IdentifierGenerator ( TraderId trader_id , Clock clock )

Bases: object

Provides a generator for unique ID strings.

class PositionIdGenerator ( TraderId trader_id , Clock clock )

Bases: IdentifierGenerator

Provides a generator for unique PositionId(s).

Parameters :

trader_id ( TraderId ) – The trader ID tag for the generator.

generate ( self , StrategyId strategy_id , bool flipped=False ) PositionId

Return a unique position ID.

Parameters :
  • strategy_id ( StrategyId ) – The strategy ID associated with the position.

  • flipped ( bool ) – If the position is being flipped. If True then the generated id will be appended with ‘F’.

Returns :

PositionId

get_count ( self , StrategyId strategy_id ) int

Return the internal position count for the given strategy ID.

Parameters :

strategy_id ( StrategyId ) – The strategy ID associated with the count.

Returns :

int

reset ( self ) void

Reset the ID generator.

All stateful fields are reset to their initial value.

set_count ( self , StrategyId strategy_id , int count ) void

Set the internal position count for the given strategy ID.

Parameters :
  • strategy_id ( StrategyId ) – The strategy ID associated with the count.

  • count ( int ) – The count to set.

Raises :

ValueError – If count is negative (< 0).

Logging

class LiveLogger ( loop , LiveClock clock , TraderId trader_id=None , unicode machine_id=None , UUID4 instance_id=None , LogLevel level_stdout=LogLevel.INFO , bool bypass=False , int maxsize=10000 )

Bases: Logger

Provides a high-performance logger which runs on the event loop.

Parameters :
  • loop ( asyncio.AbstractEventLoop ) – The event loop to run the logger on.

  • clock ( LiveClock ) – The clock for the logger.

  • trader_id ( TraderId , optional ) – The trader ID for the logger.

  • machine_id ( str , optional ) – The machine ID for the logger.

  • instance_id ( UUID4 , optional ) – The systems unique instantiation ID.

  • level_stdout ( LogLevel ) – The minimum log level for logging messages to stdout.

  • bypass ( bool ) – If the logger should be bypassed.

  • maxsize ( int , optional ) – The maximum capacity for the log queue.

change_clock ( self , Clock clock ) void

Change the loggers internal clock to the given clock.

Parameters :

clock ( Clock ) –

get_run_task ( self ) asyncio.Task

Return the internal run queue task for the engine.

Returns :

asyncio.Task

instance_id

Return the loggers system instance ID.

Returns :

UUID4

is_bypassed

Return whether the logger is in bypass mode.

Returns :

bool

is_running

Return whether the logger is running.

Returns :

bool

last_blocked

Return the timestamp (UTC) the logger last blocked.

Returns :

datetime or None

machine_id

Return the loggers machine ID.

Returns :

str

register_sink ( self , handler : Callable [ [ dict ] , None ] ) void

Register the given sink handler with the logger.

Parameters :

handler ( Callable [ [ dict ] , None ] ) – The sink handler to register.

Raises :

KeyError – If handler already registered.

start ( self ) void

Start the logger on a running event loop.

stop ( self ) void

Stop the logger by cancelling the internal event loop task.

Future messages sent to the logger will be passed directly to the Logger base class for logging.

trader_id

Return the loggers trader ID.

Returns :

TraderId

class Logger ( Clock clock , TraderId trader_id=None , unicode machine_id=None , UUID4 instance_id=None , LogLevel level_stdout=LogLevel.INFO , bool bypass=False )

Bases: object

Provides a high-performance logger.

Parameters :
  • clock ( Clock ) – The clock for the logger.

  • trader_id ( TraderId , optional ) – The trader ID for the logger.

  • machine_id ( str , optional ) – The machine ID.

  • instance_id ( UUID4 , optional ) – The instance ID.

  • level_stdout ( LogLevel ) – The minimum log level for logging messages to stdout.

  • bypass ( bool ) – If the logger should be bypassed.

change_clock ( self , Clock clock ) void

Change the loggers internal clock to the given clock.

Parameters :

clock ( Clock ) –

instance_id

Return the loggers system instance ID.

Returns :

UUID4

is_bypassed

Return whether the logger is in bypass mode.

Returns :

bool

machine_id

Return the loggers machine ID.

Returns :

str

register_sink ( self , handler : Callable [ [ dict ] , None ] ) void

Register the given sink handler with the logger.

Parameters :

handler ( Callable [ [ dict ] , None ] ) – The sink handler to register.

Raises :

KeyError – If handler already registered.

trader_id

Return the loggers trader ID.

Returns :

TraderId

class LoggerAdapter ( unicode component_name , Logger logger )

Bases: object

Provides an adapter for a components logger.

Parameters :
  • component_name ( str ) – The name of the component.

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

component

Return the loggers component name.

Returns :

str

critical ( self , unicode msg , LogColor color=LogColor.RED , dict annotations=None ) void

Log the given critical message with the logger.

Parameters :
  • msg ( str ) – The message to log.

  • color ( LogColor , optional ) – The color for the log record.

  • annotations ( dict [ str , object ] , optional ) – The annotations for the log record.

debug ( self , unicode msg , LogColor color=LogColor.NORMAL , dict annotations=None ) void

Log the given debug message with the logger.

Parameters :
  • msg ( str ) – The message to log.

  • color ( LogColor , optional ) – The color for the log record.

  • annotations ( dict [ str , object ] , optional ) – The annotations for the log record.

error ( self , unicode msg , LogColor color=LogColor.RED , dict annotations=None ) void

Log the given error message with the logger.

Parameters :
  • msg ( str ) – The message to log.

  • color ( LogColor , optional ) – The color for the log record.

  • annotations ( dict [ str , object ] , optional ) – The annotations for the log record.

exception ( self , unicode msg , ex , dict annotations=None ) void

Log the given exception including stack trace information.

Parameters :
  • msg ( str ) – The message to log.

  • ex ( Exception ) – The exception to log.

  • annotations ( dict [ str , object ] , optional ) – The annotations for the log record.

get_logger ( self ) Logger

Return the encapsulated logger.

Returns :

Logger

info ( self , unicode msg , LogColor color=LogColor.NORMAL , dict annotations=None ) void

Log the given information message with the logger.

Parameters :
  • msg ( str ) – The message to log.

  • color ( LogColor , optional ) – The color for the log record.

  • annotations ( dict [ str , object ] , optional ) – The annotations for the log record.

instance_id

Return the loggers system instance ID.

Returns :

UUID4

is_bypassed

Return whether the logger is in bypass mode.

Returns :

str

machine_id

Return the loggers machine ID.

Returns :

str

trader_id

Return the loggers trader ID.

Returns :

TraderId

warning ( self , unicode msg , LogColor color=LogColor.YELLOW , dict annotations=None ) void

Log the given warning message with the logger.

Parameters :
  • msg ( str ) – The message to log.

  • color ( LogColor , optional ) – The color for the log record.

  • annotations ( dict [ str , object ] , optional ) – The annotations for the log record.

log_memory ( LoggerAdapter logger ) void
nautilus_header ( LoggerAdapter logger ) void

Providers

class InstrumentProvider ( venue : Venue , logger : Logger , config : Optional [ InstrumentProviderConfig ] = None )

Bases: object

The abstract base class for all instrument providers.

Parameters :

Warning

This class should not be used directly, but through a concrete subclass.

property venue : Venue

Return the providers venue.

Returns :

Venue

property count : int

Return the count of instruments held by the provider.

Returns :

int

async load_all_async ( filters : Optional [ dict ] = None ) None

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

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 .

async load_async ( instrument_id : 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 .

async initialize ( ) None

Initialize the instrument provider.

If initialize() then will immediately return.

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.

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.

load ( instrument_id : 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.

add_currency ( currency :