Skip to content

Brokerage

QuantConnect.Brokerages.Brokerage

Brokerage(name: str)

Bases: Object, IBrokerage

Represents the base Brokerage implementation. This provides logging on brokerage events.

Creates a new Brokerage instance with the specified name

This codeEntityType is protected.

Parameters:

Name Type Description Default
name str

The name of the brokerage

required

order_id_changed

order_id_changed: _EventContainer[
    Callable[[Object, BrokerageOrderIdChangedEvent], Any],
    Any,
]

Event that fires each time the brokerage order id changes

orders_status_changed

orders_status_changed: _EventContainer[
    Callable[[Object, List[OrderEvent]], Any], Any
]

Event that fires each time the status for a list of orders change

order_updated

order_updated: _EventContainer[
    Callable[[Object, OrderUpdateEvent], Any], Any
]

Event that fires each time an order is updated in the brokerage side

option_position_assigned

option_position_assigned: _EventContainer[
    Callable[[Object, OrderEvent], Any], Any
]

Event that fires each time a short option position is assigned

option_notification

option_notification: _EventContainer[
    Callable[[Object, OptionNotificationEventArgs], Any],
    Any,
]

Event that fires each time an option position has changed

new_brokerage_order_notification

new_brokerage_order_notification: _EventContainer[
    Callable[
        [Object, NewBrokerageOrderNotificationEventArgs],
        Any,
    ],
    Any,
]

Event that fires each time there's a brokerage side generated order

delisting_notification

delisting_notification: _EventContainer[
    Callable[[Object, DelistingNotificationEventArgs], Any],
    Any,
]

Event that fires each time a delisting occurs

account_changed

account_changed: _EventContainer[
    Callable[[Object, AccountEvent], Any], Any
]

Event that fires each time a user's brokerage account is changed

message

message: _EventContainer[
    Callable[[Object, BrokerageMessageEvent], Any], Any
]

Event that fires when an error is encountered in the brokerage

name

name: str

Gets the name of the brokerage

is_connected

is_connected: bool

Returns true if we're currently connected to the broker

concurrency_enabled

concurrency_enabled: bool

Enables or disables concurrent processing of messages to and from the brokerage.

account_instantly_updated

account_instantly_updated: bool

Specifies whether the brokerage will instantly update account balances

account_base_currency

account_base_currency: str

Returns the brokerage account's base currency

last_sync_date

last_sync_date: datetime

Gets the date of the last sync (New York time zone)

This codeEntityType is protected.

last_sync_date_time_utc

last_sync_date_time_utc: datetime

Gets the datetime of the last sync (UTC)

lean_order_by_zero_cross_brokerage_order_id

lean_order_by_zero_cross_brokerage_order_id: (
    ConcurrentDictionary[str, Order]
)

A thread-safe dictionary that maps brokerage order IDs to their corresponding Order objects.

This codeEntityType is protected.

get_account_holdings

get_account_holdings(
    brokerage_data: Dictionary[str, str],
    securities: List[Security],
) -> List[Holding]
get_account_holdings() -> List[Holding]

Signature descriptions:

  • Helper method that will try to get the live holdings from the provided brokerage data collection else will default to the algorithm state

  • Gets all holdings for the account

Returns:

Type Description
List[Holding]

The current holdings from the account.

get_cash_balance

get_cash_balance(
    brokerage_data: Dictionary[str, str],
    cash_book: CashBook,
) -> List[CashAmount]
get_cash_balance() -> List[CashAmount]

Signature descriptions:

  • Helper method that will try to get the live cash balance from the provided brokerage data collection else will default to the algorithm state

  • Gets the current cash balance for each currency held in the brokerage account

Returns:

Type Description
List[CashAmount]

The current cash balance for each currency available for trading.

cancel_order

cancel_order(order: Order) -> bool

Cancels the order with the specified ID

Parameters:

Name Type Description Default
order Order

The order to cancel

required

Returns:

Type Description
bool

True if the request was made for the order to be canceled, false otherwise.

connect

connect() -> None

Connects the client to the broker's remote servers

disconnect

disconnect() -> None

Disconnects the client from the broker's remote servers

dispose

dispose() -> None

Dispose of the brokerage instance

get_history

get_history(request: HistoryRequest) -> Iterable[BaseData]

Gets the history for the requested security

Parameters:

Name Type Description Default
request HistoryRequest

The historical data request

required

Returns:

Type Description
Iterable[BaseData]

An enumerable of bars covering the span specified in the request.

get_open_orders

get_open_orders() -> List[Order]

Gets all open orders on the account. NOTE: The order objects returned do not have QC order IDs.

Returns:

Type Description
List[Order]

The open orders returned from IB.

get_order_position

get_order_position(
    order_direction: OrderDirection,
    holdings_quantity: float,
) -> OrderPosition

Gets the position that might result given the specified order direction and the current holdings quantity. This is useful for brokerages that require more specific direction information than provided by the OrderDirection enum (e.g. Tradier differentiates Buy/Sell and BuyToOpen/BuyToCover/SellShort/SellToClose)

This codeEntityType is protected.

Parameters:

Name Type Description Default
order_direction OrderDirection

The order direction

required
holdings_quantity float

The current holdings quantity

required

Returns:

Type Description
OrderPosition

The order position.

on_account_changed

on_account_changed(e: AccountEvent) -> None

Event invocator for the AccountChanged event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e AccountEvent

The AccountEvent

required

on_delisting_notification

on_delisting_notification(
    e: DelistingNotificationEventArgs,
) -> None

Event invocator for the DelistingNotification event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e DelistingNotificationEventArgs

The DelistingNotification event arguments

required

on_message

on_message(e: BrokerageMessageEvent) -> None

Event invocator for the Message event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e BrokerageMessageEvent

The error

required

on_new_brokerage_order_notification

on_new_brokerage_order_notification(
    e: NewBrokerageOrderNotificationEventArgs,
) -> None

Event invocator for the NewBrokerageOrderNotification event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e NewBrokerageOrderNotificationEventArgs

The NewBrokerageOrderNotification event arguments

required

on_option_notification

on_option_notification(
    e: OptionNotificationEventArgs,
) -> None

Event invocator for the OptionNotification event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e OptionNotificationEventArgs

The OptionNotification event arguments

required

on_option_position_assigned

on_option_position_assigned(e: OrderEvent) -> None

Event invocator for the OptionPositionAssigned event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e OrderEvent

The OrderEvent

required

on_order_event

on_order_event(e: OrderEvent) -> None

Event invocator for the OrderFilled event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e OrderEvent

The order event

required

on_order_events

on_order_events(order_events: List[OrderEvent]) -> None

Event invocator for the OrderFilled event

This codeEntityType is protected.

Parameters:

Name Type Description Default
order_events List[OrderEvent]

The list of order events

required

on_order_id_changed_event

on_order_id_changed_event(
    e: BrokerageOrderIdChangedEvent,
) -> None

Event invocator for the OrderIdChanged event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e BrokerageOrderIdChangedEvent

The BrokerageOrderIdChangedEvent

required

on_order_updated

on_order_updated(e: OrderUpdateEvent) -> None

Event invocator for the OrderUpdated event

This codeEntityType is protected.

Parameters:

Name Type Description Default
e OrderUpdateEvent

The update event

required

perform_cash_sync

perform_cash_sync(
    algorithm: IAlgorithm,
    current_time_utc: Union[datetime, date],
    get_time_since_last_fill: Callable[[], timedelta],
) -> bool

Synchronizes the cashbook with the brokerage account

Parameters:

Name Type Description Default
algorithm IAlgorithm

The algorithm instance

required
current_time_utc Union[datetime, date]

The current time (UTC)

required
get_time_since_last_fill Callable[[], timedelta]

A function which returns the time elapsed since the last fill

required

Returns:

Type Description
bool

True if the cash sync was performed successfully.

place_cross_zero_order

