Implement retry logic for IB connection on startup
This commit is contained in:
@@ -80,6 +80,25 @@ async def reconnect_loop() -> None:
|
|||||||
logger.error("Max reconnect attempts reached. Manual restart required.")
|
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:
|
def on_disconnect() -> None:
|
||||||
logger.warning("IB Gateway disconnected. Scheduling reconnect...")
|
logger.warning("IB Gateway disconnected. Scheduling reconnect...")
|
||||||
asyncio.create_task(reconnect_loop())
|
asyncio.create_task(reconnect_loop())
|
||||||
@@ -89,9 +108,7 @@ def on_disconnect() -> None:
|
|||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
_validate_config()
|
_validate_config()
|
||||||
try:
|
try:
|
||||||
await ib.connectAsync(IBKR_HOST, IBKR_PORT, clientId=IBKR_CLIENT_ID)
|
await connect_with_retries()
|
||||||
logger.info("Connected to IB Gateway")
|
|
||||||
dependencies.setup_dependencies(ib, conn, cursor, db_write_lock)
|
|
||||||
ib.disconnectedEvent += on_disconnect
|
ib.disconnectedEvent += on_disconnect
|
||||||
yield
|
yield
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
Reference in New Issue
Block a user