IB-insync

0.9.86 · active · verified Thu Apr 16

ib-insync is a Pythonic framework for Interactive Brokers API, offering both synchronous and asynchronous interfaces. It abstracts much of the complexity of the underlying `ibapi` library, providing a high-level, event-driven API for trading, market data, and account management. The current version is 0.9.86, and the library maintains a frequent release cadence with minor updates and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to the Interactive Brokers API using `ib-insync`, qualify a stock contract, and retrieve historical data. It uses the asynchronous interface, which is the recommended modern approach. Ensure TWS (Trader Workstation) or IB Gateway is running and configured to accept API connections on the specified port.

import asyncio
from ib_insync import IB, Stock, util

async def main():
    ib = IB()
    # Connect to TWS or IB Gateway on default port 7497 (TWS) or 4002 (Gateway)
    # Ensure TWS/Gateway is running and API settings allow connection (File -> Global Configuration -> API -> Settings).
    try:
        await ib.connect('127.0.0.1', 7497, clientId=1)
        print("Connected to Interactive Brokers API.")

        # Define a contract (e.g., Apple stock)
        contract = Stock('AAPL', 'SMART', 'USD')
        
        # Qualify the contract to ensure it's valid and get full details
        # This step is crucial to avoid 'No security definition' errors
        await ib.qualifyContracts(contract)
        print(f"Qualified contract: {contract.conId} - {contract.longName}")

        # Request historical data for the contract
        # Requires an active market data subscription for 'TRADES' or 'MIDPOINT'
        bars = await ib.reqHistoricalData(
            contract,
            endDateTime='',
            durationStr='1 D', # Request 1 day of data
            barSizeSetting='1 min',
            whatToShow='TRADES',
            useRTH=True, # Use regular trading hours
            formatDate=1 # Return datetime objects
        )
        print(f"Received {len(bars)} historical bars for {contract.symbol}.")
        if bars:
            print(f"Last bar: Time={bars[-1].date}, Open={bars[-1].open}, Close={bars[-1].close}")

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        if ib.isConnected():
            ib.disconnect()
            print("Disconnected from Interactive Brokers API.")

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →