Skip to content

Interactive Brokers API

Low-level wrapper for Interactive Brokers market data operations.

Advanced API

This is a low-level API intended for advanced use cases, particularly streaming and real-time data. For most scenarios, use the high-level functions:

  • ohlcv_from_ib() for historical data retrieval
  • ohlcv_from_ib_async() for asynchronous historical data retrieval

Overview

The chronos_lab.ib module provides the IBMarketData singleton class for direct control over Interactive Brokers TWS/Gateway connections, real-time tick subscriptions, streaming bar data, and contract management.

When to Use This API

  • Real-time tick data subscriptions
  • Streaming bar data with live updates
  • Custom contract qualification workflows
  • Direct access to ib_async API
  • Fine-grained control over subscription management
  • Batch asynchronous operations with rate limiting

When NOT to Use This API

  • Simple historical data fetching (use ohlcv_from_ib())
  • Asynchronous historical data fetching (use ohlcv_from_ib_async())
  • One-time data retrieval without subscriptions

Functions

chronos_lab.ib.get_ib

get_ib(ib: Optional[IB] = None) -> IBMarketData

Get or initialize the IBMarketData singleton instance with optional IB connection.

Convenience function for obtaining the IBMarketData singleton and ensuring it has an active connection. Preferred way to access IBMarketData in application code.

Parameters:

Name Type Description Default
ib Optional[IB]

Optional ib_async IB instance to use. If provided, the singleton uses this connection. If None, attempts to connect using default settings if not already connected.

None

Returns:

Type Description
IBMarketData

IBMarketData singleton instance with active connection, or None if connection fails.

Note
  • Internally calls IBMarketData.get_instance().init(ib)
  • Safe to call multiple times; returns the same singleton instance
  • Connection parameters from ~/.chronos_lab/.env used if ib not provided

chronos_lab.ib.map_interval_to_barsize

map_interval_to_barsize(interval: str) -> str

Convert chronos-lab interval string to IB API bar size string.

Maps human-readable interval notation to Interactive Brokers API bar size format.

Parameters:

Name Type Description Default
interval str

Chronos-lab interval string. Supported values: - Seconds: '1s', '5s', '10s', '15s', '30s' - Minutes: '1m', '2m', '3m', '5m', '10m', '15m', '20m', '30m' - Hours: '1h', '2h', '3h', '4h', '8h' - Days: '1d' - Weeks: '1w', '1wk' - Months: '1mo'

required

Returns:

Type Description
str

IB API bar size string (e.g., '1 min', '5 mins', '1 hour', '1 day', '1 week', '1 month').

Raises:

Type Description
ValueError

If interval is not in the supported list.

Note
  • IB API uses singular 'min' for 1 minute, plural 'mins' for multiple
  • IB API uses singular 'hour' for 1 hour, plural 'hours' for multiple
  • IB API uses 'secs' (plural) even for 1 second
  • Weeks and months use singular form ('1 week', '1 month')

chronos_lab.ib.calculate_ib_params

calculate_ib_params(*, period: Optional[str] = None, start_dt: Optional[str | datetime | date] = None, end_dt: Optional[str | datetime | date] = None, what_to_show: str = 'ADJUSTED_LAST', barsize: str) -> dict

Calculate Interactive Brokers historical data request parameters.

Two mutually exclusive modes are supported:

Period mode

A chronos-lab style period string (e.g., '1d', '7d', '1mo', '1y') is mapped directly to an IB duration string. Calendar units (years, months, weeks, days) map directly to IB units. Intraday units (hours, minutes, seconds) are converted to seconds.

Datetime range mode

A start datetime is provided and an optional end datetime. The duration is derived from the elapsed time. Units are chosen to minimize over- fetching (years for long daily ranges, days for multi-day spans, seconds for intraday). For daily+ barsizes spanning >= 365 days, uses year-based duration which may cause overfetching if the range doesn't align to year boundaries.

Parameters:

Name Type Description Default
period Optional[str]

chronos-lab style period string (e.g., '1d', '7d', '1mo', '1y'). Mutually exclusive with start_dt. Supported units: 'S' (seconds), 'M' (minutes), 'H' (hours), 'd' (days), 'w' (weeks), 'm' (months), 'y' (years).

None
start_dt Optional[str | datetime | date]

Start datetime of the request window. Accepts string, datetime, or date objects. Converted to UTC. Mutually exclusive with period.

None
end_dt Optional[str | datetime | date]

End datetime of the request window. Accepts string, datetime, or date objects. Converted to UTC. Defaults to current UTC time if not provided. Cannot be used with what_to_show='ADJUSTED_LAST'.

None
what_to_show str

IB data type string. Defaults to 'ADJUSTED_LAST'. Cannot specify end_dt with 'ADJUSTED_LAST' - use 'TRADES' or 'MIDPOINT' instead.

'ADJUSTED_LAST'
barsize str

IB bar size string (e.g., '1 min', '5 mins', '1 hour', '1 day'). Use map_interval_to_barsize() to convert from chronos-lab interval notation.

required

Returns:

Type Description
dict

Dictionary containing: - duration_str (str): IB duration string (e.g., '1 D', '30 D', '1 Y', '3600 S') - end_datetime (str | pd.Timestamp): Empty string ('') for ADJUSTED_LAST or when end_dt not specified, otherwise the effective end timestamp - requested_start (pd.Timestamp | None): The requested start datetime (None in period mode, timestamp in datetime range mode) - effective_start (pd.Timestamp | None): The actual start that will be fetched (None in period mode, calculated timestamp in datetime range mode) - will_overfetch (bool): True if IB API will fetch data before requested_start due to duration rounding constraints - overfetch_days (int): Number of days of overfetch (0 if no overfetch) - barsize (str): The provided barsize, echoed back for convenience - what_to_show (str): The provided what_to_show, echoed back for convenience

Raises:

Type Description
ValueError

If both period and start_dt provided, or if neither provided, or if end_dt is before start_dt, or if end_dt specified with what_to_show='ADJUSTED_LAST', or if period format is invalid.

Examples:

Period mode: >>> calculate_ib_params(period='1d', barsize='5 mins', what_to_show='TRADES')

Datetime range mode: >>> calculate_ib_params( ... start_dt='2024-01-01', ... barsize='1 day', ... what_to_show='TRADES' ... )

chronos_lab.ib.hist_to_ohlcv

hist_to_ohlcv(hist_data)

Convert historical data DataFrame to OHLCV format.

Transforms historical data from IB format (indexed by contract, datatype, date) to chronos-lab OHLCV format (indexed by date, symbol).

Parameters:

Name Type Description Default
hist_data

DataFrame from get_hist_data() or get_hist_data_async() with MultiIndex (contract, datatype, date) and columns ['open', 'high', 'low', 'close', 'volume'].

required

Returns:

Type Description

DataFrame with MultiIndex (date, symbol) and columns ['open', 'high', 'low', 'close',

'volume', 'conId']. Returns empty DataFrame with correct structure if input is empty.

Note
  • Extracts symbol from contract objects in index
  • Extracts conId from contract objects
  • Reorders index to (date, symbol) for chronos-lab conventions
  • Compatible with ohlcv_to_arcticdb() for storage

Class

chronos_lab.ib.IBMarketData

Singleton class for Interactive Brokers market data operations.

Provides centralized connection management and data retrieval from Interactive Brokers TWS/Gateway. Supports real-time tick subscriptions, historical data requests, streaming bars, and contract lookups. Uses singleton pattern to ensure a single connection instance across the application.

The class maintains internal state for active subscriptions (tickers, bars) and cached contract details. Supports both synchronous and asynchronous operations with semaphore- controlled concurrency for API rate limiting.

Attributes:

Name Type Description
conn Optional[IB]

Active IB connection instance from ib_async library. None if not connected.

_connected bool

Boolean indicating whether connection is established.

tickers Dict[str, Any]

Dictionary mapping contract IDs to real-time tick data objects.

bars Dict[str, Any]

Nested dictionary containing OHLCV bar data and contract mappings. Structure: {'ohlcv': {conId: bars}, 'contract': {conId: contract}}

contract_details Dict[str, Any]

Dictionary mapping contract IDs to cached contract detail objects.

gen_tick_list str

Default generic tick list string for market data subscriptions (includes shortcuts, option volume, IV, etc.).

_ref_data_sem Optional[Semaphore]

Asyncio semaphore controlling concurrent reference data requests.

_historical_data_sem Optional[Semaphore]

Asyncio semaphore controlling concurrent historical data requests.

_tickers_cols List

List of column names for tick data DataFrame output.

_bars_cols List

List of column names for bar data DataFrame output.

Note
  • This class uses the singleton pattern. Use get_instance() or get_ib() to obtain instance.
  • Connection parameters are read from chronos_lab settings (configured in ~/.chronos_lab/.env).
  • All datetime values are converted to UTC timezone-aware timestamps.
  • Subscriptions remain active until explicitly cancelled or disconnected.
  • Contract IDs (conId) are used as primary keys for data storage and retrieval.

get_instance classmethod

get_instance() -> IBMarketData

Get or create the singleton IBMarketData instance.

Returns:

Type Description
IBMarketData

The singleton IBMarketData instance. Creates a new instance if one doesn't exist.

connect

connect(host: Optional[str] = None, port: Optional[int] = None, readonly: Optional[bool] = None, client_id: Optional[int] = None, account: Optional[str] = None) -> bool

Connect to Interactive Brokers TWS or Gateway.

Establishes connection to IB using provided parameters or defaults from settings. If already connected, returns True without creating a new connection.

Parameters:

Name Type Description Default
host Optional[str]

TWS/Gateway hostname or IP address. If None, uses IB_GATEWAY_HOST from settings (default: 127.0.0.1).

None
port Optional[int]

TWS/Gateway port number. If None, uses IB_GATEWAY_PORT from settings (default: 4002 for Gateway, 7497 for TWS).

None
readonly Optional[bool]

Read-only mode flag. If None, uses IB_GATEWAY_READONLY from settings (default: True).

None
client_id Optional[int]

Client ID for connection. If None, uses IB_GATEWAY_CLIENT_ID from settings (default: 1). Must be unique per connection.

None
account Optional[str]

IB account identifier. If None, uses IB_GATEWAY_ACCOUNT from settings.

None

Returns:

Type Description
bool

True if connection successful or already connected, False on connection failure.

Note
  • Connection parameters default to values in ~/.chronos_lab/.env
  • Uses ib_async IB.connect() for underlying connection
  • Sets _connected flag on successful connection

disconnect

disconnect()

Disconnect from Interactive Brokers and clean up active subscriptions.

Automatically unsubscribes from all active tick and bar subscriptions before disconnecting. Safe to call even if not connected.

Returns:

Type Description

Result of IB.disconnect() if connected, None if not connected.

Note
  • Cleans up all tick subscriptions via unsub_tickers()
  • Cleans up all bar subscriptions via unsub_bars()
  • Resets _connected flag

get_hist_data

get_hist_data(contracts, duration, barsize, datatype, end_datetime: Optional[str | datetime | date] = '', userth=True)

Retrieve historical bar data for multiple contracts synchronously.

Fetches historical OHLCV data for a list of contracts using IB's reqHistoricalData. Automatically qualifies contracts if needed. Returns a MultiIndex DataFrame indexed by (contract, datatype, date).

Parameters:

Name Type Description Default
contracts

List of ib_async Contract objects to retrieve data for.

required
duration

IB duration string (e.g., '1 D', '2 W', '30 D', '1 Y').

required
barsize

IB bar size string (e.g., '1 min', '5 mins', '1 hour', '1 day').

required
datatype

IB data type string ('TRADES', 'MIDPOINT', 'BID', 'ASK', 'BID_ASK', 'ADJUSTED_LAST', 'HISTORICAL_VOLATILITY', 'OPTION_IMPLIED_VOLATILITY').

required
end_datetime Optional[str | datetime | date]

End date/time for historical data. Empty string (default) uses current time. Accepts string, datetime, or date objects.

''
userth

Use Regular Trading Hours only. True (default) for RTH, False for extended hours.

True

Returns:

Type Description

MultiIndex DataFrame with index (contract, datatype, date) and columns

['open', 'high', 'low', 'close', 'volume', 'barsize']. Returns empty

DataFrame if no data available for any contract.

Note
  • Date column is converted to UTC timezone-aware timestamps
  • Contracts with conId=0 are automatically qualified
  • Each contract is fetched sequentially (for async, use get_hist_data_async)
  • Warnings logged for contracts with no data

get_hist_data_async async

get_hist_data_async(contracts, duration, barsize, datatype, end_datetime: Optional[str | datetime | date] = '', userth=True)

Asynchronously retrieve historical data for multiple contracts in parallel.

Fetches historical OHLCV data for multiple contracts concurrently using asyncio TaskGroup. Rate-limited by _historical_data_sem semaphore. Returns a MultiIndex DataFrame indexed by (contract, datatype, date).

Parameters:

Name Type Description Default
contracts

List of ib_async Contract objects to retrieve data for.

required
duration

IB duration string (e.g., '1 D', '2 W', '30 D', '1 Y').

required
barsize

IB bar size string (e.g., '1 min', '5 mins', '1 hour', '1 day').

required
datatype

IB data type string ('TRADES', 'MIDPOINT', 'BID', 'ASK', etc.).

required
end_datetime Optional[str | datetime | date]

End date/time for historical data. Empty string (default) uses current time. Accepts string, datetime, or date objects.

''
userth

Use Regular Trading Hours only. True (default) for RTH, False for extended hours.

True

Returns:

Type Description

MultiIndex DataFrame with index (contract, datatype, date) and columns

['open', 'high', 'low', 'close', 'volume', 'barsize']. Returns empty

DataFrame if no valid data retrieved for any contract.

Note
  • Uses asyncio.TaskGroup for concurrent execution
  • Concurrency controlled by IB_HISTORICAL_DATA_CONCURRENCY setting
  • Logs progress: total contracts requested and successfully retrieved
  • Failed contracts are skipped (logged as warnings)

sub_tickers

sub_tickers(contracts, gen_tick_list='')

Subscribe to real-time tick data for specified contracts.

Initiates real-time market data subscriptions for a list of contracts. Automatically qualifies contracts if needed. Stores ticker objects in self.tickers keyed by contract ID.

Parameters:

Name Type Description Default
contracts

List of ib_async Contract objects to subscribe to.

required
gen_tick_list

Comma-separated string of generic tick types (e.g., '104,106,165'). Empty string (default) subscribes to basic ticks only. Use self.gen_tick_list for a comprehensive set including shortcuts, option volume, and implied volatility.

''
Note
  • Contracts with conId=0 are automatically qualified
  • Skips contracts already subscribed (logs warning)
  • Ticker objects stored in self.tickers[conId]
  • Use get_tickers() to retrieve current tick data as DataFrame
  • Use unsub_tickers() to cancel subscriptions

unsub_tickers

unsub_tickers(contract_ids=None)

Unsubscribe from real-time tick data subscriptions.

Cancels market data subscriptions for specified contracts or all active subscriptions.

Parameters:

Name Type Description Default
contract_ids

List of contract IDs (integers) to unsubscribe. If None (default), unsubscribes from all active tick subscriptions and clears self.tickers.

None
Note
  • Uses IB.cancelMktData() to cancel subscriptions
  • Removes unsubscribed contracts from self.tickers dictionary
  • Safe to call even if no active subscriptions

get_tickers

get_tickers(allcols=False)

