From 32537ef6e2c38e1f226dd1d58f8093e21f852011 Mon Sep 17 00:00:00 2001 From: coddard Date: Tue, 19 May 2026 01:56:23 +0300 Subject: [PATCH] Implement retry logic for IB connection on startup --- main.py | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index f3c47de..1313387 100644 --- a/main.py +++ b/main.py @@ -80,6 +80,25 @@ async def reconnect_loop() -> None: logger.error("Max reconnect attempts reached. Manual restart required.") +async def connect_with_retries(max_attempts: int = 12) -> None: + for attempt in range(1, max_attempts + 1): + try: + await asyncio.wait_for( + ib.connectAsync(IBKR_HOST, IBKR_PORT, clientId=IBKR_CLIENT_ID), + timeout=15.0, + ) + dependencies.setup_dependencies(ib, conn, cursor, db_write_lock) + logger.info("Connected to IB Gateway") + return + except Exception as exc: + logger.warning( + f"Startup IB connection attempt {attempt}/{max_attempts} failed: {exc}" + ) + if attempt == max_attempts: + raise + await asyncio.sleep(5) + + def on_disconnect() -> None: logger.warning("IB Gateway disconnected. Scheduling reconnect...") asyncio.create_task(reconnect_loop()) @@ -89,9 +108,7 @@ def on_disconnect() -> None: async def lifespan(app: FastAPI): _validate_config() try: - await ib.connectAsync(IBKR_HOST, IBKR_PORT, clientId=IBKR_CLIENT_ID) - logger.info("Connected to IB Gateway") - dependencies.setup_dependencies(ib, conn, cursor, db_write_lock) + await connect_with_retries() ib.disconnectedEvent += on_disconnect yield finally: