Problem Description
Solution
To detect when your live trading bot has lost its connection to the brokerage in QuantConnect, you should implement the on_brokerage_disconnect event handler.
This method is automatically triggered 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.
Implementation Strategy
on_brokerage_disconnect: Use this to log the error, send an immediate notification (Email/SMS) to yourself, and pause trading logic.on_brokerage_reconnect: Use this to log the recovery and resume trading logic.on_brokerage_message: Use this to capture specific error messages provided by the brokerage for debugging.
Python Code Example
Here is a complete algorithm structure demonstrating how to handle these events.
# 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 logic 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
# Standard trading logic example
if not self.portfolio.invested and self.time.hour == 10:
self.set_holdings("SPY", 1.0)
def on_brokerage_disconnect(self) -> None:
"""
Triggered immediately when the brokerage connection is lost.
"""
self._is_connected = False
# 1. Log the critical event
self.error(f"CRITICAL: Brokerage Disconnected at {self.time}")
# 2. Send a notification to the user (Live Mode Only)
# Replace with your actual email or phone number
self.notify.email("[email protected]",
"Algorithm Disconnect Alert",
f"Trading bot lost connection at {self.time}")
# self.notify.sms("1234567890", f"Disconnect Alert at {self.time}")
def on_brokerage_reconnect(self) -> None:
"""
Triggered when the brokerage connection is restored.
"""
self._is_connected = True
# 1. Log the recovery
self.log(f"INFO: Brokerage Reconnected at {self.time}")
# 2. Notify the user that systems are back online
self.notify.email("[email protected]",
"Algorithm Reconnect",
f"Connection restored at {self.time}")
def on_brokerage_message(self, message: BrokerageMessageEvent) -> None:
"""
Captures specific messages from the brokerage, including warnings and errors.
"""
# Filter for disconnect messages to get specific error details
if message.type == BrokerageMessageType.DISCONNECT:
self.log(f"Brokerage Message (Disconnect): {message.message}")
# Log errors that might precede a disconnect
elif message.type == BrokerageMessageType.ERROR:
self.error(f"Brokerage Error: {message.code} - {message.message}")
Key Considerations
- Asynchronous Execution: In live trading, these events are triggered asynchronously. This means they happen in real-time as the event occurs, independent of the
on_dataloop. - Backtesting Behavior: The
on_brokerage_disconnectandon_brokerage_reconnectmethods are not triggered during backtesting. They are exclusively for handling real-world network or API instability in live deployment. - Trading While Disconnected: Do not attempt to place orders (e.g.,
self.liquidate()) inside theon_brokerage_disconnectmethod. Since the connection is lost, any order requests sent at that exact moment will likely fail or be rejected.
Q&A: Brokerage Connection Management
Q: Can I attempt to reconnect manually inside on_brokerage_disconnect?
A: No. The LEAN engine handles the reconnection logic automatically. Your algorithm code should focus on managing the state of your strategy (e.g., pausing logic) and notifying you, rather than managing the network socket.
Q: Will on_brokerage_message catch all disconnects?
A: on_brokerage_message provides the text content of messages sent by the brokerage. While it often contains disconnect reasons, on_brokerage_disconnect is the specific event handler designed to guarantee you catch the state change programmatically.
Q: How do I test this code if it doesn't run in backtesting?
A: You cannot test actual disconnection logic in the backtester. To verify your notification logic works, you can temporarily call self.on_brokerage_disconnect() manually within your initialize or on_data method during a short live test (paper trading), or rely on the standard implementation provided above which follows the API specification.
Q: Does this work for all brokerages (Interactive Brokers, Coinbase, etc.)?
A: Yes. The LEAN engine abstracts the brokerage connection. Regardless of whether you are using Interactive Brokers, Bitfinex, or OANDA, the engine normalizes connection drops into these specific event handlers.