Retrieve current tick data as a DataFrame for all subscribed contracts.

Converts active ticker objects to a pandas DataFrame with symbol index. Automatically handles timezone conversion (UTC) and calculates market price.

Parameters:

Name Type Description Default
allcols

If True, returns all available columns (drops only columns with all NaN). If False (default), returns only standard tick columns defined in _tickers_cols: ['time', 'symbol', 'last', 'lastSize', 'bid', 'bidSize', 'ask', 'askSize', 'open', 'high', 'low', 'close', 'conId', 'marketPrice'].

False

Returns:

Type Description

DataFrame indexed by symbol with tick data columns. Returns empty DataFrame with

standard columns if no active subscriptions.

Note
  • Time column is converted to UTC timezone-aware timestamps
  • marketPrice is calculated via ticker.marketPrice() method
  • Symbol and conId columns added from contract objects

sub_bars

sub_bars(contracts, realtime=False, **kwargs)

Subscribe to historical or real-time bar data for specified contracts.

Initiates bar data subscriptions for a list of contracts. Supports both historical bars with keepUpToDate=True and real-time 5-second bars. Stores bar data in self.bars['ohlcv'] and contract references in self.bars['contract'].

Parameters:

Name Type Description Default
contracts

List of ib_async Contract objects to subscribe to.

required
realtime

If False (default), subscribes to historical bars (requires kwargs). If True, subscribes to real-time 5-second bars via reqRealTimeBars.

False
**kwargs

Keyword arguments passed to IB.reqHistoricalData() when realtime=False. Required parameters: endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, keepUpToDate, formatDate.

{}
Note
  • Contracts with conId=0 are automatically qualified
  • Skips contracts already subscribed (logs warning)
  • Bar data stored in self.bars['ohlcv'][conId]
  • Contract objects stored in self.bars['contract'][conId]
  • Use get_bars() to retrieve bar data as DataFrame
  • Use unsub_bars() to cancel subscriptions

sub_bars_async async

sub_bars_async(contracts, realtime=False, **kwargs)

Asynchronously subscribe to bar data for multiple contracts in parallel.

Subscribes to bar data for multiple contracts concurrently using asyncio TaskGroup. Rate-limited by _historical_data_sem semaphore.

Parameters:

Name Type Description Default
contracts

List of ib_async Contract objects to subscribe to.

required
realtime

If False (default), subscribes to historical bars (requires kwargs). If True, subscribes to real-time 5-second bars.

False
**kwargs

Keyword arguments passed to IB.reqHistoricalDataAsync() when realtime=False. Required parameters: endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, keepUpToDate, formatDate.

{}

Returns:

Type Description

Integer count of successfully subscribed contracts.

Note
  • Uses asyncio.TaskGroup for concurrent execution
  • Concurrency controlled by IB_HISTORICAL_DATA_CONCURRENCY setting
  • Logs progress: total contracts requested and successfully subscribed
  • Failed or already-subscribed contracts are skipped

unsub_bars

unsub_bars(contract_ids=None)

Unsubscribe from bar data subscriptions.

Cancels bar data subscriptions (historical or real-time) for specified contracts or all active subscriptions.

Parameters:

Name Type Description Default
contract_ids

List of contract IDs (integers) to unsubscribe. If None (default), unsubscribes from all active bar subscriptions and clears self.bars.

None
Note
  • Automatically detects subscription type (RealTimeBar vs Historical)
  • Uses IB.cancelRealTimeBars() or IB.cancelHistoricalData() accordingly
  • Removes unsubscribed contracts from self.bars['ohlcv'] and self.bars['contract']
  • Safe to call even if no active subscriptions

get_bars

get_bars(contracts: Optional[List] = None, symbols: Optional[List[str]] = None, start_date: Optional[str | datetime | date] = None, end_date: Optional[str | datetime | date] = None, first: Optional[int] = None, last: Optional[int] = None, ohlcv: bool = True, allcols: bool = False)

Retrieve bar data as DataFrame for subscribed contracts with flexible filtering.

