Trading

The trading subpackage groups all trading domain specific components and tooling.

This is a top-level package where the majority of users will interface with the framework. Custom trading strategies can be implemented by inheriting from the Strategy base class.

Filters

class EconomicNewsEventFilter ( list currencies , list impacts , news_data: pd.DataFrame )

Bases: object

Provides methods to help filter trading strategy rules based on economic news events.

Parameters
  • currencies ( list [ str ] ) – The list of three letter currency codes to filter.

  • impacts ( list [ str ] ) – The list of impact levels to filter (‘LOW’, ‘MEDIUM’, ‘HIGH’).

  • news_data ( pd.DataFrame ) – The economic news data.

currencies

Return the currencies the data is filtered on.

Returns

list[str]

impacts

Return the news impacts the data is filtered on.

Returns

list[str]

next_event ( self , datetime time_now ) NewsEvent

Return the next news event matching the filter conditions. Will return None if no news events match the filter conditions.

Parameters

time_now ( datetime ) –

Returns

NewsEvent or None – The next news event in the filtered data if any.

Raises
  • ValueError – The time_now < self.unfiltered_data_start .

  • ValueError – The time_now > self.unfiltered_data_end .

  • ValueError – If time_now is not tz aware UTC.

prev_event ( self , datetime time_now ) NewsEvent

Return the previous news event matching the initial filter conditions. Will return None if no news events match the filter conditions.

Parameters

time_now ( datetime ) –

Returns

NewsEvent or None – The previous news event in the filtered data if any.

Raises
  • ValueError – The time_now < self.unfiltered_data_start .

  • ValueError – The time_now > self.unfiltered_data_end .

  • ValueError – If time_now is not tz aware UTC.

unfiltered_data_end

Return the end of the raw data.

Returns

datetime

unfiltered_data_start

Return the start of the raw data.

Returns

datetime

class ForexSession ( value )

Bases: enum.Enum

An enumeration.

class ForexSessionFilter

Bases: object

Provides methods to help filter trading strategy rules dependent on Forex session times.

local_from_utc ( self , session: ForexSession , datetime time_now ) datetime

Return the local datetime from the given session and time_now (UTC).

Parameters
  • session ( ForexSession ) – The session for the local timezone conversion.

  • time_now ( datetime ) – The time now (UTC).

Returns

datetime – The converted local datetime.

Raises

ValueError – If time_now is not tz aware UTC.

next_end ( self , session: ForexSession , datetime time_now ) datetime

Return the next session end.

All FX sessions run Monday to Friday local time.

Sydney Session 0700-1600 ‘Australia/Sydney’

Tokyo Session 0900-1800 ‘Asia/Tokyo’

London Session 0800-1600 ‘Europe/London’

New York Session 0800-1700 ‘America/New_York’

Parameters
  • session ( ForexSession ) – The session for the end datetime.

  • time_now ( datetime ) – The datetime now (UTC).

Returns

datetime

Raises

ValueError – If time_now is not tz aware UTC.

next_start ( self , session: ForexSession , datetime time_now ) datetime

Return the next session start.

All FX sessions run Monday to Friday local time.

Sydney Session 0700-1600 ‘Australia/Sydney’

Tokyo Session 0900-1800 ‘Asia/Tokyo’

London Session 0800-1600 ‘Europe/London’

New York Session 0800-1700 ‘America/New_York’

Parameters
  • session ( ForexSession ) – The session for the start datetime.

  • time_now ( datetime ) – The datetime now.

Returns

datetime

Raises

ValueError – If time_now is not tz aware UTC.

prev_end ( self , session: ForexSession , datetime time_now ) datetime

Return the previous sessions end.

All FX sessions run Monday to Friday local time.

Sydney Session 0700-1600 ‘Australia/Sydney’

Tokyo Session 0900-1800 ‘Asia/Tokyo’

London Session 0800-1600 ‘Europe/London’

New York Session 0800-1700 ‘America/New_York’

Parameters
  • session ( ForexSession ) – The session for end datetime.

  • time_now ( datetime ) – The datetime now.

Returns

datetime

Raises

ValueError – If time_now is not tz aware UTC.

prev_start ( self , session: ForexSession , datetime time_now ) datetime

Return the previous session start.

All FX sessions run Monday to Friday local time.

Sydney Session 0700-1600 ‘Australia/Sydney’

Tokyo Session 0900-1800 ‘Asia/Tokyo’

London Session 0800-1600 ‘Europe/London’

New York Session 0800-1700 ‘America/New_York’

Parameters
  • session ( ForexSession ) – The session for the start datetime.

  • time_now ( datetime ) – The datetime now.

Returns

datetime

Raises

ValueError – If time_now is not tz aware UTC.

class NewsEvent ( impact: NewsImpact , unicode name , Currency currency , uint64_t ts_event , uint64_t ts_init )

Bases: nautilus_trader.core.data.Data

Represents an economic news event.

Parameters
  • impact ( NewsImpact ) – The expected impact for the economic news event.

  • name ( str ) – The name of the economic news event.

  • currency ( Currency ) – The currency the economic news event is expected to affect.

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

  • ts_init ( uint64_t ) – The UNIX timestamp (nanoseconds) when the data object was initialized.

currency

The currency affected by the news event.

Returns

Currency

classmethod fully_qualified_name ( type cls ) str

Return the fully qualified name for the Data class.

Returns

str

References

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

impact

The expected news impact.

Returns

Enum

name

The descriptive name of the news event.

Returns

str

ts_event

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

Returns

uint64_t

ts_init

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

Returns

uint64_t

class NewsImpact ( value )

Bases: enum.Enum

An enumeration.

Strategy

This module defines a trading strategy class which allows users to implement their own customized trading strategies

A user can inherit from Strategy 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 strategies to a Trader so that they can be fully “wired” into the platform. Exceptions will be raised if a Strategy attempts to operate without a managing Trader instance.

class Strategy ( config : Optional [ StrategyConfig ] = None )

Bases: nautilus_trader.common.actor.Actor

The base class for all trading strategies.

This class allows traders to implement their own customized trading strategies. A trading strategy can configure its own order management system type, which determines how positions are handled by the ExecutionEngine .

Strategy OMS (Order Management System) types:
  • NONE : No specific type has been configured, will therefore default to the native OMS type for each venue.

  • HEDGING : A position ID will be assigned for each new position which is opened per instrument.

  • NETTING : There will only ever be a single position for the strategy per instrument. The position ID will be {instrument_id}-{strategy_id} .

Parameters

config ( StrategyConfig , optional ) – The trading strategy configuration.

Raises

TypeError – If config is not of type StrategyConfig .

Warning

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

cache

The read-only cache for the actor.

Returns

CacheFacade

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

Cancel all orders for this strategy for the given instrument ID.

Parameters
  • instrument_id ( InstrumentId ) – The instrument for the orders to cancel.

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

cancel_order ( self , Order order , ClientId client_id=None ) void

Cancel the given order with optional routing instructions.

A CancelOrder command will be created and then sent to the ExecutionEngine .

Logs an error if no VenueOrderId has been assigned to the order.

Parameters
  • order ( Order ) – The order to cancel.

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

clock

The actors clock.

Returns

Clock

close_all_positions ( self , InstrumentId instrument_id , ClientId client_id=None , unicode tags=None ) void

Close all positions for the given instrument ID for this strategy.

Parameters
  • instrument_id ( InstrumentId ) – The instrument for the positions to close.

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

  • tags ( str , optional ) – The tags for the market orders closing the positions.

close_position ( self , Position position , ClientId client_id=None , unicode tags=None ) void

Close the given position.

A closing MarketOrder for the position will be created, and then sent to the ExecutionEngine via a SubmitOrder command.