place_cross_zero_order(
    cross_zero_order_request: CrossZeroFirstOrderRequest,
    is_place_order_with_lean_event: bool = True,
) -> CrossZeroOrderResponse

Places an order that crosses zero (transitions from a short position to a long position or vice versa) and returns the response. This method should be overridden in a derived class to implement brokerage-specific logic for placing such orders.

This codeEntityType is protected.

Parameters:

Name Type Description Default
cross_zero_order_request CrossZeroFirstOrderRequest

The request object containing details of the cross zero order to be placed.

required
is_place_order_with_lean_event bool

A boolean indicating whether the order should be placed with triggering a Lean event. Default is true, meaning Lean events will be triggered.

True

Returns:

Type Description
CrossZeroOrderResponse

A CrossZeroOrderResponse object indicating the result of the order placement.

place_order

place_order(order: Order) -> bool

Places a new order and assigns a new broker ID to the order

Parameters:

Name Type Description Default
order Order

The order to be placed

required

Returns:

Type Description
bool

True if the request for a new order has been placed, false otherwise.

should_perform_cash_sync

should_perform_cash_sync(
    current_time_utc: Union[datetime, date],
) -> bool

Returns whether the brokerage should perform the cash synchronization

Parameters:

Name Type Description Default
current_time_utc Union[datetime, date]

The current time (UTC)

required

Returns:

Type Description
bool

True if the cash sync should be performed.

try_cross_zero_position_order

try_cross_zero_position_order(
    order: Order, holding_quantity: float
) -> Optional[bool]

Attempts to place an order that may cross the zero position. If the order needs to be split into two parts due to crossing zero, this method handles the split and placement accordingly.

This codeEntityType is protected.

Parameters:

Name Type Description Default
order Order

The order to be placed. Must not be null.

required
holding_quantity float

The current holding quantity of the order's symbol.

required

Returns:

Type Description
Optional[bool]

true if the order crosses zero and the first part was successfully placed;false if the first part of the order could not be placed;null if the order does not cross zero.

try_get_or_remove_cross_zero_order

try_get_or_remove_cross_zero_order(
    brokerage_order_id: str,
    lean_order_status: OrderStatus,
    lean_order: Optional[Order],
) -> Tuple[bool, Order]

Attempts to retrieve or remove a cross-zero order based on the brokerage order ID and its filled status.

This codeEntityType is protected.

Parameters:

Name Type Description Default
brokerage_order_id str

The unique identifier of the brokerage order.

required
lean_order_status OrderStatus

The updated status of the order received from the brokerage

required
lean_order Optional[Order]

When this method returns, contains the Order object associated with the given brokerage order ID, if the operation was successful; otherwise, null. This parameter is passed uninitialized.

required

Returns:

Type Description
Tuple[bool, Order]

true if the method successfully retrieves or removes the order; otherwise, false.

try_get_update_cross_zero_order_quantity

try_get_update_cross_zero_order_quantity(
    lean_order: Order, quantity: Optional[float]
) -> Tuple[bool, float]

Determines whether the given Lean order crosses zero quantity based on the initial order quantity.

This codeEntityType is protected.

Parameters:

Name Type Description Default
lean_order Order

The Lean order to check.

required
quantity Optional[float]

The quantity to be updated based on whether the order crosses zero.

required

Returns:

Type Description
Tuple[bool, float]

true if the Lean order does not cross zero quantity; otherwise, false.

try_handle_remaining_cross_zero_order

try_handle_remaining_cross_zero_order(
    lean_order: Order, order_event: OrderEvent
) -> bool

Attempts to handle any remaining orders that cross the zero boundary.

This codeEntityType is protected.

Parameters:

Name Type Description Default
lean_order Order

The order object that needs to be processed.

required
order_event OrderEvent

The event object containing order event details.

required

update_order

update_order(order: Order) -> bool

Updates the order with the same id

Parameters:

Name Type Description Default
order Order

The new order information

required

Returns:

Type Description
bool

True if the request was made for the order to be updated, false otherwise.