Retrieves and filters bar data from active subscriptions. Supports filtering by contract/symbol, date range, or head/tail selection. Returns data in OHLCV format (indexed by date and symbol) or contract format (indexed by contract and date).

Parameters:

Name Type Description Default
contracts Optional[List]

List of contracts to retrieve. Can be contract IDs (int) or Contract objects. If None, retrieves all subscribed contracts. Mutually exclusive with symbols parameter.

None
symbols Optional[List[str]]

List of symbol strings to retrieve (e.g., ['AAPL', 'MSFT']). Matched against subscribed contracts. Mutually exclusive with contracts parameter.

None
start_date Optional[str | datetime | date]

Start date for filtering (inclusive). Accepts string, datetime, or date objects. Converted to UTC. Mutually exclusive with first/last.

None
end_date Optional[str | datetime | date]

End date for filtering (inclusive). Accepts string, datetime, or date objects. Converted to UTC. Mutually exclusive with first/last.

None
first Optional[int]

Return first N bars per contract after sorting by date. Mutually exclusive with last and start_date/end_date.

None
last Optional[int]

Return last N bars per contract after sorting by date. Mutually exclusive with first and start_date/end_date.

None
ohlcv bool

If True (default), returns OHLCV format indexed by (date, symbol). If False, returns contract format indexed by (contract, date).

True
allcols bool

If True, includes all available columns. If False (default), includes only standard columns (['open', 'high', 'low', 'close', 'volume', 'conId'] for OHLCV format, or _bars_cols for contract format).

False

Returns:

Type Description

DataFrame with bar data. Index and columns depend on ohlcv and allcols parameters.

Returns empty DataFrame if no subscriptions or no matching data.

Note
  • Date column is always UTC timezone-aware
  • Empty bar lists are skipped
  • 'time' column renamed to 'date' for real-time bars
  • 'open_' column renamed to 'open' if present

subscribe_bars

subscribe_bars(symbols: Optional[List[str]] = None, contracts: Optional[List] = None, period: str = '1d', start_date: Optional[str | datetime | date] = None, interval: str = '5m', what_to_show: str = 'TRADES', use_rth: bool = True, realtime: bool = False) -> List[int]

Subscribe to streaming bar data with automatic IB API parameter calculation.

High-level method for subscribing to bar data using period/interval notation. Automatically converts chronos-lab period and interval strings to IB API parameters (duration, barsize) and handles contract qualification. Supports two modes for specifying the data window: period-based (relative lookback) or datetime-based (absolute start date).

Parameters:

Name Type Description Default
symbols Optional[List[str]]

List of symbol strings to subscribe to. Mutually exclusive with contracts. If provided, contracts are created and qualified automatically.

None
contracts Optional[List]

List of ib_async Contract objects to subscribe to. Mutually exclusive with symbols.

None
period str

Chronos-lab period string (e.g., '1d', '7d', '1mo', '1y'). Used to calculate IB duration parameter as a relative lookback from now. Mutually exclusive with start_date.

'1d'
start_date Optional[str | datetime | date]

Absolute start datetime for the data window. Accepts string, datetime, or date objects. Converted to UTC. If provided, the duration is calculated from this date to now. Mutually exclusive with period.

None
interval str

Chronos-lab interval string (e.g., '1m', '5m', '1h', '1d'). Mapped to IB barsize via map_interval_to_barsize().

'5m'
what_to_show str

IB data type string. Defaults to 'TRADES'. Options: 'TRADES', 'MIDPOINT', 'BID', 'ASK', 'BID_ASK', 'ADJUSTED_LAST', etc.

'TRADES'
use_rth bool

Use Regular Trading Hours only. Defaults to True. Set False for extended hours.

True
realtime bool

If False (default), uses historical bars with keepUpToDate=True. If True, uses real-time 5-second bars via reqRealTimeBars (ignores interval parameter).

False

Returns:

Type Description
List[int]

List of contract IDs (integers) successfully subscribed. Empty list on failure.

