Problem Description
Solution
To detect when your live trading algorithm has lost connection to the brokerage in QuantConnect, you should implement the on_brokerage_disconnect event handler.
This method is triggered automatically by the LEAN engine whenever the connection to the brokerage API is interrupted. You can also implement on_brokerage_reconnect to handle the restoration of the connection and on_brokerage_message for more granular debugging.
Key Event Handlers
on_brokerage_disconnect: Fires immediately upon connection loss. Use this to halt trading logic or send notifications.on_brokerage_reconnect: Fires when the connection is re-established. Use this to re-sync state or resume trading.on_brokerage_message: Provides raw messages from the brokerage, which can be useful for logging specific error codes regarding the disconnection.
Implementation Example
The following algorithm demonstrates how to manage connection state. It sets a flag to stop trading logic when disconnected and sends a notification.
# region imports
from AlgorithmImports import *
# endregion
class BrokerageConnectionMonitor(QCAlgorithm):
def initialize(self):
self.set_start_date(2023, 1, 1)
self.set_cash(100000)
self.add_equity("SPY", Resolution.MINUTE)
# State flag to control trading based on connection status
self._is_connected = True
def on_data(self, data: Slice):
# Prevent trading logic if disconnected
if not self._is_connected:
return
if not self.portfolio.invested:
self.set_holdings("SPY", 1.0)
def on_brokerage_disconnect(self):
"""
Triggered when the algorithm loses connection to the brokerage.
"""
self._is_connected = False
self.log(f"CRITICAL: Brokerage disconnected at {self.time}")
# Example: Send an email or SMS notification
# self.notify.email("[email protected]", "Algorithm Disconnected", f"Connection lost at {self.time}")
def on_brokerage_reconnect(self):
"""
Triggered when the algorithm reconnects to the brokerage.
"""
self._is_connected = True
self.log(f"INFO: Brokerage reconnected at {self.time}")
# Optional: Re-check open orders or positions here to ensure state is synced
def on_brokerage_message(self, message: BrokerageMessageEvent):
"""
Triggered when the brokerage sends a message (info, warning, or error).
"""
# Log specific reconnect/disconnect messages for debugging
if message.type == BrokerageMessageType.DISCONNECT:
self.log(f"Brokerage Message (Disconnect): {message.message}")
elif message.type == BrokerageMessageType.RECONNECT:
self.log(f"Brokerage Message (Reconnect): {message.message}")
Important Considerations
- Live Mode Only: These events are triggered asynchronously in Live Trading only. They will not trigger during backtesting.
- Execution Safety: When
on_brokerage_disconnectfires, you generally cannot place new orders (e.g.,self.liquidate()) immediately because the pipe to the broker is broken. The primary use case is to stop your algorithm from attempting to trade based on stale data and to notify the administrator. - Data Feed vs. Brokerage: In some setups, the data feed and the brokerage execution are separate connections. These handlers specifically refer to the brokerage (execution) connection.
Q&A
What happens to open orders during a disconnect?
The status of open orders depends on the brokerage. Generally, orders already sitting on the exchange remain active. However, the algorithm will not receive fill updates until the connection is re-established.
Can I liquidate my portfolio inside on_brokerage_disconnect?
No. Since the connection to the brokerage is lost, any order sent (including liquidation orders) will fail to reach the broker. You must wait for on_brokerage_reconnect to manage positions.
Does this work for all brokerages supported by QuantConnect?
Yes, the on_brokerage_disconnect and on_brokerage_reconnect methods are standardized across the LEAN engine and work for all supported brokerages (Interactive Brokers, Coinbase, OANDA, etc.), provided the brokerage API reports the connection status.