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.
class Controller
Bases: Actor
The base class for all trader controllers.
- Parameters:
- trader (Trader) – The reference to the trader instance to control.
- config (ActorConfig , optional) – The configuration for the controller
- Raises: TypeError – If config is not of type ActorConfig.
create_actor(actor: Actor, start: bool = True) → None
Add the given actor to the controlled trader.
- Parameters:
- actor (Actor) – The actor to add.
- start (bool , default True) – If the actor should be started immediately.
- Raises:
- ValueError – If actor.state is
RUNNING
orDISPOSED
. - RuntimeError – If actor is already registered with the trader.
- ValueError – If actor.state is
create_strategy(strategy: Strategy, start: bool = True) → None
Add the given strategy to the controlled trader.
- Parameters:
- strategy (Strategy) – The strategy to add.
- start (bool , default True) – If the strategy should be started immediately.
- Raises:
- ValueError – If strategy.state is
RUNNING
orDISPOSED
. - RuntimeError – If strategy is already registered with the trader.
- ValueError – If strategy.state is
start_actor(actor: Actor) → None
Start the given actor.
Will log a warning if the actor is already RUNNING
.
- Raises: ValueError – If actor is not already registered with the trader.
start_strategy(strategy: Strategy) → None
Start the given strategy.
Will log a warning if the strategy is already RUNNING
.
- Raises: ValueError – If strategy is not already registered with the trader.
stop_actor(actor: Actor) → None
Stop the given actor.
Will log a warning if the actor is not RUNNING
.
- Parameters: actor (Actor) – The actor to stop.
- Raises: ValueError – If actor is not already registered with the trader.
stop_strategy(strategy: Strategy) → None
Stop the given strategy.
Will log a warning if the strategy is not RUNNING
.
- Parameters: strategy (Strategy) – The strategy to stop.
- Raises: ValueError – If strategy is not already registered with the trader.
remove_actor(actor: Actor) → None
Remove the given actor.
Will stop the actor first if state is RUNNING
.
- Parameters: actor (Actor) – The actor to remove.
- Raises: ValueError – If actor is not already registered with the trader.
remove_strategy(strategy: Strategy) → None
Remove the given strategy.
Will stop the strategy first if state is RUNNING
.
- Parameters: strategy (Strategy) – The strategy to remove.
- Raises: ValueError – If strategy is not already registered with the trader.
class Strategy
Bases: Actor
Strategy(config: StrategyConfig | None = None) 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:
: - UNSPECIFIED
: 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 be a single position for the strategy per instrument. The position ID naming convention is {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.
- Do not call components such as clock and logger in the __init__ prior to registration.
cancel_all_orders(self, InstrumentId instrument_id, OrderSide order_side=OrderSide.NO_ORDER_SIDE, ClientId client_id=None) → void
Cancel all orders for this strategy for the given instrument ID.
A CancelAllOrders command will be created and then sent to both the OrderEmulator and the ExecutionEngine.
- Parameters:
- instrument_id (InstrumentId) – The instrument for the orders to cancel.
- order_side (OrderSide, default
NO_ORDER_SIDE
(both sides)) – The side of 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_gtd_expiry(self, Order order) → void
Cancel the managed GTD expiry for the given order.
If there is no current GTD expiry timer, then an error will be logged.
- Parameters: order (Order) – The order to cancel the GTD expiry for.
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 either the OrderEmulator or the ExecutionEngine (depending on whether the order is emulated).
- Parameters:
cancel_orders(self, list orders, ClientId client_id=None) → void
Batch cancel the given list of orders with optional routing instructions.
For each order in the list, a CancelOrder command will be created and added to a BatchCancelOrders command. This command is then sent to the ExecutionEngine.
Logs an error if the orders list contains local/emulated orders.
- Parameters:
- Raises:
- ValueError – If orders is empty.
- TypeError – If orders contains a type other than Order.
change_id(self, StrategyId strategy_id) → void
Change the strategies identifier to the given strategy_id.
- Parameters: strategy_id (StrategyId) – The new strategy ID to change to.
change_order_id_tag(self, str order_id_tag) → void
Change the order identifier tag to the given order_id_tag.
- Parameters: order_id_tag (str) – The new order ID tag to change to.
close_all_positions(self, InstrumentId instrument_id, PositionSide position_side=PositionSide.NO_POSITION_SIDE, ClientId client_id=None, list tags=None, bool reduce_only=True) → void
Close all positions for the given instrument ID for this strategy.
- Parameters:
- instrument_id (InstrumentId) – The instrument for the positions to close.
- position_side (PositionSide, default
NO_POSITION_SIDE
(both sides)) – The side of 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 (list *[*str ] , optional) – The tags for the market orders closing the positions.
- reduce_only (bool , default True) – If the market orders to close positions should carry the ‘reduce-only’ execution instruction. Optional, as not all venues support this feature.
close_position(self, Position position, ClientId client_id=None, list tags=None, bool reduce_only=True) → 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 (list *[*str ] , optional) – The tags for the market order closing the position.
- reduce_only (bool , default True) – If the market order to close the position should carry the ‘reduce-only’ execution instruction. Optional, as not all venues support this feature.
event_logging
If event logging should be enabled for the strategy.
- Returns: bool
external_order_claims
The external order claims instrument IDs for the strategy.
- Returns: list[InstrumentId]
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).
manage_contingent_orders
If contingent orders should be managed automatically by the strategy.
- Returns: bool
manage_gtd_expiry
If all order GTD time in force expirations should be managed automatically by the strategy.
- Returns: bool
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 will be created and then sent to either the OrderEmulator or the RiskEngine (depending on whether the order is emulated).
At least one value 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 for the API, then will cancel and 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 price is not
None
and order does not have a price. - ValueError – If trigger is not
None
and order does not have a trigger_price.
- ValueError – If price is not
WARNING
If the order is already closed or at PENDING_CANCEL status then the command will not be generated, and a warning will be logged.
oms_type
The order management system for the strategy.
- Returns: OmsType
on_order_accepted(self, OrderAccepted event) → void
Actions to be performed when running and receives an order accepted event.
- Parameters: event (OrderAccepted) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_cancel_rejected(self, OrderCancelRejected event) → void
Actions to be performed when running and receives an order cancel rejected event.
- Parameters: event (OrderCancelRejected) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_canceled(self, OrderCanceled event) → void
Actions to be performed when running and receives an order canceled event.
- Parameters: event (OrderCanceled) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_denied(self, OrderDenied event) → void
Actions to be performed when running and receives an order denied event.
- Parameters: event (OrderDenied) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_emulated(self, OrderEmulated event) → void
Actions to be performed when running and receives an order initialized event.
- Parameters: event (OrderEmulated) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_event(self, OrderEvent event) → void
Actions to be performed when running and receives an order event.
- Parameters: event (OrderEvent) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_expired(self, OrderExpired event) → void
Actions to be performed when running and receives an order expired event.
- Parameters: event (OrderExpired) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_filled(self, OrderFilled event) → void
Actions to be performed when running and receives an order filled event.
- Parameters: event (OrderFilled) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_initialized(self, OrderInitialized event) → void
Actions to be performed when running and receives an order initialized event.
- Parameters: event (OrderInitialized) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_modify_rejected(self, OrderModifyRejected event) → void
Actions to be performed when running and receives an order modify rejected event.
- Parameters: event (OrderModifyRejected) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_pending_cancel(self, OrderPendingCancel event) → void
Actions to be performed when running and receives an order pending cancel event.
- Parameters: event (OrderPendingCancel) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_pending_update(self, OrderPendingUpdate event) → void
Actions to be performed when running and receives an order pending update event.
- Parameters: event (OrderPendingUpdate) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_rejected(self, OrderRejected event) → void
Actions to be performed when running and receives an order rejected event.
- Parameters: event (OrderRejected) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_released(self, OrderReleased event) → void
Actions to be performed when running and receives an order released event.
- Parameters: event (OrderReleased) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_submitted(self, OrderSubmitted event) → void
Actions to be performed when running and receives an order submitted event.
- Parameters: event (OrderSubmitted) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_triggered(self, OrderTriggered event) → void
Actions to be performed when running and receives an order triggered event.
- Parameters: event (OrderTriggered) – The event received.
WARNING
System method (not intended to be called by user code).
on_order_updated(self, OrderUpdated event) → void
Actions to be performed when running and receives an order updated event.
- Parameters: event (OrderUpdated) – The event received.
WARNING
System method (not intended to be called by user code).
on_position_changed(self, PositionChanged event) → void
Actions to be performed when running and receives a position changed event.
- Parameters: event (PositionChanged) – The event received.
WARNING
System method (not intended to be called by user code).
on_position_closed(self, PositionClosed event) → void
Actions to be performed when running and receives a position closed event.
- Parameters: event (PositionClosed) – The event received.
WARNING
System method (not intended to be called by user code).
on_position_event(self, PositionEvent event) → void
Actions to be performed when running and receives a position event.
- Parameters: event (PositionEvent) – The event received.
WARNING
System method (not intended to be called by user code).
on_position_opened(self, PositionOpened event) → void
Actions to be performed when running and receives a position opened event.
- Parameters: event (PositionOpened) – The event received.
WARNING
System method (not intended to be called by user code).
on_reset(self) → void
on_resume(self) → void
on_start(self) → void
on_stop(self) → void
order_factory
The order factory for the strategy.
- Returns: OrderFactory
order_id_tag
The order ID tag for the strategy.
- Returns: str
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:
register(self, TraderId trader_id, PortfolioFacade portfolio, MessageBus msgbus, CacheFacade cache, Clock clock) → 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.
WARNING
System method (not intended to be called by user code).
submit_order(self, Order order, PositionId position_id=None, ClientId client_id=None) → void
Submit the given order with optional position ID, execution algorithm and routing instructions.
A SubmitOrder command will be created and sent to either an ExecAlgorithm, the OrderEmulator or the RiskEngine (depending whether the order is emulated and/or has an exec_algorithm_id specified).
If the client order ID is duplicate, then the order will be denied.
- Parameters:
- order (Order) – The order to submit.
- position_id (PositionId , optional) – The position ID to submit the order against. If a position does not yet exist, then any position opened will have this identifier assigned.
- client_id (ClientId , optional) – The specific execution client ID for the command.
If
None
then will be inferred from the venue in the instrument ID.
- Raises:
ValueError – If order.status is not
INITIALIZED
.
WARNING
If a position_id is passed and a position does not yet exist, then any position opened by the order will have this position ID assigned. This may not be what you intended.
submit_order_list(self, OrderList order_list, PositionId position_id=None, ClientId client_id=None) → void
Submit the given order list with optional position ID, execution algorithm and routing instructions.
A SubmitOrderList command with be created and sent to either the OrderEmulator, or the RiskEngine (depending whether an order is emulated).
If the order list ID is duplicate, or any client order ID is duplicate, then all orders will be denied.
- Parameters:
- order_list (OrderList) – The order list to submit.
- position_id (PositionId , optional) – The position ID to submit the order against. If a position does not yet exist, then any position opened will have this identifier assigned.
- client_id (ClientId , optional) – The specific execution client ID for the command.
If
None
then will be inferred from the venue in the instrument ID.
- Raises:
ValueError – If any order.status is not
INITIALIZED
.
WARNING
If a position_id is passed and a position does not yet exist, then any position opened by an order will have this position ID assigned. This may not be what you intended.
to_importable_config(self) → ImportableStrategyConfig
Returns an importable configuration for this strategy.
- Return type: ImportableStrategyConfig
class Trader
Bases: Component
Provides a trader for managing a fleet of actors, execution algorithms and trading strategies.
- Parameters:
- trader_id (TraderId) – The ID for the trader.
- instance_id (UUID4) – The instance 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.
- has_controller (bool , default False) – If the trader has a controller.
- loop (asyncio.AbstractEventLoop , optional) – The event loop 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.
property instance_id : UUID4
Return the traders instance ID.
- Return type: UUID4
actors() → list[Actor]
Return the actors loaded in the trader.
- Return type: list[Actor]
strategies() → list[Strategy]
Return the strategies loaded in the trader.
- Return type: list[Strategy]
exec_algorithms() → list[Any]
Return the execution algorithms loaded in the trader.
- Return type: list[ExecAlgorithms]
actor_ids() → list[ComponentId]
Return the actor IDs loaded in the trader.
- Return type: list[ComponentId]
strategy_ids() → list[StrategyId]
Return the strategy IDs loaded in the trader.
- Return type: list[StrategyId]
exec_algorithm_ids() → list[ExecAlgorithmId]
Return the execution algorithm IDs loaded in the trader.
- Return type: list[ExecAlgorithmId]
actor_states() → dict[ComponentId, str]
Return the traders actor states.
- Return type: dict[ComponentId, str]
strategy_states() → dict[StrategyId, str]
Return the traders strategy states.
- Return type: dict[StrategyId, str]
exec_algorithm_states() → dict[ExecAlgorithmId, str]
Return the traders execution algorithm states.
- Return type: dict[ExecAlgorithmId, str]
add_actor(actor: Actor) → None
Add the given custom component to the trader.
- Parameters: actor (Actor) – The actor to add and register.
- Raises:
- ValueError – If actor.state is
RUNNING
orDISPOSED
. - RuntimeError – If actor.id already exists in the trader.
- ValueError – If actor.state is
add_actors(actors: list[Actor]) → None
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_strategy(strategy: Strategy) → None
Add the given trading strategy to the trader.
- Parameters: strategy (Strategy) – The trading strategy to add and register.
- Raises:
- ValueError – If strategy.state is
RUNNING
orDISPOSED
. - RuntimeError – If strategy.id already exists in the trader.
- ValueError – If strategy.state is
add_strategies(strategies: list[Strategy]) → None
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_exec_algorithm(exec_algorithm: Any) → None
Add the given execution algorithm to the trader.
- Parameters: exec_algorithm (ExecAlgorithm) – The execution algorithm to add and register.
- Raises:
- KeyError – If exec_algorithm.id already exists in the trader.
- ValueError – If exec_algorithm.state is
RUNNING
orDISPOSED
.
add_exec_algorithms(exec_algorithms: list[Any]) → None
Add the given execution algorithms to the trader.
- Parameters: exec_algorithms (list [ExecAlgorithm ]) – The execution algorithms to add and register.
- Raises:
ValueError – If exec_algorithms is
None
or empty.