Note
  • Automatically calculates IB API parameters using calculate_ib_params()
  • Either period OR start_date must be provided (not both)
  • If neither period nor start_date provided, period defaults to '1d'
  • Logs calculated IB API parameters for transparency
  • Logs warning if IB API constraints require overfetching data
  • Creates and qualifies contracts if symbols provided
  • Use get_bars() to retrieve subscribed bar data
  • Use unsub_bars() to cancel subscriptions

subscribe_bars_async async

subscribe_bars_async(symbols: Optional[List[str]] = None, contracts: Optional[List] = None, period: str = '1d', start_date: Optional[str | datetime | date] = None, interval: str = '5m', what_to_show: str = 'TRADES', use_rth: bool = True, realtime: bool = False) -> List[int]

Asynchronously subscribe to streaming bar data with automatic parameter calculation.

High-level async method for subscribing to bar data using period/interval notation. Automatically converts chronos-lab period and interval strings to IB API parameters and handles contract qualification asynchronously with rate limiting. Supports two modes for specifying the data window: period-based (relative lookback) or datetime- based (absolute start date).

Parameters:

Name Type Description Default
symbols Optional[List[str]]

List of symbol strings to subscribe to. Mutually exclusive with contracts. If provided, contracts are created and qualified asynchronously.

None
contracts Optional[List]

List of ib_async Contract objects to subscribe to. Mutually exclusive with symbols.

None
period str

Chronos-lab period string (e.g., '1d', '7d', '1mo', '1y'). Used to calculate IB duration parameter as a relative lookback from now. Mutually exclusive with start_date.

'1d'
start_date Optional[str | datetime | date]

Absolute start datetime for the data window. Accepts string, datetime, or date objects. Converted to UTC. If provided, the duration is calculated from this date to now. Mutually exclusive with period.

None
interval str

Chronos-lab interval string (e.g., '1m', '5m', '1h', '1d'). Mapped to IB barsize via map_interval_to_barsize().

'5m'
what_to_show str

IB data type string. Defaults to 'TRADES'. Options: 'TRADES', 'MIDPOINT', 'BID', 'ASK', 'BID_ASK', 'ADJUSTED_LAST', etc.

'TRADES'
use_rth bool

Use Regular Trading Hours only. Defaults to True. Set False for extended hours.

True
realtime bool

If False (default), uses historical bars with keepUpToDate=True. If True, uses real-time 5-second bars via reqRealTimeBars (ignores interval parameter).

False

Returns:

Type Description
List[int]

List of contract IDs (integers) successfully subscribed. Empty list on failure.

List[int]

Only includes contracts with successful subscriptions.

Note
  • Uses asyncio.TaskGroup for concurrent subscriptions
  • Concurrency controlled by IB_HISTORICAL_DATA_CONCURRENCY setting
  • Automatically calculates IB API parameters using calculate_ib_params()
  • Either period OR start_date must be provided (not both)
  • If neither period nor start_date provided, period defaults to '1d'
  • Logs calculated IB API parameters for transparency
  • Logs warning if IB API constraints require overfetching data
  • Creates and qualifies contracts asynchronously if symbols provided
  • Logs progress: contracts requested and successfully subscribed

symbols_to_contracts

symbols_to_contracts(symbols: List[str], sec_type: SecType = 'STK', exchange: str = 'SMART', currency: str = 'USD') -> List[Contract]

Convert symbol strings to qualified IB Contract objects synchronously.

Creates Contract objects from symbols and qualifies them with IB to obtain contract IDs and full details. Uses IB.qualifyContracts() for synchronous qualification.

Parameters:

Name Type Description Default
symbols List[str]

List of symbol strings to convert (e.g., ['AAPL', 'MSFT', 'GOOGL']).

required
sec_type SecType

Security type. Defaults to 'STK' (stocks). Options: 'STK', 'CASH', 'IND', 'FUT', 'CRYPTO', 'CMDTY'.

