Generate code in 3 minutes
Enter your idea and AI generates runnable code.
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.
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.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("your_email@example.com", "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}")
on_brokerage_disconnect fires, 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.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.
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.
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.