-
Notifications
You must be signed in to change notification settings - Fork 55
Ibkr Client
The IbkrClient class provides an interface to the IBKR REST API.
It shares some basic configuration with the IbkrWsClient. See IBind Configuration - Construction Parameters section for more.
Basic usage of IbkrClient:
from ibind import IbkrClient
c = IbkrClient()
c.tickle()The IbkrClient class is a concrete implementation of the abstract RestClient class.
The RestClient provides a boilerplate support for common REST methods: GET, POST and DELETE, and handles the request/response processing of all API methods declared in the IbkrClient.
Almost all endpoints defined in the IBKR REST API are mapped to IbkrClient methods. Currently, the endpoint sections that are still NOT mapped are:
- Alerts
- FA Allocation Management
- FYIs and Notifications
Note:
- IBKR endpoints are not documented in this documentation. Please refer to the official IBKR REST API reference for full documentation.
- Endpoints' API implementation is categorised into Python class mixins. See ibkr_client_mixins directory for implementation details.
Majority of the IBKR endpoints' mapping is implemented by performing a simple REST request. For example:
class SessionMixin():
def authentication_status(self: 'IbkrClient') -> Result:
return self.post('iserver/auth/status')
...In several cases, IbkrClient implements additional logic to allow more sophisticated interaction with the IBKR endpoints.
The advanced API methods are:
- security_stocks_by_symbol (contract mixin)
- stock_conid_by_symbol (contract mixin)
- marketdata_history_by_symbol (marketdata mixin)
- marketdata_unsubscribe (marketdata mixin)
- marketdata_history_by_symbols (marketdata mixin)
- place_order (order mixin)
- modify_order (order mixin)
IBKR provides access to multiple exchanges, markets and instruments for most symbols. As a result, when searching for a stock by symbol using the trsrv/stocks endpoint, the API will frequently return more than one security.
{
"AAPL": [
{
"assetClass": "STK",
"chineseName": "苹果公司",
"contracts": [
{"conid": 265598, "exchange": "NASDAQ", "isUS": True},
{"conid": 38708077, "exchange": "MEXI", "isUS": False},
{"conid": 273982664, "exchange": "EBS", "isUS": False},
],
"name": "APPLE INC",
},
{
"assetClass": "STK",
"chineseName": None,
"contracts": [{"conid": 493546048, "exchange": "LSEETF", "isUS": False}],
"name": "LS 1X AAPL",
},
{
"assetClass": "STK",
"chineseName": "苹果公司",
"contracts": [{"conid": 532640894, "exchange": "AEQLIT", "isUS": False}],
"name": "APPLE INC-CDR",
},
]
}To facilitate specifying which security we want to operate on, the security_stocks_by_symbol provides a filtering mechanism. To use it, each stock that you'd want to search for can be expressed as an instance of the StockQuery dataclass:
@dataclass
class StockQuery():
"""
A class to encapsulate query parameters for filtering stock data.
Attributes:
symbol (str): The stock symbol to query.
name_match (Optional[str], optional): A string pattern to match against stock names. Optional.
instrument_conditions (Optional[dict], optional): Key-value pairs representing conditions to apply to
stock instruments. Each condition is matched exactly against the instrument's attributes.
contract_conditions (Optional[dict], optional): Key-value pairs representing conditions to apply to
stock contracts. Each condition is matched exactly against the contract's attributes.
"""
symbol: str
name_match: Optional[str] = field(default=None)
instrument_conditions: Optional[dict] = field(default=None)
contract_conditions: Optional[dict] = field(default=None)When using the StockQuery, apart from specifying the symbol to search for, we can provide additional filters that will be used to narrow down our stock search query, eg.:
from ibind import IbkrClient, StockQuery
c = IbkrClient()
queries = [StockQuery('AAPL', contract_conditions={'exchange': 'MEXI'})]
stocks = c.security_stocks_by_symbol(queries, default_filtering=False)This will call the trsrv/stocks endpoint and filter the result to contracts whose exchange is equal to MEXI:
{
"AAPL": [
{
"assetClass": "STK",
"chineseName": "苹果公司",
"contracts": [{"conid": 38708077, "exchange": "MEXI", "isUS": False}],
"name": "APPLE INC",
}
]
}Note:
- A
isUS=Truecontract condition is applied to all calls of this method by default. Disable by settingsecurity_stocks_by_symbol(..., default_filtering=False). - You can call this method with
strarguments instead ofStockQuery. These will be interpreted asStockQueryarguments with no filtering. - You can call this method with one or many arguments, eg.
security_stocks_by_symbol('AAPL')orsecurity_stocks_by_symbol(['AAPL', 'GOOG']) - You can mix
strandStockQueryarguments, eg.:security_stocks_by_symbol(['AAPL', StockQuery('GOOG')]) - Same rules apply to all other methods using
StockQueryparameters.
Most of the IBKR endpoints require us to specify securities' numerical contract IDs (usually shortened to conid) rather than symbols.
c.contract_information_by_conid('AAPL') # INVALID
c.contract_information_by_conid(265598) # VALIDstock_conid_by_symbol method facilitates acquiring conids for stock symbols using the same filtering functionality as the security_stocks_by_symbol.
- Importantly, this method will raise a
RuntimeErrorunless all of the filtered stocks return exactly one instrument and one contract. - As a result, exactly one conid can be acquired for each symbol, prompting the users to tweak the
StockQueryarguments until this is true. - This ensures that there is no ambiguity when searching for conids.
Note:
- This one instrument and one contract limitation is not present in the
security_stocks_by_symbolmethod.
Eg.:
from ibind import IbkrClient, StockQuery
stock_queries = [
StockQuery('AAPL', contract_conditions={'exchange': 'MEXI'}),
'HUBS',
StockQuery('GOOG', name_match='ALPHABET INC - CDR')
]
conids = c.stock_conid_by_symbol(stock_queries, default_filtering=False).data
print(conids)
# outputs:
{'AAPL': 38708077, 'GOOG': 532638805, 'HUBS': 169544810}marketdata_history_by_symbol is a small wrapper around the simple marketdata_history_by_conid method.
It utilises the stock_conid_by_symbol to query stock conids automatically before calling the marketdata_history_by_conid.
The /iserver/marketdata/unsubscribe endpoint allows for only one conid to be unsubscribed from at a time.
The marketdata_unsubscribe method alows to unsubscribe from multiple marketdata history conids at the same time.
marketdata_history_by_symbols is an extended version of the marketdata_history_by_symbol method.
For each StockQuery provided, it queries the marketdata history for the specified symbols in parallel. The results are then cleaned up and unified.
c.marketdata_history_by_symbols('AAPL', period='1min', bar='1min', outside_rth=True)
# outputs:
{
"AAPL": [
{
"open": 169.15,
"high": 169.15,
"low": 169.15,
"close": 169.15,
"volume": 0,
"date": datetime.datetime(2024, 4, 25, 19, 56),
},
]
}c.marketdata_history_by_symbols(['AAPL', 'MSFT'], period='1min', bar='1min', outside_rth=True)
# outputs:
{
"AAPL": [
{
"open": 169.15,
"high": 169.15,
"low": 169.15,
"close": 169.15,
"volume": 0,
"date": datetime.datetime(2024, 4, 25, 19, 56),
},
],
"MSFT": [
{
"open": 400.75,
"high": 400.75,
"low": 400.75,
"close": 400.75,
"volume": 0,
"date": datetime.datetime(2024, 4, 25, 19, 56),
},
]
}Note that both of these requests took approximately the same amount of time to execute, due to parallel querying.
See any error on this page? Create an Issue and let us know.