'STK'
exchange str

Exchange code. Defaults to 'SMART' (IB smart routing). Common values: 'NYSE', 'NASDAQ', 'CBOE', 'IDEALPRO' (for forex).

'SMART'
currency str

Currency code. Defaults to 'USD'. Use 'EUR', 'GBP', etc. for other currencies. For CASH pairs, this is the quote currency.

'USD'

Returns:

Type Description
List[Contract]

List of qualified Contract objects with conId populated. Empty list if creation

List[Contract]

or qualification fails.

Note
  • Requires active IB connection
  • Failed symbols are logged and excluded from results
  • For async version with rate limiting, use symbols_to_contracts_async()

symbols_to_contracts_async async

symbols_to_contracts_async(symbols: List[str], sec_type: SecType = 'STK', exchange: str = 'SMART', currency: str = 'USD') -> List[Contract]

Asynchronously convert symbol strings to qualified IB Contract objects.

Creates Contract objects from symbols and qualifies them with IB to obtain contract IDs and full details. Uses IB.qualifyContractsAsync() for asynchronous qualification.

Parameters:

Name Type Description Default
symbols List[str]

List of symbol strings to convert (e.g., ['AAPL', 'MSFT', 'GOOGL']).

required
sec_type SecType

Security type. Defaults to 'STK' (stocks). Options: 'STK', 'CASH', 'IND', 'FUT', 'CRYPTO', 'CMDTY'.

'STK'
exchange str

Exchange code. Defaults to 'SMART' (IB smart routing). Common values: 'NYSE', 'NASDAQ', 'CBOE', 'IDEALPRO' (for forex).

'SMART'
currency str

Currency code. Defaults to 'USD'. Use 'EUR', 'GBP', etc. for other currencies. For CASH pairs, this is the quote currency.

'USD'

Returns:

Type Description
List[Contract]

List of qualified Contract objects with conId populated. Empty list if creation

List[Contract]

or qualification fails.

Note
  • Requires active IB connection
  • Failed symbols are logged and excluded from results
  • Logs qualification progress
  • For synchronous version, use symbols_to_contracts()

lookup_cds

lookup_cds(contracts)

Look up and cache contract details synchronously for multiple contracts.

Retrieves detailed contract information from IB and stores in self.contract_details. Uses cached values for contracts already looked up.

Parameters:

Name Type Description Default
contracts

List of ib_async Contract objects to look up details for.

required
Note
  • Automatically qualifies contracts if conId=0
  • Skips contracts already in cache (logs warning)
  • Stores results in self.contract_details[conId]
  • Use get_cds() to retrieve details as DataFrame
  • For async version with rate limiting, use lookup_cds_async()

lookup_cds_async async

lookup_cds_async(contracts)

Asynchronously look up contract details for multiple contracts in parallel.

Retrieves contract details for multiple contracts concurrently using asyncio TaskGroup. Rate-limited by _ref_data_sem semaphore. Stores results in self.contract_details.

Parameters:

Name Type Description Default
contracts

List of ib_async Contract objects to look up details for.

required

Returns:

Type Description

Integer count of successfully looked up contracts (excluding already cached).

Note
  • Uses asyncio.TaskGroup for concurrent execution
  • Concurrency controlled by IB_REF_DATA_CONCURRENCY setting
  • Logs progress: total contracts requested and successfully retrieved
  • Failed or already-cached contracts are skipped
  • Use get_cds() to retrieve details as DataFrame

get_cds

get_cds()

Retrieve cached contract details as a DataFrame.

Converts cached contract details from self.contract_details to a pandas DataFrame indexed by symbol.

Returns:

Type Description

DataFrame indexed by symbol with contract detail columns including contract

objects, symbol, and conId. Returns empty DataFrame with 'symbol' index if

no contract details have been looked up.

Note
  • Only includes contracts that have been looked up via lookup_cds() or lookup_cds_async()
  • Symbol and conId columns are extracted from contract objects
  • Contract objects are included in 'contract' column