import logging from typing import Optional from ib_insync import IB from config import config logger = logging.getLogger(__name__) class IBConnection: def __init__(self): self.ib = IB() self._connected = False async def connect(self) -> bool: if self._connected: return True try: await self.ib.connectAsync( host=config.ib.host, port=config.ib.port, clientId=config.ib.client_id, account=config.ib.account or "", ) self._connected = True logger.info( "Connected to IB Gateway at %s:%s (%s)", config.ib.host, config.ib.port, config.ib.port_label, ) return True except Exception as e: logger.error("Connection failed: %s", e) self._connected = False return False def disconnect(self): if self._connected: self.ib.disconnect() self._connected = False logger.info("Disconnected") async def reconnect(self) -> bool: self.disconnect() return await self.connect() def is_connected(self) -> bool: return self._connected and self.ib.isConnected() async def ensure_connected(self) -> bool: if not self.is_connected(): return await self.reconnect() return True ib_conn = IBConnection()