-
Notifications
You must be signed in to change notification settings - Fork 47
API Reference ‐ IbkrClient
- Result
- IbkrClient
- AccountsMixin
-
ContractMixin
- security_definition_by_conid
- all_conids_by_exchange
- contract_information_by_conid
- currency_pairs
- currency_exchange_rate
- info_and_rules_by_conid
- algo_params_by_conid
- search_bond_filter_information
- search_contract_by_symbol
- search_contract_rules
- search_secdef_info_by_conid
- search_strikes_by_conid
- security_future_by_symbol
- security_stocks_by_symbol
- stock_conid_by_symbol
- trading_schedule_by_symbol
- MarketdataMixin
- OrderMixin
-
PortfolioMixin
- portfolio_accounts
- portfolio_subaccounts
- large_portfolio_subaccounts
- portfolio_account_information
- portfolio_account_allocation
- portfolio_account_allocations
- positions
- positions2
- positions_by_conid
- invalidate_backend_portfolio_cache
- portfolio_summary
- get_ledger
- position_and_contract_info
- account_performance
- transaction_history
- ScannerMixin
- SessionMixin
- WatchlistMixin
A class to encapsulate the result of an API request.
This class is used to store and handle data returned from an API call. It includes the response data and the original request details.
Attributes:
-
dataOptional[Union[list, dict]] - The data returned from the operation. Can be either a list or a dictionary. -
requestOptional[dict] - Details of the request that resulted in this data.
A client class for interfacing with the IBKR API, extending the RestClient class.
This subclass of RestClient is specifically designed for the IBKR API. It inherits the foundational REST API interaction capabilities from RestClient and adds functionalities particular to the IBKR API, such as specific endpoint handling.
The class provides methods to perform various operations with the IBKR API, such as fetching stock data, submitting orders, and managing account information.
See: https://interactivebrokers.github.io/cpwebapi/endpoints
Notes:
- All endpoint mappings are defined as class mixins, categorised similar to the IBKR REST API documentation. See appropriate mixins for more information.
def __init__(account_id: Optional[str] = var.IBIND_ACCOUNT_ID,
url: str = var.IBIND_REST_URL,
host: str = 'localhost',
port: str = '5000',
base_route: str = '/v1/api/',
cacert: Union[str, os.PathLike, bool] = var.IBIND_CACERT,
timeout: float = 10,
max_retries: int = 3,
use_oauth: bool = var.IBIND_USE_OAUTH,
oauth_config: 'OAuthConfig' = None) -> NoneArguments:
-
account_idstr - An identifier for the account. Defaults to None. -
urlstr - The base URL for the REST API. Defaults to None. If 'use_oauth' is specified, the url is taken from oauth_config. Only if it couldn't be found in oauth_config, this url is used, or the parameters host, port and base_route. -
hoststr, optional - Host for the IBKR REST API. Defaults to 'localhost'. -
portstr, optional - Port for the IBKR REST API. Defaults to '5000' -
base_routestr, optional - Base route for the IBKR REST API. Defaults to '/v1/api/'. -
cacertUnion[os.PathLike, bool], optional - Path to the CA certificate file for SSL verification, or False to disable SSL verification. Always True when use_oauth is True. Defaults to False. -
timeoutfloat, optional - Timeout in seconds for the API requests. Defaults to 10. -
max_retriesint, optional - Maximum number of retries for failed API requests. Defaults to 3. -
use_oauthbool, optional - Whether to use OAuth authentication. Defaults to False. -
oauth_configOAuthConfig, optional - The configuration for the OAuth authentication. OAuth1aConfig is used if not specified.
def generate_live_session_token()Generates a new live session token for OAuth 1.0a authentication.
This method requests a new OAuth live session token from the IBKR API using the configured OAuth credentials. The token is stored along with its expiration time and signature.
The live session token is required for authenticated requests to IBKR's OAuth 1.0a API.
Raises:
-
ExternalBrokerError- If the token request fails.
def oauth_init(maintain_oauth: bool, shutdown_oauth: bool,
init_brokerage_session: bool)Initializes the OAuth authentication flow for the IBKR API.
This method sets up OAuth authentication by generating a live session token, validating it, and optionally starting a tickler to maintain the session. It also allows registering a shutdown handler and initializing a brokerage session if specified.
OAuth authentication is required for certain IBKR API operations. The process includes:
- Checking for the necessary cryptographic dependencies.
- Generating and validating a live session token.
- Optionally maintaining the session by running a tickler.
- Registering a shutdown handler to clean up OAuth-related processes.
- Initializing a brokerage session if required.
Arguments:
-
maintain_oauthbool - If True, starts the Tickler process to keep the session alive. -
shutdown_oauthbool - If True, registers a shutdown handler to clean up OAuth-related resources. -
init_brokerage_sessionbool - If True, initializes the brokerage session after authentication.
Raises:
-
ImportError- If the required cryptographic dependencies (Cryptomodule) are missing. -
RuntimeError- If live session token validation fails.See:
-
generate_live_session_token: Generates a new OAuth session token. -
validate_live_session_token: Validates the generated OAuth session token. -
start_tickler: Maintains the session by periodically sending requests. -
register_shutdown_handler: Registers cleanup processes for session termination. -
initialize_brokerage_session: Establishes a brokerage session post-authentication.
-
def start_tickler()Starts the Tickler instance and starts it in a separate thread to maintain the OAuth session.
The Tickler sends periodic requests to the IBKR API to prevent the session from expiring. This is necessary when using OAuth authentication to keep the connection active.
Notes:
- The Tickler should be stopped when the session is no longer needed using
stop_tickler().
def stop_tickler()Stops the Tickler thread if the Tickler is running.
The Tickler is responsible for maintaining an active session by sending periodic requests to the IBKR API. This method stops the Tickler process, preventing further requests.
def register_shutdown_handler()Registers a signal-based shutdown handler for graceful session termination.
This method sets up signal handlers to ensure the OAuth session and Tickler process
are properly shut down when the program receives termination signals (SIGINT or SIGTERM).
When the specified signals are received:
-
oauth_shutdown()is called to stop the Tickler and log out. - Any previously registered signal handlers for
SIGINTandSIGTERMare preserved and executed after the shutdown process.
def oauth_shutdown()Shuts down the OAuth session and cleans up resources.
This method stops the Tickler process, which keeps the session alive, and logs out from the IBKR API to ensure a clean session termination.
https://ibkrcampus.com/ibkr-api-page/webapi-doc/#accounts
def account_summary(account_id: str = None) -> ResultReturns a summary of the account's information.
Arguments:
-
account_idstr - The account identifier. If not provided, the active account is used.
def account_profit_and_loss() -> ResultReturns an object containing PnL for the selected account and its models (if any).
def search_dynamic_account(search_pattern: str) -> ResultSearches for broker accounts configured with the DYNACCT property using a specified pattern.
Arguments:
-
search_patternstr - The pattern used to describe credentials to search for. Valid Format: “DU” in order to query all paper accounts.
Notes:
- Customers without the DYNACCT property will receive the following 503 message: "Details currently unavailable. Please try again later and contact client services if the issue persists."
def set_dynamic_account(account_id: str) -> ResultSet the active dynamic account. Values retrieved from Search Dynamic Account.
Arguments:
-
account_idstr - The account ID that should be set for future requests.
Notes:
- If the account does not have the DYNACCT property, a 503 error message is returned.
def signatures_and_owners(account_id: str = None) -> ResultReceive a list of all applicant names on the account and for which account and entity is represented.
Arguments:
-
account_idstr - Pass the account identifier to receive information for. Valid Structure: “U1234567”.
def switch_account(account_id: str) -> ResultSwitch the active account for how you request data.
Only available for financial advisors and multi-account structures.
Arguments:
-
acctIdstr - Identifier for the unique account to retrieve information from. Value Format: “DU1234567”.
def receive_brokerage_accounts() -> ResultReturns a list of accounts the user has trading access to, their respective aliases, and the currently selected account. Note this endpoint must be called before modifying an order or querying open orders.
https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#contract
@ensure_list_arg('conids')
def security_definition_by_conid(conids: OneOrMany[str]) -> ResultReturns a list of security definitions for the given conids.
Arguments:
-
conidsOneOrMany[str] - One or many contract ID strings. Value Format: 1234.
def all_conids_by_exchange(exchange: str) -> ResultSend out a request to retrieve all contracts made available on a requested exchange. This returns all contracts that are tradable on the exchange, even those that are not using the exchange as their primary listing.
Note: This is only available for Stock contracts.
Arguments:
-
exchangestr - Specify a single exchange to receive conids for.
def contract_information_by_conid(conid: str) -> ResultRequests full contract details for the given conid.
Arguments:
-
conidstr - Contract ID for the desired contract information.
def currency_pairs(currency: str) -> ResultObtains available currency pairs corresponding to the given target currency.
Arguments:
-
currencystr - Specify the target currency you would like to receive official pairs of. Valid Structure: “USD”.
def currency_exchange_rate(source: str, target: str) -> ResultObtains the exchange rates of the currency pair.
Arguments:
-
sourcestr - Specify the base currency to request data for. Valid Structure: “AUD” -
targetstr - Specify the quote currency to request data for. Valid Structure: “USD”
def info_and_rules_by_conid(conid: str, is_buy: bool) -> ResultReturns both contract info and rules from a single endpoint.
Arguments:
-
conidstr - Contract identifier for the given contract. -
is_buybool, optional - Indicates whether you are searching for Buy or Sell order rules. Set to true for Buy Orders, set to false for Sell Orders.
def algo_params_by_conid(conid: str,
algos: List[str] = None,
add_description: str = None,
add_params: str = None) -> ResultReturns supported IB Algos for contract.
Arguments:
-
conidstr - Contract identifier for the requested contract of interest. -
algosstr, optional - List of algo ids. Max of 8 algos ids can be specified. Case sensitive to algo id. -
add_descriptionstr, optional - Whether or not to add algo descriptions to response. Set to 1 for yes, 0 for no. -
add_paramsstr, optional - Whether or not to show algo parameters. Set to 1 for yes, 0 for no.
def search_bond_filter_information(symbol: str, issuer_id: str) -> ResultRequest a list of filters relating to a given Bond issuerID.
Arguments:
-
symbolstr - This should always be set to “BOND” -
issuer_idstr - Specifies the issuerId value used to designate the bond issuer type.
def search_contract_by_symbol(symbol: str,
name: bool = None,
sec_type: str = None) -> ResultSearch by underlying symbol or company name. Relays back what derivative contract(s) it has. This endpoint must be called before using /secdef/info.
Arguments:
-
symbolstr - Underlying symbol of interest. May also pass company name if 'name' is set to true, or bond issuer type to retrieve bonds. -
namebool, optional - Determines if symbol reflects company name or ticker symbol. -
sec_typestr, optional - Valid Values: “STK”, “IND”, “BOND”. Declares underlying security type.
def search_contract_rules(conid: str,
exchange: str = None,
is_buy: bool = None,
modify_order: bool = None,
order_id: int = None) -> ResultReturns trading related rules for a specific contract and side.
Arguments:
-
conidstr - Contract identifier for the interested contract. -
exchangestr, optional - Designate the exchange you wish to receive information for in relation to the contract. -
is_buybool, optional - Side of the market rules apply to. Set to true for Buy Orders, set to false for Sell Orders. Defaults to true or Buy side rules. -
modify_orderbool, optional - Used to find trading rules related to an existing order. -
order_idint - Required for modify_order:true. Specify the order identifier used for tracking a given order.
def search_secdef_info_by_conid(conid: str,
sec_type: str,
month: str,
exchange: str = None,
strike: str = None,
right: str = None,
issuer_id: str = None) -> ResultProvides Contract Details of Futures, Options, Warrants, Cash and CFDs based on conid.
Arguments:
-
conidstr - Contract identifier of the underlying. May also pass the final derivative conid directly. -
sec_typestr - Security type of the requested contract of interest. -
monthstr - Required for Derivatives. Expiration month for the given derivative. -
exchangestr, optional - Designate the exchange you wish to receive information for in relation to the contract. -
strikestr - Required for Options and Futures Options. Set the strike price for the requested contract details. -
rightstr - Required for Options. Set the right for the given contract. Value Format: “C” for Call or “P” for Put. -
issuer_idstr - Required for Bonds. Set the issuer_id for the given bond issuer type. Example Format: “e1234567”
def search_strikes_by_conid(conid: str,
sec_type: str,
month: str,
exchange: str = None) -> ResultQuery to receive a list of potential strikes supported for a given underlying.
Arguments:
-
conidstr - Contract Identifier number for the underlying. -
sec_typestr - Security type of the derivatives you are looking for. Value Format: “OPT” or “WAR”. -
monthstr - Expiration month and year for the given underlying. Value Format: {3 character month}{2 character year}. Example: AUG23. -
exchangestr, optional - Exchange from which derivatives should be retrieved from. Default value is set to SMART.
@ensure_list_arg('symbols')
def security_future_by_symbol(symbols: OneOrMany[str]) -> ResultReturns a list of non-expired future contracts for given symbol(s).
Arguments:
-
symbolsstr - Indicate the symbol(s) of the underlier you are trying to retrieve futures on. Accepts list of string of symbols.
@ensure_list_arg('queries')
def security_stocks_by_symbol(queries: StockQueries,
default_filtering: bool = True) -> ResultRetrieves and filters stock information based on specified queries.
This function fetches stock data and applies filtering based on the provided queries, each represented by a StockQuery object. Each query can specify conditions on stock symbol, name matching, and additional criteria for instruments and contracts. The function processes these queries to filter and return the relevant stock data.
Arguments:
-
queriesList[StockQuery] - A list of StockQuery objects, each specifying filter conditions for the stocks to be retrieved. The StockQuery can include criteria like stock symbol, name matching, and specific conditions for instruments and contracts.
Returns:
-
support.rest_client.Result- The result object containing filtered stock information based on the provided queries, in form of {symbol: stock_data} dictionary data.See:
-
StockQuery- for details on how to construct queries for filtering stocks.
@ensure_list_arg('queries')
def stock_conid_by_symbol(queries: StockQueries,
default_filtering: bool = True,
return_type: str = 'dict') -> ResultRetrieves contract IDs (conids) for given stock queries, ensuring only one conid per query.
This function fetches conids for each stock query provided. It is essential that each query's filtering criteria is specific enough to return exactly one instrument and one contract, hence one conid per symbol. If the filtering returns multiple instruments or contracts, a RuntimeError is raised to prevent ambiguity in conid selection.
Arguments:
-
queriesList[StockQuery] - A list of StockQuery objects to specify filtering criteria for stocks. -
default_filteringbool, optional - Indicates whether to apply default filtering of {isUS: True}. Defaults to True. -
return_typestr, optional - Specifies the return type ('dict' or 'list') of the conids. Defaults to 'dict'.
Returns:
-
support.rest_client.Result- A Result object containing the conids, either as a dictionary with symbols as keys and conids as values or as a list of conids, depending on the return_type parameter.
Raises:
-
RuntimeError- If the filtering criteria do not result in exactly one instrument and one contract per query, thereby leading to ambiguity in conid selection.See:
-
StockQuery- for details on how to construct queries for filtering stocks.
def trading_schedule_by_symbol(asset_class: str,
symbol: str,
exchange: str = None,
exchange_filter: str = None) -> ResultReturns the trading schedule up to a month for the requested contract.
Arguments:
-
asset_classstr - Specify the security type of the given contract. Value Formats: Stock: STK, Option: OPT, Future: FUT, Contract For Difference: CFD, Warrant: WAR, Forex: SWP, Mutual Fund: FND, Bond: BND, Inter-Commodity Spreads: ICS. -
symbolstr - Specify the symbol for your contract. -
exchangestr, optional - Specify the primary exchange of your contract. -
exchange_filterstr, optional - Specify all exchanges you want to retrieve data from.
https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#md
@ensure_list_arg('conids', 'fields')
def live_marketdata_snapshot(conids: OneOrMany[str],
fields: OneOrMany[str]) -> ResultGet Market Data for the given conid(s).
A pre-flight request must be made prior to ever receiving data.
Arguments:
-
conidsOneOrMany[str] - Contract identifier(s) for the contract of interest. -
fieldsOneOrMany[str] - Specify a series of tick values to be returned.
Notes:
- The endpoint /iserver/accounts must be called prior to /iserver/marketdata/snapshot.
- For derivative contracts, the endpoint /iserver/secdef/search must be called first.
def live_marketdata_snapshot_by_symbol(queries: StockQueries,
fields: OneOrMany[str]) -> dictGet Market Data for the given symbols(s).
A pre-flight request must be made prior to ever receiving data.
Arguments:
-
queriesList[StockQuery] - A list of StockQuery objects to specify filtering criteria for stocks. -
fieldsOneOrMany[str] - Specify a series of tick values to be returned.
Notes:
- The endpoint /iserver/accounts must be called prior to /iserver/marketdata/snapshot.
- For derivative contracts, the endpoint /iserver/secdef/search must be called first.
def regulatory_snapshot(conid: str) -> ResultSend a request for a regulatory snapshot. This will cost $0.01 USD per request unless you are subscribed to the direct exchange market data already.
WARNING: Each regulatory snapshot made will incur a fee of $0.01 USD to the account. This applies to both live and paper accounts.
Arguments:
-
conidstr - Provide the contract identifier to retrieve market data for.
Notes:
- If you are already paying for, or are subscribed to, a specific US Network subscription, your account will not be charged.
- For stocks, there are individual exchange-specific market data subscriptions necessary to receive streaming quotes.
def marketdata_history_by_conid(
conid: str,
bar: str,
exchange: str = None,
period: str = None,
outside_rth: bool = None,
start_time: datetime.datetime = None) -> ResultGet historical market Data for given conid, length of data is controlled by 'period' and 'bar'.
Arguments:
-
conidstr - Contract identifier for the ticker symbol of interest. -
barstr - Individual bars of data to be returned. Possible values– 1min, 2min, 3min, 5min, 10min, 15min, 30min, 1h, 2h, 3h, 4h, 8h, 1d, 1w, 1m. -
exchangestr, optional - Returns the exchange you want to receive data from. -
periodstr - Overall duration for which data should be returned. Default to 1w. Available time period– {1-30}min, {1-8}h, {1-1000}d, {1-792}w, {1-182}m, {1-15}y. -
outside_rthbool, optional - Determine if you want data after regular trading hours. -
start_timedatetime.datetime, optional - Starting date of the request duration.
Notes:
- There's a limit of 5 concurrent requests. Excessive requests will return a 'Too many requests' status 429 response.
def historical_marketdata_beta(conid: str,
period: str,
bar: str,
outside_rth: bool = None,
start_time: datetime.datetime = None,
direction: str = None,
bar_type: str = None) -> ResultUsing a direct connection to the market data farm, will provide a list of historical market data for given conid.
Arguments:
-
conidstr - The contract identifier for which data should be requested. -
periodstr - The duration for which data should be requested. Available Values: See HMDS Period Units. -
barstr - The bar size for which bars should be returned. Available Values: See HMDS Bar Sizes. -
outside_rthbool, optional - Define if data should be returned for trades outside regular trading hours. -
start_timedatetime.datetime, optional - Specify the value from where historical data should be taken. Value Format: UTC; YYYYMMDD-HH:mm:dd. Defaults to the current date and time. -
directionstr, optional - Specify the direction from which market data should be returned. Available Values: -1: time from the start_time to now; 1: time from now to the end of the period. Defaults to 1. -
bar_typestr, optional - Returns valid bar types for which data may be requested. Available Values: Last, Bid, Ask, Midpoint, FeeRate, Inventory. Defaults to Last for Stocks, Options, Futures, and Futures Options.
Notes:
- The first time a user makes a request to the /hmds/history endpoints will result in a 404 error. This initial request instantiates the historical market data services allowing future requests to return data. Subsequent requests will return data as expected.
def marketdata_history_by_symbol(
symbol: Union[str, StockQuery],
bar: str,
exchange: str = None,
period: str = None,
outside_rth: bool = None,
start_time: datetime.datetime = None) -> ResultGet historical market Data for given symbol, length of data is controlled by 'period' and 'bar'.
Arguments:
-
symbolUnion[str, StockQuery] - StockQuery or str symbol for the ticker of interest. -
barstr - Individual bars of data to be returned. Possible values– 1min, 2min, 3min, 5min, 10min, 15min, 30min, 1h, 2h, 3h, 4h, 8h, 1d, 1w, 1m. -
exchangestr, optional - Returns the exchange you want to receive data from. -
periodstr - Overall duration for which data should be returned. Default to 1w. Available time period– {1-30}min, {1-8}h, {1-1000}d, {1-792}w, {1-182}m, {1-15}y. -
outside_rthbool, optional - Determine if you want data after regular trading hours. -
start_timedatetime.datetime, optional - Starting date of the request duration.
def marketdata_history_by_conids(conids: Union[List[str], Dict[str, str]],
period: str = "1min",
bar: str = "1min",
outside_rth: bool = True,
start_time: datetime.datetime = None,
raise_on_error: bool = False,
run_in_parallel: bool = True) -> dictAn extended version of the marketdata_history_by_conid method.
For each conid provided, it queries the marketdata history for the specified symbols. The results are then cleaned up and unified. Due to this grouping and post-processing, this method returns data directly without the Result dataclass.
Arguments:
-
conidsOneOrMany[str] - A list of conids to get market data for. -
exchangestr, optional - Returns the exchange you want to receive data from. -
periodstr - Overall duration for which data should be returned. Default to 1w. Available time period– {1-30}min, {1-8}h, {1-1000}d, {1-792}w, {1-182}m, {1-15}y. -
barstr - Individual bars of data to be returned. Possible values– 1min, 2min, 3min, 5min, 10min, 15min, 30min, 1h, 2h, 3h, 4h, 8h, 1d, 1w, 1m. -
outside_rthbool, optional - Determine if you want data after regular trading hours. -
start_timedatetime.datetime, optional - Starting date of the request duration. -
raise_on_errorbool, optional - If True, raise an exception if an error occurs during the request. Defaults to False. -
run_in_parallelbool, optional - If True, send requests in parallel to speed up the response. Defaults to True.
Notes:
- This method returns data directly without the
Resultdataclass.
@ensure_list_arg('queries')
def marketdata_history_by_symbols(queries: StockQueries,
period: str = "1min",
bar: str = "1min",
outside_rth: bool = True,
start_time: datetime.datetime = None,
raise_on_error: bool = False,
run_in_parallel: bool = True) -> dictAn extended version of the marketdata_history_by_conids method.
For each StockQuery provided, it queries the marketdata history for the specified symbols. The results are then cleaned up and unified. Due to this grouping and post-processing, this method returns data directly without the Result dataclass.
Arguments:
-
queriesList[StockQuery] - A list of StockQuery objects to specify filtering criteria for stocks. -
exchangestr, optional - Returns the exchange you want to receive data from. -
periodstr - Overall duration for which data should be returned. Default to 1w. Available time period– {1-30}min, {1-8}h, {1-1000}d, {1-792}w, {1-182}m, {1-15}y. -
barstr - Individual bars of data to be returned. Possible values– 1min, 2min, 3min, 5min, 10min, 15min, 30min, 1h, 2h, 3h, 4h, 8h, 1d, 1w, 1m. -
outside_rthbool, optional - Determine if you want data after regular trading hours. -
start_timedatetime.datetime, optional - Starting date of the request duration. -
raise_on_errorbool, optional - If True, raise an exception if an error occurs during the request. Defaults to False. -
run_in_parallelbool, optional - If True, send requests in parallel to speed up the response. Defaults to True.
Notes:
- This method returns data directly without the
Resultdataclass.
@ensure_list_arg('conids')
def marketdata_unsubscribe(conids: OneOrMany[str]) -> List[Result]Cancel market data for given conid(s).
Arguments:
-
conidsOneOrMany[str] - Enter the contract identifier to cancel the market data feed. This can clear all standing market data feeds to invalidate your cache and start fresh.
def marketdata_unsubscribe_all() -> ResultCancel all market data request(s). To cancel market data for a specific conid, see /iserver/marketdata/{conid}/unsubscribe.
- https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#order-monitor
- https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#orders
@ensure_list_arg('filters')
def live_orders(filters: OneOrMany[str] = None,
force: bool = None,
account_id: str = None) -> ResultRetrieves live orders with optional filtering. The filters, if provided, should be a list of strings. These filters are then converted and sent as a comma-separated string in the request to the API.
Arguments:
-
filtersList[str], optional - A list of strings representing the filters to be applied. Defaults to None -
forcebool, optional - Force the system to clear saved information and make a fresh request for orders. Submission will appear as a blank array. Defaults to False. -
account_idstr - For linked accounts, allows users to view orders on sub-accounts as specified.Available filters:
- Inactive: Order was received by the system but is no longer active because it was rejected or cancelled.
- PendingSubmit: Order has been transmitted but have not received confirmation yet that order accepted by destination exchange or venue.
- PreSubmitted: Simulated order transmitted but the order has yet to be elected. Order is held by IB system until election criteria are met.
- Submitted: Order has been accepted by the system.
- Filled: Order has been completely filled.
- PendingCancel: Sent an order cancellation request but have not yet received confirmation order cancelled by destination exchange or venue.
- Cancelled: The balance of your order has been confirmed canceled by the system.
- WarnState: Order has a specific warning message such as for basket orders.
- SortByTime: There is an initial sort by order state performed so active orders are always above inactive and filled then orders are sorted chronologically.
Notes:
- This endpoint requires a pre-flight request. Orders is the list of live orders (cancelled, filled, submitted).
def order_status(order_id: str) -> ResultRetrieve the given status of an individual order using the orderId returned by the order placement response or the orderId available in the live order response.
Arguments:
-
order_idstr - Order identifier for the placed order. Returned by the order placement response or the order_id available in the live order response.
def trades(days: str = None, account_id: str = None) -> ResultReturns a list of trades for the currently selected account for current day and six previous days. It is advised to call this endpoint once per session.
Arguments:
-
daysstr - Specify the number of days to receive executions for, up to a maximum of 7 days. If unspecified, only the current day is returned. -
account_idstr - Include a specific account identifier or allocation group to retrieve trades for.
@ensure_list_arg('order_request')
def place_order(order_request: OneOrMany[dict],
answers: Answers,
account_id: str = None) -> ResultWhen connected to an IServer Brokerage Session, this endpoint will allow you to submit orders.
Notes:
- With the exception of OCA groups and bracket orders, the orders endpoint does not currently support the placement of unrelated orders in bulk.
- Developers should not attempt to place another order until the previous order has been fully acknowledged, that is, when no further warnings are received deferring the client to the reply endpoint.
Arguments:
-
account_idstr - The account ID for which account should place the order. -
answersAnswers - List of question-answer pairs for order submission process. -
order_requestOneOrMany[dict] - Used to the order content.Keep this in mind: https://interactivebrokers.github.io/tws-api/automated_considerations.html#order_placement
Notes:
- Only one order can be placed at a time due to question-reply mechanism
def reply(reply_id, confirmed: bool) -> ResultConfirm order precautions and warnings presented from placing orders.
Many of the warning notifications within the Client Portal API can be disabled.
Arguments:
-
reply_idstr - Include the id value from the prior order request relating to the particular order's warning confirmation. -
confirmedbool - Pass your confirmation to the reply to allow or cancel the order to go through. true will agree to the message transmit the order. false will decline the message and discard the order.
def whatif_order(order_request: dict, account_id: str) -> ResultThis endpoint allows you to preview order without actually submitting the order and you can get commission information in the response. Also supports bracket orders.
Clients must query /iserver/marketdata/snapshot for the instrument prior to requesting the /whatif endpoint.
The body content of the /whatif endpoint will follow the same structure as the standard /iserver/account/{accountId}/orders endpoint.
Arguments:
-
account_idstr - The account ID for which account should place the order. Financial Advisors may specify. -
order_requestdict - Used to the order content.
def cancel_order(order_id: str, account_id: str = None) -> ResultCancels an open order.
Must call /iserver/accounts endpoint prior to cancelling an order. Use /iservers/account/orders endpoint to review open-order(s) and get latest order status.
Arguments:
-
account_idstr - The account ID for which account should place the order. -
order_idstr - The orderID for that should be modified. Can be retrieved from /iserver/account/orders. Submitting '-1' will cancel all open orders.
def modify_order(order_id: str,
order_request: dict,
answers: Answers,
account_id: str = None) -> ResultModifies an open order.
Must call /iserver/accounts endpoint prior to modifying an order. Use /iservers/account/orders endpoint to review open-order(s).
Arguments:
-
order_idstr - The orderID for that should be modified. Can be retrieved from /iserver/account/orders. -
order_requestdict - Used to the order content. The content should mirror the content of the original order. -
answersAnswers - List of question-answer pairs for order submission process. -
account_idstr - The account ID for which account should place the order.
Notes:
- Only one order can be modified at a time due to question-reply mechanism
def suppress_messages(message_ids: List[str]) -> ResultDisables a messageId, or series of messageIds, that will no longer prompt the user.
Arguments:
-
message_idsList[str] - The identifier for each warning message to suppress. The array supports up to 51 messages sent in a single request. Any additional values will result in a system error. The majority of the message IDs are based on the TWS API Error Codes with a “o” prepended to the id.
def reset_suppressed_messages() -> ResultResets all messages disabled by the Suppress Messages endpoint.
- https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#portfolio
- https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#pa
def portfolio_accounts() -> ResultIn non-tiered account structures, returns a list of accounts for which the user can view position and account information. This endpoint must be called prior to calling other /portfolio endpoints for those accounts.
def portfolio_subaccounts() -> ResultUsed in tiered account structures (such as Financial Advisor and IBroker Accounts) to return a list of up to 100 sub-accounts for which the user can view position and account-related information. This endpoint must be called prior to calling other /portfolio endpoints for those sub-accounts.
def large_portfolio_subaccounts(page: int = 0) -> ResultUsed in tiered account structures (such as Financial Advisor and IBroker Accounts) to return a list of sub-accounts, paginated up to 20 accounts per page, for which the user can view position and account-related information. This endpoint must be called prior to calling other /portfolio endpoints for those sub-accounts.
def portfolio_account_information(account_id: str = None) -> ResultAccount information related to account Id. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint.
Arguments:
-
account_idstr, optional - Specify the AccountID to receive portfolio information for.
def portfolio_account_allocation(account_id: str = None) -> ResultInformation about the account's portfolio allocation by Asset Class, Industry and Category. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint.
Arguments:
-
account_idstr, optional - Specify the account ID for the request.
@ensure_list_arg('account_ids')
def portfolio_account_allocations(account_ids: OneOrMany[str]) -> ResultSimilar to /portfolio/{accountId}/allocation but returns a consolidated view of all the accounts returned by /portfolio/accounts.
Arguments:
-
account_idsOneOrMany[str] - Contains all account IDs as strings the user should receive data for.
def positions(account_id: str = None,
page: int = 0,
model: str = None,
sort: str = None,
direction: str = None,
period: str = None) -> ResultReturns a list of positions for the given account. The endpoint supports paging, each page will return up to 100 positions.
Arguments:
-
account_idstr, optional - The account ID for which account should place the order. -
page_idstr, optional - The “page” of positions that should be returned. One page contains a maximum of 100 positions. Pagination starts at 0. -
modelstr, optional - Code for the model portfolio to compare against. -
sortstr, optional - Declare the table to be sorted by which column. -
directionstr, optional - The order to sort by. 'a' means ascending 'd' means descending. -
periodstr, optional - Period for pnl column. Value Format: 1D, 7D, 1M.
def positions2(account_id: str = None,
model: str = None,
sort: str = None,
direction: str = None) -> ResultReturns a list of positions for the given account. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint. This endpoint provides near-real time updates and removes caching otherwise found in the /portfolio/{accountId}/positions/{pageId} endpoint.
Arguments:
-
account_idstr, optional - The account ID for which account should place the order. -
modelstr, optional - Code for the model portfolio to compare against. -
sortstr, optional - Declare the table to be sorted by which column. -
directionstr, optional - The order to sort by. 'a' means ascending 'd' means descending.
def positions_by_conid(account_id: str, conid: str) -> ResultReturns a list containing position details only for the specified conid.
Arguments:
-
account_idstr - The account ID for which account should place the order. -
conidstr - The contract ID to receive position information on.
def invalidate_backend_portfolio_cache(account_id: str = None) -> ResultInvalidates the cached value for your portfolio’s positions and calls the /portfolio/{accountId}/positions/0 endpoint automatically.
Arguments:
-
account_idstr - The account ID for which cache to invalidate.
def portfolio_summary(account_id: str = None) -> ResultInformation regarding settled cash, cash balances, etc. in the account’s base currency and any other cash balances hold in other currencies. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint. The list of supported currencies is available at https://www.interactivebrokers.com/en/index.php?f=3185.
Arguments:
-
account_idstr - Specify the account ID for which account you require ledger information on.
def get_ledger(account_id: str = None) -> ResultInformation regarding settled cash, cash balances, etc. in the account’s base currency and any other cash balances hold in other currencies. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint. The list of supported currencies is available at https://www.interactivebrokers.com/en/index.php?f=3185.
Arguments:
-
account_idstr - Specify the account ID for which account you require ledger information on.
def position_and_contract_info(conid: str) -> ResultReturns an object containing information about a given position along with its contract details.
Arguments:
-
conidstr - The contract ID to receive position information on.
@ensure_list_arg('account_ids')
def account_performance(account_ids: OneOrMany[str], period: str) -> ResultReturns the performance (MTM) for the given accounts, if more than one account is passed, the result is consolidated.
Arguments:
-
account_idsOneOrMany[str] - Include each account ID to receive data for. -
periodstr - Specify the period for which the account should be analyzed. Available Values: “1D”, “7D”, “MTD”, “1M”, “YTD”, “1Y”.
@ensure_list_arg('account_ids', 'conids')
def transaction_history(account_ids: OneOrMany[str],
conids: OneOrMany[str],
currency: str,
days: str = None) -> ResultTransaction history for a given number of conids and accounts. Types of transactions include dividend payments, buy and sell transactions, transfers.
Arguments:
-
account_idsOneOrMany[str] - Include each account ID to receive data for. -
conidsOneOrMany[str] - Include contract ID to receive data for. Only supports one contract id at a time. -
currencystr - Define the currency to display price amounts with. Defaults to USD. -
daysstr, optional - Specify the number of days to receive transaction data for. Defaults to 90 days of transaction history if unspecified.
https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#scanner
def scanner_parameters() -> ResultReturns an xml file containing all available parameters to be sent for the Iserver scanner request.
def market_scanner(instrument: str,
type: str,
location: str,
filter: List[Dict[str, str]] = None) -> ResultSearches for contracts according to the filters specified in /iserver/scanner/params endpoint. Users can receive a maximum of 50 contracts from 1 request.
Arguments:
-
instrumentstr - Instrument type as the target of the market scanner request. Found in the “instrument_list” section of the /iserver/scanner/params response. -
typestr - Scanner value the market scanner is sorted by. Based on the “scan_type_list” section of the /iserver/scanner/params response. -
locationstr - Location value the market scanner is searching through. Based on the “location_tree” section of the /iserver/scanner/params response. -
filterList[Dict[str, str]] - Contains any additional filters that should apply to response. Each filter object may include:- code (str): Code value of the filter. Based on the “code” value within the “filter_list” section of the /iserver/scanner/params response.
- value (int): Value corresponding to the input for “code”.
def hmds_scanner_parameters() -> ResultQuery the parameter list for the HMDS market scanner.
def hmds_market_scanner(instrument: str,
location: str,
scan_code: str,
sec_type: str,
filter: List[Dict[str, str]],
max_items: int = None) -> ResultRequest a market scanner from our HMDS service. Can return a maximum of 250 contracts.
Arguments:
-
instrumentstr - Specify the type of instrument for the request. Found under the “instrument_list” value of the /hmds/scanner/params request. -
locationsstr - Specify the type of location for the request. Found under the “location_tree” value of the /hmds/scanner/params request. -
scanCodestr - Specify the scanner type for the request. Found under the “scan_type_list” value of the /hmds/scanner/params request. -
secTypestr - Specify the type of security type for the request. Found under the “location_tree” value of the /hmds/scanner/params request. -
filtersList[Dict[str, str]] - Array of objects containing all filters upon the scanner request. While “filters” must be specified in the body, no content in the array needs to be passed. -
maxItemsint, optional - Specify how many items should be returned. Default and maximum set to 250.
https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#session
def authentication_status() -> ResultCurrent Authentication status to the Brokerage system. Market Data and Trading is not possible if not authenticated, e.g. authenticated shows false.
def initialize_brokerage_session(compete: bool = True) -> ResultAfter retrieving the access token and subsequent Live Session Token, customers can initialize their brokerage session with the ssodh/init endpoint. NOTE: This is essential for using all /iserver endpoints, including access to trading and market data.
Arguments:
-
competeBoolean - Determines if other brokerage sessions should be disconnected to prioritize this connection.
Notes:
-
publishparameter is always set toTrueas per the documentation.
def logout() -> ResultLogs the user out of the gateway session. Any further activity requires re-authentication.
def tickle() -> ResultIf the gateway has not received any requests for several minutes an open session will automatically timeout. The tickle endpoint pings the server to prevent the session from ending. It is expected to call this endpoint approximately every 60 seconds to maintain the connection to the brokerage session.
def reauthenticate() -> ResultWhen using the CP Gateway, this endpoint provides a way to reauthenticate to the Brokerage system as long as there is a valid brokerage session. All interest in reauthenticating the gateway session should be handled using the /iserver/auth/ssodh/init endpoint.
def validate() -> ResultValidates the current session for the SSO user.
def check_health() -> boolVerifies the health and authentication status of the IBKR Gateway server.
This method checks if the Gateway server is alive and whether the user is authenticated. It also checks for any competing connections and the connection status.
Returns:
-
bool- True if the Gateway server is authenticated, not competing, and connected, False otherwise.
Raises:
-
AttributeError- If the Gateway health check request returns invalid data.
Notes:
- This method returns a boolean directly without the
Resultdataclass.
https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#watchlists
def create_watchlist(id: str, name: str,
rows: List[Dict[str, Union[str, int]]]) -> ResultCreate a watchlist to monitor a series of contracts.
Arguments:
-
idstr - Supply a unique identifier to track a given watchlist. Must supply a number. -
namestr - Supply the human readable name of a given watchlist. Displayed in TWS and Client Portal. -
rowsList[Dict[str, Union[str, int]]] - Provide details for each contract or blank space in the watchlist. Each object may include:- C (int): Provide the conid, or contract identifier, of the conid to add.
- H (str): Can be used to add a blank row between contracts in the watchlist.
def get_all_watchlists(sc: str = 'USER_WATCHLIST') -> ResultRetrieve a list of all available watchlists for the account.
Arguments:
-
SCstr - Optional. Specify the scope of the request. Valid Values: USER_WATCHLIST.
def get_watchlist_information(id: str) -> ResultRequest the contracts listed in a particular watchlist.
Arguments:
-
idstr - Set equal to the watchlist ID you would like data for.
def delete_watchlist(id: str) -> ResultPermanently delete a specific watchlist for all platforms.
Arguments:
-
idstr - Include the watchlist ID you wish to delete.
See any error on this page? Create an Issue and let us know.