Skip to content

Ibkr Client

voyz edited this page Apr 25, 2024 · 15 revisions

IbkrClient

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.

Mapped endpoints

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.

Advanced API

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)
  • get_conids (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)

security_stocks_by_symbol

IBKR provides access to multiple exchanges, markets and variations of the stock 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.

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=True contract condition is applied to all calls of this method by default. Disable by setting security_stocks_by_symbol(..., default_filtering=False).
  • You can call this method with str arguments instead of StockQuery. These will be interpreted as StockQuery arguments with no filtering.
  • You can call this method with one or many arguments, eg. security_stocks_by_symbol('AAPL') or security_stocks_by_symbol(['AAPL', 'GOOG'])
  • You can mix str and StockQuery arguments, eg.: security_stocks_by_symbol(['AAPL', StockQuery('GOOG')])

Clone this wiki locally