How erdewit/ib_insync works
Project type and purpose
• Open-source Python library (not a multi-tier web app).
• Purpose: Simplify and unify access to Interactive Brokers’ Trader Workstation (TWS) or IB Gateway API via a high-level IB class, domain models (Contract, Order, Ticker, FlexReport, etc.), and an asyncio/event-driven framework.
• Includes Sphinx-based docs, Jupyter notebooks, examples, and pytest tests.
File structure
• Top-level package: ib_insync/ with modules:
• connection.py, client.py, decoder.py, wrapper.py
• contract.py, order.py, ticker.py, flexreport.py, objects.py
• util.py (pandas integration), version.py, py.typed
• Directories:
• docs/ (Sphinx source + built HTML)
• examples/ (standalone scripts)
• notebooks/ (Jupyter .ipynb demos)
• tests/ (pytest tests + fixtures)
• Build & packaging: setup.py, setup.cfg, dist.sh, requirements*.txt, .github/workflows/test.yml.
README
• Confirms the async framework (asyncio + eventkit).
• Mentions domain-specific “IB component” that syncs state with TWS.
• Points at user-facing APIs, notebooks, and recipes.
Main components & their interactions
a. External System
• Interactive Brokers TWS or IB Gateway (TCP/IP server).
b. Core Library Components (in Python process):
• Connection Layer (connection.py): low-level socket I/O, message framing.
• Decoder (decoder.py): parses raw IB API messages into Python structures.
• Client Core (client.py): orchestrates requests, responses, callback dispatch.
• Wrapper (wrapper.py): high-level callbacks mapped to domain objects.
• IB Component (ib.py): top-level façade; maintains live sync with TWS, exposes req*/cancel* methods.
• Domain Models (contract.py, order.py, ticker.py, flexreport.py, objects.py): type definitions for IB entities.
• Event Framework: asyncio event loop + eventkit event bus for pub/sub of updates.
• Utilities (util.py): helpers (e.g. df() to convert to pandas).
• Versioning (version.py): package metadata.
c. User Layer
• Scripts & applications (in examples/).
• Jupyter notebooks (in notebooks/).
• External consumers import ib_insync.IB, call .connect(), issue requests, handle returned objects/events.
d. Documentation & CI
• Sphinx (docs/): source .rst → HTML.
• CI pipeline (.github/workflows/test.yml): runs pytest.
• Packaging scripts (setup.py, dist.sh).
Architectural patterns & principles
• Modular layering: connection → decoding → client orchestration → high-level facade.
• Event-driven: asynchronous pub/sub via asyncio/eventkit.
• Domain-driven design: separate modules for each IB domain object.
• Separation of concerns: core library vs. docs vs. examples vs. tests.