Parameters
  • position ( Position ) – The position to close.

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

  • tags ( str , optional ) – The tags for the market order closing the position.

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 , bool is_historical=False ) void

Handle the given bar data.

Calls on_bar if state is RUNNING .

Parameters
  • bar ( Bar ) – The bar received.

  • is_historical ( bool ) – If bar is historical then it won’t be passed to on_bar .

Warning

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

handle_bars ( self , list bars ) void

Handle the given 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.

Calls on_data if state is RUNNING .

Parameters

data ( Data ) – The received data.

Warning

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

handle_event ( self , Event event ) void

Handle the given event.

Calls on_event if state is RUNNING .

Parameters

event ( Event ) – The received event.

Warning

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

handle_instrument ( self , Instrument instrument ) void

Handle the given instrument.

Calls on_instrument if state is RUNNING .

Parameters

instrument ( Instrument ) – The received instrument.

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.

Calls on_instrument_close_price if .state is RUNNING .

Parameters

update ( InstrumentClosePrice ) – The received update.

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.

Calls on_instrument_status_update if state is RUNNING .

Parameters

update ( InstrumentStatusUpdate ) – The received update.

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.

Calls on_order_book if state is RUNNING .

Parameters

order_book ( OrderBook ) – The received order book.

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.

Calls 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 , bool is_historical=False ) void

Handle the given tick.

Calls on_quote_tick if state is RUNNING .

Parameters
  • tick ( QuoteTick ) – The received tick.

  • is_historical ( bool ) – If tick is historical then it won’t be passed to on_quote_tick .

Warning

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

handle_quote_ticks ( self , list ticks ) void

Handle the given tick data by handling each tick individually.

Parameters

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

Warning

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

handle_ticker ( self , Ticker ticker , bool is_historical=False ) void

Handle the given ticker.

Calls on_ticker if state is RUNNING .

Parameters
  • ticker ( Ticker ) – The received ticker.

  • is_historical ( bool ) – If ticker is historical then it won’t be passed to on_ticker .

Warning

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

handle_trade_tick ( self , TradeTick tick , bool is_historical=False ) void

Handle the given tick.

Calls on_trade_tick if state is RUNNING .

Parameters
  • tick ( TradeTick ) – The received trade tick.

  • is_historical ( bool ) – If tick is historical then it won’t be passed to on_trade_tick .

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 received ticks.

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.

Calls on_venue_status_update if state is RUNNING .

Parameters

update ( VenueStatusUpdate ) – The received update.

Warning

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

id

The components ID.

Returns

ComponentId

indicators_initialized ( self ) bool

Return a value indicating whether all indicators are initialized.

Returns

bool – True if all initialized, else False

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

load ( self , dict state ) void

Load the strategy state from the give state dictionary.

Calls on_load and passes the state.

Parameters

state ( dict [ str , object ] ) – The state dictionary.

Raises

RuntimeError – If strategy is not registered with a trader.

Warning

Exceptions raised will be caught, logged, and reraised.

log

The actors logger.

Returns

LoggerAdapter

modify_order ( self , Order order , Quantity quantity=None , Price price=None , Price trigger_price=None , ClientId client_id=None ) void

Modify the given order with optional parameters and routing instructions.

An ModifyOrder command is created and then sent to the ExecutionEngine . Either one or both values must differ from the original order for the command to be valid.

Will use an Order Cancel/Replace Request (a.k.a Order Modification) for FIX protocols, otherwise if order update is not available with the API, then will cancel - then replace with a new order using the original ClientOrderId .

Parameters
  • order ( Order ) – The order to update.

  • quantity ( Quantity , optional ) – The updated quantity for the given order.

  • price ( Price , optional ) – The updated price for the given order (if applicable).

  • trigger_price ( Price , optional ) – The updated trigger price for the given order (if applicable).

  • 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 trigger is not None and order.type != STOP_LIMIT .

References

https://www.onixs.biz/fix-dictionary/5.0.SP2/msgType_G_71.html

msgbus

The message bus for the actor (if registered).

Returns

MessageBus or None

oms_type

The order management system for the strategy.

Returns

OMSType

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_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_load ( self , dict state ) void

Actions to be performed when the strategy is loaded.

Saved state values will be contained in the give state dictionary.

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_save ( self ) dict

Actions to be performed when the strategy is saved.

Create and return a state dictionary of values to be saved.

Returns

dict[str, bytes] – The strategy state dictionary.

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

order_factory

The order factory for the strategy.

Returns

OrderFactory

portfolio

The read-only portfolio for the strategy.

Returns

PortfolioFacade

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 , bool stream=False ) 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.

  • stream ( bool , default False ) – If the signal should also be streamed for persistence.

query_order ( self , Order order , ClientId client_id=None ) void

query the given order with optional routing instructions.

A QueryOrder command will be created and then sent to the ExecutionEngine .

Logs an error if no VenueOrderId has been assigned to the order.

Parameters
  • order ( Order ) – The order to query.

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

register ( self , TraderId trader_id , PortfolioFacade portfolio , MessageBus msgbus , CacheFacade cache , Clock clock , Logger logger ) void

Register the strategy with a trader.

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

  • portfolio ( PortfolioFacade ) – The read-only portfolio for the strategy.

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

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

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

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

Warning

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

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_indicator_for_bars ( self , BarType bar_type , Indicator indicator ) void

Register the given indicator with the strategy to receive bar data for the given bar type.

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

  • indicator ( Indicator ) – The indicator to register.

register_indicator_for_quote_ticks ( self , InstrumentId instrument_id , Indicator indicator ) void

Register the given indicator with the strategy to receive quote tick data for the given instrument ID.

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

  • indicator ( Indicator ) – The indicator to register.

register_indicator_for_trade_ticks ( self , InstrumentId instrument_id , Indicator indicator ) void

Register the given indicator with the strategy to receive trade tick data for the given instrument ID.

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

  • indicator ( indicator ) – The indicator to register.

register_warning_event ( self , type event ) void

Register the given event type for warning log levels.

Parameters

event ( type ) – The event class to register.

registered_indicators

Return the registered indicators for the strategy.

Returns

list[Indicator]

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

save ( self ) dict

Return the strategy state dictionary to be saved.

Calls on_save .

Raises

RuntimeError – If strategy is not registered with a trader.

Warning

Exceptions raised will be caught, logged, and reraised.

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.

submit_order ( self , Order order , PositionId position_id=None , ClientId client_id=None , bool check_position_exists=True ) void

Submit the given order with optional position ID and routing instructions.

A SubmitOrder command will be created and then sent to the ExecutionEngine .

Parameters
  • order ( Order ) – The order to submit.

  • position_id ( PositionId , optional ) – The position ID to submit the order against.

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

  • check_position_exists ( bool , default True ) – If a position is checked to exist for any given position ID.

submit_order_list ( self , OrderList order_list , ClientId client_id=None ) void

Submit the given order list.

A SubmitOrderList command with be created and sent to the ExecutionEngine .

Parameters
  • order_list ( OrderList ) – The order list to submit.

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

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 ) ImportableStrategyConfig

Returns an importable configuration for this strategy.

Returns

ImportableStrategyConfig

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.

Trader

The Trader class is intended to manage a portfolio of trading strategies within a running instance of the platform.

A running instance could be either a test/backtest or live implementation - the Trader will operate in the same way.

class Trader ( TraderId trader_id , MessageBus msgbus , Cache cache , Portfolio portfolio , DataEngine data_engine , RiskEngine risk_engine , ExecutionEngine exec_engine , Clock clock , Logger logger , dict config=None )

Bases: nautilus_trader.common.component.Component

Provides a trader for managing a portfolio of trading strategies.

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

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

  • cache ( Cache ) – The cache for the trader.

  • portfolio ( Portfolio ) – The portfolio for the trader.

  • data_engine ( DataEngine ) – The data engine for the trader.

  • risk_engine ( RiskEngine ) – The risk engine for the trader.

  • exec_engine ( ExecutionEngine ) – The execution engine for the trader.

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

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

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

Raises
  • ValueError – If portfolio is not equal to the exec_engine portfolio.

  • ValueError – If strategies is None .

  • ValueError – If strategies is empty.

  • TypeError – If strategies contains a type other than Strategy .

actor_ids ( self ) list

Return the actor IDs loaded in the trader.

Returns

list[ComponentId]

actor_states ( self ) dict

Return the traders actor states.

Returns

dict[ComponentId, str]

add_actor ( self , Actor actor ) void

Add the given custom component to the trader.

Parameters

actor ( Actor ) – The actor to add and register.

Raises
  • KeyError – If component.id already exists in the trader.

  • ValueError – If component.state is RUNNING or DISPOSED .

add_actors ( self, list actors: [Actor] ) void

Add the given actors to the trader.

Parameters

actors ( list [ TradingStrategies ] ) – The actors to add and register.

Raises

ValueError – If actors is None or empty.

add_strategies ( self, list strategies: [Strategy] ) void

Add the given trading strategies to the trader.

Parameters

strategies ( list [ TradingStrategies ] ) – The trading strategies to add and register.

Raises

ValueError – If strategies is None or empty.

add_strategy ( self , Strategy strategy ) void

Add the given trading strategy to the trader.

Parameters

strategy ( Strategy ) – The trading strategy to add and register.

Raises
  • KeyError – If strategy.id already exists in the trader.

  • ValueError – If strategy.state is RUNNING or DISPOSED .

check_residuals ( self ) void

Check for residual open state such as open orders or open positions.

clear_actors ( self ) void

Dispose and clear all actors held by the trader.

Raises

ValueError – If state is RUNNING .

clear_strategies ( self ) void

Dispose and clear all strategies held by the trader.

Raises

ValueError – If state is RUNNING .

degrade ( self ) void

Degrade the component.

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

Warning

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

dispose ( self ) void

Dispose of the component.

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

Warning

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

fault ( self ) void

Fault the component.

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

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

Warning

Do not override.

If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.

classmethod fully_qualified_name ( type cls ) str

Return the fully qualified name for the components class.

Returns

str

References

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

generate_account_report ( self , Venue venue )

Generate an account report.

Returns

pd.DataFrame

generate_order_fills_report ( self )

Generate an order fills report.

Returns

pd.DataFrame

generate_orders_report ( self )

Generate an orders report.

Returns

pd.DataFrame

generate_positions_report ( self )

Generate a positions report.

Returns

pd.DataFrame

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

load ( self ) void

Load all strategy states from the execution 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.

save ( self ) void

Save all strategy states to the execution cache.

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.

strategy_ids ( self ) list

Return the strategy IDs loaded in the trader.

Returns

list[StrategyId]

strategy_states ( self ) dict

Return the traders strategy states.

Returns

dict[StrategyId, str]

subscribe ( self, unicode topic, handler: Callable[[Any], None] ) void

Subscribe to the given message topic with the given callback handler.

Parameters
  • topic ( str ) – The topic for the subscription. May include wildcard glob patterns.

  • handler ( Callable [ [ Any ] , None ] ) – The handler for the subscription.

trader_id

The trader ID associated with the component.

Returns

TraderId

type

The components type.

Returns

type

unsubscribe ( self, unicode topic, handler: Callable[[Any], None] ) void

Unsubscribe the given handler from the given message topic.

Parameters
  • topic ( str , optional ) – The topic to unsubscribe from. May include wildcard glob patterns.

  • handler ( Callable [ [ Any ] , None ] ) – The handler for the subscription.