Close Navigation
Learn more about IBKR accounts

Introduction

Interactive Brokers’ Client Portal Web API delivers real-time access to Interactive Brokers’ trading functionality, including live market data, market scanners, and intra-day portfolio updates. Clients can communicate directly with IBKR infrastructure, both synchronously using RESTful HTTP endpoints and in an asynchronous, event-driven manner via websocket. A variety of authorization and authentication methods are available to accommodate any use case, including OAuth 1.0a, OAuth 2.0, SSO, and our Java-based CP Gateway tool.

Getting Started

Step One: Create an Interactive Brokers account

An active Interactive Brokers account is required in order to use the Client Portal API. If you do not already have an account, you can create one for free. Please note that you will have to wait for the account to be fully activated before connecting to the API. The Client Portal API supports only IBKR Pro accounts.

Step Two: Download and unzip the Client Portal API Gateway

Individual clients using Client Portal API will need to use a Java-based API gateway in order to access protected endpoints. The gateway is responsible for routing requests to the backend and ensuring that the brokerage session is authenticated. Interactive Brokers offers both a Standard and Beta release for our Client Portal API platforms. If you ever experience issues with the standard release, please try our Beta client in case your issue has already been resolved.

Download the Standard Release Download the Beta Release

Step Three: Download and install the Java Runtime Environment

As the Client Portal API Gateway was developed using Java, a working installation of the Java Runtime Environment (JRE) is required to run it. The minimum required version is Java 8 update 192.

 

In order to check if you have a working installation of Java, open a terminal and run the following command:

java --version

If Java is installed and correctly configured you should see information about the currently installed version, otherwise an error is raised.

If you do not have a working installation of Java, you can download it from the official website

Step Four: Run the API Gateway

In order to launch the Client Portal Gateway, you must execute a set of commands through the Windows Command Prompt or Unix Terminal. This can not be done through the default file explorer. The API gateway is meant to be run on a local machine. As such, attempting to operate the gateway on a separate machine from where commands are generated may result in the issues and is not a supported practice by Interactive Brokers.

By default, the gateway will listen on port 5000. Clients can however change this to any available port on their device by modifying the listenPort field in the gateway configuration file ‘conf.yaml’, found in the ‘root’ directory of the gateway.

After successfully running the gateway, you may proceed through the Authentication steps before proceeding to calling your requested endpoints.

Using the terminal, navigate to the directory where the gateway has been unzipped. For example:

cd C:/Users/Example/Downloads/clientportal.gw

On Windows, launch the gateway using the following command:

bin\run.bat root\conf.yaml

And in the case of Unix systems:

bin/run.sh root/conf.yaml

Authentication

After launching the client portal gateway, navigate to https://localhost:5000  and sign in using your standard Interactive Brokers credentials. After entering your username and password, you will be prompted for Two-Factor Authentication based on your authentication method of choice. After entering your information, you will see  Client login succeeds to indicate a successful login.

If you are signing in with your paper account, be sure to use the unique Paper Trading username. This can be found by logging in to the Client Portal with your live account’s username then selecting the Head and Shoulders icon in the top right corner and click Settings. Here, you should see a link for Paper Trading account. This will list your Paper Account’s account ID and username.

Session Authentication

An authenticated brokerage session is necessary to access order information, place orders, or receive market data via Client Portal API, and generally across all /iserver endpoints. Individual clients using Client Portal API are required to use the API Gateway in order to establish a secure brokerage session.

Interactive Brokers permits a single username to be signed in once at any given time. However, the Client Portal API permits users to log in without connecting to their brokerage session. This allows brokerage sessions to continue trading while non-brokerage sessions can perform certain actions such as requesting portfolio information without breaking existing trading sessions.

Background regarding CP Web API sessions:

  1. An IB username can only have one brokerage session (trading-enabled) session open at a time, i.e., it can only trade and use similarly restricted functionality on one platform (TWS, Client Portal, etc.) at any given moment, and switching to trading on a different platform entails closing the existing brokerage session and opening a new one from the new platform.
  2. Web API sessions in general are two-tiered:
    • An “outer” prerequisite “read-only session” that is required to be active/valid in order to make any CP Web API request, though by itself it only permits access to non-/iserver endpoints.
    • The “brokerage session”, established after the read-only, that permits access to trading, consumption of market data, and all other functionality behind /iserver endpoints.
  3. This two-tiered arrangement reflects the way our Client Portal website permits you to log into a read-only session for account management when that username is already logged into a brokerage session elsewhere (e.g., TWS), leaving the TWS brokerage session undisturbed.
  4. The CPAPI iframe actually behaves like the CP Gateway mentioned frequently in our CP Web API documentation (the Java-based reverse proxy tool for retail clients). The CPAPI iframe will attempt to establish a brokerage session automatically, as soon as a login occurs and the read-only session is created via SSO.

Understanding Brokerage Sessions

All resources behind /iserver are accessible only with an active “brokerage” session. Some additional info:

  1. TWS being a trading platform requires that a username has trading permissions in order for it to be used to access TWS – there is no purely “read-only” TWS access
  2. The Client Portal website, on the other hand, contains all of the reporting and account management functionality, and consequently it is possible to log in to Client Portal with a read-only/no-trading-permissions username and access reports, portfolio info, etc.
  3. Iserver is effectively TWS running on IB infrastructure, and it serves all of the trading-permissions-required resources, hence the need for a brokerage session to access those endpoints
  4. As a result of #2 and #3, the CP Web API also has this two-tiered session arrangement: The first tier is the read-only Portal session, and the second tier is the brokerage session through which you can talk to /iserver and actually trade the account(s), etc.
  5. After logging in to the Client Portal Gateway without competing sessions, you have a Portal session and can visit non-iserver resources. The additional /reauthenticate endpoint is used to subsequently reopen a brokerage session with our backend, through which you can access the protected /iserver endpoints.
  6. The brokerage session is associated with the credentials in use – your username – so you don’t need to select an account here. Rather, once you have access to a brokerage session, you can manipulate all accounts visible/accessible to the username in use.
  7. Non-iserver endpoints like /portfolio are served by different backend processes that do not require trading permissions and are accessible without a brokerage session

Understanding Interactive Brokers terminology

A brokerage session (or trading session) is established by a username (your credentials), which in turn has trading permissions for one or more accounts (the actual pools of equity). A single username can only have one trading (or “brokerage”) session active at a time. Permissions for trading in general/ for specific asset classes, market data subscriptions (and thus access to the subscribed feeds), etc. are carried by usernames, not the underlying accounts. Hence references to brokerage sessions refer to a logged-in username that is in contact with IBKR’s backend trading infrastructure.

Managing Multiple Sessions

Only a single active brokerage session can exist for any username accross all IBKR services. If you are logged in to either Client Portal, TWS, or IBKR Mobile, make sure to log out and try reauthenticating your session Client Portal API again.

Clients wishing to use multiple IBKR products at the same time (TWS, IBKR Mobile or Client Portal) can do so by creating a new username that can then be used to log into other services while using the Client Portal API. To create a second username please see the following IBKR Knowledege Base article.

Note: In accordance with market data vendor requirements, market data services are user-specific and any username subscribed will be assessed a separate market data subscription fee.

Using a Paper Account

Customers are encouraged to authenticate and test with their Paper accounts before proceeding to live testing in the Client Portal API. Users may notice that unlike other parts of Interactive Brokers, there is no slider to indicate a live or Paper account login. As such, customers must use their specific Paper username to authenticate. You can find your Paper username by following these steps:

  1. Log in to the Client Portal
  2. Select the Head & Shoulders Icon   client portal head and shoulders icon.
  3. Click “Settings”.
  4. On the left under “Account Configuration” select “Paper Trading Account”
  5. You should see a Paper Trading Username, Paper Trading Account Number, as well as options for linking your Market Data.
    • If you do not know your password already, it is recommended to select “Reset Paper Trading Password” to have a unique password for paper trading. This can be reset at any time.

You may now log in to the Client Portal Gateway using your newfound Paper Trading username and password.

Authentication Frequently Asked Questions

Pacing Limitations

Interactive Brokers has implemented pacing limits on endpoints accessible via Client Portal API. Currently a limit of 10 requests per second exists. In addition some endpoint specific limits are also in place. These limits can be found in the table below.

Where this limit is exceeded, the API will return a “429 Too Many Requests” exception. Violator IP addresses are put in a penalty box for 10 minutes. After this period, the IP address is removed from the penalty box until another request exceeds the limit again. Repeat violator IP addresses can be permanently blocked until the issue is resolved.

Endpoint Method Limit
/iserver/marketdata/snapshot GET 10 req/s
/iserver/marketdata/history GET 5 concurrent requests
/iserver/scanner/params GET 1 req/15 mins
/iserver/scanner/run POST 1 req/sec
/iserver/trades GET 1 req/5 secs
iserver/orders GET 1 req/5 secs
/iserver/account/pnl/partitioned GET 1 req/5 secs
/portfolio/accounts GET 1 req/5 secs
/portfolio/subaccounts GET 1 req/5 secs
/pa/performance POST 1 req/15 mins
/pa/summary POST 1 req/15 mins
/pa/transactions POST 1 req/15 mins
/trsv/secdef POST 200 conids/request
/fyi/unreadnumber GET 1 req/sec
/fyi/settings GET 1 req/sec
/fyi/settings/{typecode} POST 1 req/sec
/fyi/disclaimer/{typecode} GET 1 req/sec
/fyi/disclaimer/{typecode} PUT 1 req/sec
/fyi/deliveryoptions GET 1 req/sec
/fyi/deliveryoptions/email PUT 1 req/sec
/fyi/deliveryoptions/device POST 1 req/sec
/fyi/deliveryoptions/{deviceId} DELETE 1 req/sec
/fyi/notifications GET 1 req/sec
/fyi/notifications/more GET 1 req/sec
/fyi/notifications/{notificationId} PUT 1 req/sec
/tickle GET 1 req/sec
/sso/validate GET 1 req/min

Regular Server Maintenance

Interactive Brokers maintains regularly scheduled maintenance for all users of the Client Portal API. The system reset time is unique from that of the standard Trader Workstation connection. Clients will see disconnects at midnight of their connecting region.

Server Reset Times North America Europe Asia
Local Time 00:00 US/Eastern 00:00 CEST 00:00 HKT
Universal Time Coordinated 20:00 UTC 02:00 UTC 08:00 UTC

Contact Support

Interactive Brokers always welcomes users to contact customer support in the event of API behavior issues. However, to help expedite the troubleshooting process for customers, it is encouraged to first consider the following:

  • Does this issue persist in other platforms? Am I receiving errors with an order even when performing the same action in Trader Workstation rather than through the API?
  • Did the request match the Required parameters from the documentation?
  • Were documentation or guides consulted on the matter prior?
  • How long has this issue been going on? Is the error on the first attempt, or has this request been working for days prior?
  • Do other, similar requests work? Perhaps portfolio data is returned, but not trading information.

Interactive Brokers offers an array of contact methods based on your needs. The buttons listed here will direct users to the affiliated contact page so they may get started with the support team.

Create a ticket Chat in with Customer Support Phone Support

Client Portal API Status Code Definitions

Discuss the error codes returned by the Client Portal API. The table below shows the standard Status Code returned and common affiliated Error Message.

 

Code Definition Description
200 Success The content of the request was all good and accepted by the server.
400 Bad Request Typically indicates an issue with the content of the request. Potentially an invalid request type or invalid character in the body.
401 Unauthorized Unauthorized Client lacks valid authentication credentials for the requested resource.
403 Forbidden There is some issue with the authorization. Client should query the /iserver/auth/status endpoint.
404 Not found The server cannot find the requested resource. Endpoint may be deprecated
429 Too Many Requests. Often shows up when requests exceed pacing limitations.
Violator IP addresses are put in a penalty box for 10 minutes.
500 Internal Server Error. Often returned if there is an issue with the body of the request.

Endpoints

To make calls to create or modify data to Interactive Brokers, users must use an URL endpoint through the localhost. Each call is comprised of a base URL and an endpoint.

The base url is: https://localhost:5000/v1/api

By default, the Client Portal Gateway is not bundled with a signed certificate. As such, customers should either look to independently have their certificate signed, or submit requests to their localhost as ‘insecure’.

Python web requests are displayed with various external libraries that users may wish to implement. While this documentation is built around the requests library, there are a few additional libraries to consider:

  • requests
  • urllib3
  • We find particular use from  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  • json
  • ssl
  • websocket-client

To send ‘insecure’ requests in python, add “verify=False” as a request argument.

Please note the python code will not print the value direct. Customers should maintain variables or print responses as needed. One way to do this is print(requests.get({...}).content)

Please note that cURL requests are formatted using the cURL standard, documented here. Some OS specific platforms may be unique, and will require some adjustment.

Our system displays the default bash structure.

  • Unix and bash use \ (backslash)
  • Powershell will utlize ` (backtick)
  • Command Prompt uses ^ (caret)

To send ‘insecure’ requests in cURL, add “–insecure” into the request.

Alerts

Alerts allow users to set up notifications to pop-up in their Trader Workstation, Interactive Brokers app, or via email in the event of a particular event

Create or Modify Alert

Endpoint used to create a new alert, or modify an existing alert.

POST /iserver/account/{{ accountId }}/alert

Path Params

accountId: String.  Required
Identifier for the unique account to retrieve information from.
Value Format: “DU1234567”

Body Prams

alertName: String. Required
Used as a human-readable identifier for your created alert.
Format Structure: “Alert Name”

alertMessage: String. Required
The body content of what your alert will report once triggered
Value Format: “MESSAGE TEXT”

alertRepeatable: int. Required
Boolean number (0, 1) signifies if an alert can be triggered more than once.
A value of ‘1’ is required for MTA alerts
Value Format:

email: String. Required if ‘sendMessage’ == 1
Email address you want to send email alerts to
Value Format:

expireTime: String. Required if ‘tif’ == ‘GTD’
Used with a tif of “GTD” only. Signifies time when the alert should terminate if no alert is triggered.
Value Format: “YYYYMMDD-HH:mm:ss”

iTWSOrdersOnly: int. Optional
Boolean number (0, 1) to allow alerts to trigger alerts through the mobile app.
Value Format: 1

outsideRth: int. Required
Boolean number (0, 1) to allow the alert to trigger outside of regular trading hours.
Value Format: 1

sendMessage: int. Optional
Boolean number (0, 1) to allow alerts to trigger email messages
Value Format: 1

showPopup: int. Optional
Boolean number (0, 1) to allow alerts to trigger TWS Pop-up messages
Value Format: 1

tif: String.. Required
Time in Force duration of alert. Allowed: [“GTC”, “GTD”]
Value Format: “DAY”

conditions: List of Arrays. Required
Container for all conditions applied for an alert to trigger.
Required field.
Value Format:[ {…} ]

conidex: String. Required
Concatenation of conid and exchange. Formatted as “conid@exchange”
Value Format: “265598@SMART”

logicBind: String. Required
Describes how multiple conditions should behave together.
Allowed values are: {“a”: “AND”, “o”: “OR”, “n”: “END”}
Value Format: “a”

operator: String. Required
Indicates whether the trigger should be above or below the given value.
Value Format:”>=”

timeZone: String. Required for MTA alerts
Only needed for some MTA alert condition
Value Format: “US/Eastern”

triggerMethod: String. Required
Pass the string representation of zero, “0”
Value Format: “0”

type: int. Required
Designate what condition type to use.
Allowed values: {1: Price, 3: Time, 4: Margin, 5: Trade, 6: Volume, 7: MTA market, 8: MTA Position, 9: MTA Account Daily PnL}
Value Format: 1

value: String. Required
Trigger value based on Type. Allows a default value of “*”.
Value Format: “195.00”, “YYYYMMDD-HH:mm:ss”

}

]

request_url = f"{baseUrl}/iserver/account/U1234567/alert"
json_content = {
  "alertMessage": "AAPL Price Drop!",
  "alertName": "AAPL_Price",
  "expireTime":"20270101-12:00:00",
  "alertRepeatable": 0,
  "outsideRth": 0,
  "sendMessage": 1,
  "email": "user@domain.net",
  "iTWSOrdersOnly": 0,
  "showPopup": 0,
  "tif": "GTD",
  "conditions": [{
    "conidex": "265598@SMART",
    "logicBind": "n",
    "operator": "<=",
    "triggerMethod": 0,
    "type": 1,
    "value": "183.34"
  }]
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/account/U1234567/alert \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "alertMessage": "AAPL Price Drop!",
  "alertName": "AAPL_Price",
  "expireTime":"20231231-12:00:00",
  "alertRepeatable": 0,
  "outsideRth": 0,
  "sendMessage": 0,
  "email": "user@domain.net",
  "iTWSOrdersOnly": 0,
  "showPopup": 0,
  "tif": "GTD",
  "conditions": [{
    "conidex": "265598@SMART",
    "logicBind": "n",
    "operator": "<=,
    "triggerMethod": 0,
    "type": 1,
    "value": "183.34"
  }]
}'

 

Response Object:

Returns a single json object

request_id: integer. Always returns ‘null’

order_id: integer. Signifies tracking ID for given alert.

success: boolean. Displays result status of alert request

text: String. Response message to clarify success status reason.

order_status: String. Returns ‘null’

warning_message: String. Returns ‘null’
}

{
  "request_id": null,
  "order_id": 9876543210,
  "success": true,
  "text": "Submitted",
  "order_status": null,
  "warning_message": null
}

 

Get a list of available alerts

Retrieve a list of all alerts attached to the provided account.

GET /iserver/account/{{ accountId }}/alerts

 

Path Parameters

accountId: String. Required
Identifier for the unique account to retrieve information from.
Value Format: “DU1234567”

 

request_url = f"{baseUrl}/iserver/account/U1234567/alerts"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/U1234567/alerts \
--request GET

 

Response Object:

Returns an array of comma-separated json objects

order_id: int.
The searchable order ID

account: String.
The account the alert was attributed to.

alert_name: String.
The requested name for the alert.

alert_active: int.
Determines if the alert is active or not

order_time: String.
UTC-formatted time of the alert’s creation.

alert_triggered: bool.
Confirms if the order is is triggered or not.

alert_repeatable: int.
Confirms if the alert is enabled to repeat.

[
  {
    "order_id": 9876543210,
    "account": "U1234567",
    "alert_name": "AAPL Price",
    "alert_active": 1,
    "order_time": "20231211-18:55:35",
    "alert_triggered": false,
    "alert_repeatable": 0
  }
]

 

Get details of a specific alert

Request details of a specific alert by providing the assigned order ID.

GET /iserver/account/alert/{{ order_id }}

 

Path Parameters

order_id: int. Required
Alert ID returned from the original alert creation, or from the list of available alerts.

Query Parameters

type: String. Required
Must always pass ‘Q’.

request_url = f"{baseUrl}/iserver/account/alert/9876543210?type=Q"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/alert/9876543210?type=Q \
--request GET

 

Response Object

account: String.
Requestor’s account ID

order_id: int.
Alert’s tracking ID. Can be used for modifying or deleting alerts.

alertName: String.
Human readable name of the alert.

tif: String.
Time in Force effective for the Alert

expire_time: String.
Returns the UTC formatted date used in GTD orders.

alert_active: int.
Returns if the alert is active or disabled.

alert_repeatable: int.
Returns if the alert can be sent more than once.

alert_email: String.
Returns the designated email address for sendMessage functionality.

alert_send_message: int.
Returns whether or not the alert will send an email.

alert_message: String.
Returns the body content of what your alert will report once triggered

alert_show_popup: int.
Returns whether or not the alert will trigger TWS Pop-up messages

alert_play_audio: int.
Returns whether or not the alert will play audio

order_status: String.
Always returns “Presubmitted”.

alert_triggered: int.
Returns whether or not the alert was triggered yet.

fg_color: String.
Always returns “#FFFFFF”. Can be ignored.

bg_color: String.
Always returns “#000000”. Can be ignored.

order_not_editable: bool.
Returns if the order can be edited.

itws_orders_only: int.
Returns whether or not the alert will trigger mobile notifications.

alert_mta_currency: String.
Returns currency set for MTA alerts. Only valid for alert type 8 & 9.

alert_mta_defaults: String.
Returns current MTA default values.

tool_id: int.
Tracking ID for MTA alerts only. Returns ‘null’ for standard alerts.

time_zone: String.
Returned for time-specifc conditions.

alert_default_type: int.
Returns default type set for alerts. Configured in Client Portal.

condition_size: int.
Returns the total number of conditions in the alert.

condition_outside_rth: int.
Returns whether or not the alert will trigger outside of regular trading hours.

conditions: Array of json objects.
Returns all conditions, formatted as [ {Condition1}, {Condition2}, {…} ]

condition_type: int.
Returns the type of condition set.

conidex: String.
Returns full conidex in the format “conid@exchange”

contract_description_1: String.
Includes relevant descriptions (if applicable).

condition_operator: String.
Returns condition set for alert.

condition_trigger_method: int.
Returns triggerMethod value set.

condition_value: String.
Returns value set.

condition_logic_bind: String
Returns logic_bind value set.

condition_time_zone:
Returns timeZone value set.

{
  "account": "U1234567",
  "order_id": 9876543210,
  "alert_name": "AAPL Price",
  "tif": "GTD",
  "expire_time": "20231231-12:00:00",
  "alert_active": 1,
  "alert_repeatable": 0,
  "alert_email": null,
  "alert_send_message": 0,
  "alert_message": "MTA TEST!",
  "alert_show_popup": 0,
  "alert_play_audio": null,
  "order_status": "Submitted",
  "alert_triggered": false,
  "fg_color": "#FFFFFF",
  "bg_color": "#0000CC",
  "order_not_editable": false,
  "itws_orders_only": 0,
  "alert_mta_currency": null,
  "alert_mta_defaults": null,
  "tool_id": null,
  "time_zone": null,
  "alert_default_type": null,
  "condition_size": 1,
  "condition_outside_rth": 0,
  "conditions": [
    {
      "condition_type": 1,
      "conidex": "265598@SMART",
      "contract_description_1": "AAPL",
      "condition_operator": "<=",
      "condition_trigger_method": "0",
      "condition_value": "183.34",
      "condition_logic_bind": "n",
      "condition_time_zone": null
    }
  ]
}

 

Get MTA Alert

Retrieve information about your MTA alert.

Each login user only has one mobile trading assistant (MTA) alert with it’s own unique tool id that cannot be changed.

MTA alerts can not be created or deleted, only modified. When modified a new order Id is generated.

See here for more information on MTA alerts.

GET /iserver/account/mta

Request Object

No additional parameters necessary.

request_url = f"{baseUrl}/iserver/account/mta"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/mta \
--request GET

 

Response Object

account: String.
Requestor’s account ID

order_id: int.
Alert’s tracking ID. Can be used for modifying or deleting alerts.

alertName: String.
Human readable name of the alert.

tif: String.
Time in Force effective for the Alert

expire_time: String.
Returns the UTC formatted date used in GTD orders.

alert_active: int.
Returns if the alert is active or disabled.

alert_repeatable: int.
Returns if the alert can be sent more than once.

alert_email: String.
Returns the designated email address for sendMessage functionality.

alert_send_message: int.
Returns whether or not the alert will send an email.

alert_message: String.
Returns the body content of what your alert will report once triggered

alert_show_popup: int.
Returns whether or not the alert will trigger TWS Pop-up messages

alert_play_audio: int.
Returns whether or not the alert will play audio

order_status: String.
Always returns “Presubmitted”.

alert_triggered: int.
Returns whether or not the alert was triggered yet.

fg_color: String.
Always returns “#FFFFFF”. Can be ignored.

bg_color: String.
Always returns “#000000”. Can be ignored.

order_not_editable: bool.
Returns if the order can be edited.

itws_orders_only: int.
Returns whether or not the alert will trigger mobile notifications.

alert_mta_currency: String.
Returns currency set for MTA alerts. Only valid for alert type 8 & 9.

alert_mta_defaults: String.
Returns current MTA default values.

tool_id: int.
Tracking ID for MTA alerts only. Returns ‘null’ for standard alerts.

time_zone: String.
Returned for time-specifc conditions.

alert_default_type: int.
Returns default type set for alerts. Configured in Client Portal.

condition_size: int.
Returns the total number of conditions in the alert.

condition_outside_rth: int.
Returns whether or not the alert will trigger outside of regular trading hours.

conditions: Array of json objects.
Returns all conditions, formatted as [ {Condition1}, {Condition2}, {…} ]

condition_type: int.
Returns the type of condition set.

conidex: String.
Returns full conidex in the format “conid@exchange”

contract_description_1: String.
Includes relevant descriptions (if applicable).

condition_operator: String.
Returns condition set for alert.

condition_trigger_method: int.
Returns triggerMethod value set.

condition_value: String.
Returns value set.

condition_logic_bind: String
Returns logic_bind value set.

condition_time_zone:
Returns timeZone value set.

{
  "account": "U1234567",
  "order_id": 9998887776,
  "alert_name": null,
  "tif": "GTC",
  "expire_time": null,
  "alert_active": 1,
  "alert_repeatable": 1,
  "alert_email": null,
  "alert_send_message": 1,
  "alert_message": null,
  "alert_show_popup": 0,
  "alert_play_audio": null,
  "order_status": "Inactive",
  "alert_triggered": false,
  "fg_color": "#000000",
  "bg_color": "#AFAFAF",
  "order_not_editable": false,
  "itws_orders_only": 0,
  "alert_mta_currency": "USD",
  "alert_mta_defaults": "9:STATE=1,MIN=-43115000,MAX=43115000,STEP=500,DEF_MIN=-4311500,DEF_MAX=4311500|{{...}}",
  "tool_id": 55834574848,
  "time_zone": "GMT (GMT),GMT (Africa/Abidjan),{{...}}",
  "alert_default_type": null,
  "condition_size": 0,
  "condition_outside_rth": 0,
  "conditions": []
}

 

Activate or deactivate an alert

Activate or Deactivate existing alerts created for this account. This does not delete alerts, but disables notifications until reactivated.

POST /iserver/account/{{ accountId }}/alert/activate

 

Request Details

Path Parameters

accountId: String. Required
Identifier for the unique account to retrieve information from.
Value Format: “DU1234567”

Request Body

alertId: int. Required
The alertId, or order_id, received from order creation or the list of alerts.

alertActive: int. Required
Set whether or not the alert should be active (1) or inactive (0)

request_url = f"{baseUrl}/iserver/account/U1234567/alert/activate"
--request POST \
--header 'Content-Type:application/json' \
--data '{
    "alertId": 9876543210,
    "alertActive": 1
}'

 

 

curl \
--url {{baseUrl}}/iserver/account/U1234567/alert/activate \
--request POST \
--header 'Content-Type:application/json' \
--data '{
    "alertId": 9876543210,
    "alertActive": 1
}'

 

 

Response Object

request_id: int.
Returns ‘null’

order_id: int.
Returns requested alertId or order_id

success: bool.
Returns true if successful

text: String.
Adds additional information for “success” status.

failure_list: String.
If “success” returns false, will list failed order Ids

{
  "request_id": null,
  "order_id": 9876543210,
  "success": true,
  "text": "Request was submitted",
  "failure_list": null
}

 

Delete an alert

Permanently delete an existing alert.

If alertId is 0, it will delete all alerts

If you call delete an MTA alert, it will reset to the default state.

DELETE /iserver/account/{{ accountId }}/alert/{{ alertId }}

 

Request Parameters

Path Parameters

accountId: StringRequired
Identifier for the unique account to retrieve information from.
Value Format: “DU1234567”

alertId: int. Required
order_id returned from the original alert creation, or from the list of available alerts.

request_url = f"{baseUrl}/iserver/account/U1234567/alert/9876543210"
json_content = {}
requests.delete(url=request_url, json=json_content)
curl \
--url {{baseUrl}}/iserver/account/U1234567/alert/9876543210 \
--request DELETE

 

Response Object

request_id: int.
Returns ‘null’

order_id: int.
Returns requested alertId or order_id

success: bool.
Returns true if successful

text: String.
Adds additional information for “success” status.

failure_list: String.
If “success” returns false, will list failed order Ids

{
  "request_id": null,
  "order_id": 9876543210,
  "success": true,
  "text": "Request was submitted",
  "failure_list": null
}

 

Accounts

Account Profit and Loss

Returns an object containing PnL for the selected account and its models (if any).

GET /iserver/account/pnl/partitioned

 

Request Object:

No additional parameters necessary.

request_url = f"{baseUrl}/iserver/account/pnl/partitioned"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/pnl/partitioned \
--request GET

 

Response Object:

upnl : JSON Object.

Refers to “updated PnL”. Holds a json object of key-value paired account pnl details.

{accountId}.Core: JSON Object.

An object based on your current account or group model.

rowType: int.
Returns the positional value of the returned account. Always returns 1 for individual accounts.

dpl: float.
Daily PnL for the specified account profile.

nl: float.
Net Liquidity for the specified account profile.

upl: float.
Unrealized PnL for the specified account profile.

el: float.
Excess Liquidity for the specified account profile.

mv: float.
Margin value for the specified account profile.

{
  "upnl": {
    "U1234567.Core": {
      "rowType": 1,
      "dpl": 15.7,
      "nl": 10000.0,
      "upl": 607.0,
      "el": 10000.0,
      "mv": 0.0
    }
  }
}

 

Search Dynamic Account

Broker accounts configured with the DYNACCT property will not receive account information at login. Instead, they must dynamically query then set their account number.

Important:

This will not function for individual or financial advisor accounts. This will only be functional for IBrokers with the DYNACCT property approved.

Customers without the DYNACCT property will receive the following message

{
    "error": "Details currently unavailable. Please try again later and contact client services if the issue persists.",
    "statusCode": 503
}

 

Returns a list of accounts matching a query pattern set in the request.

GET /iserver/account/search/{{ searchPattern }}

 

Request Object

Query Params

searchPattern: String. Required
The pattern used to describe credentials to search for.
Valid Format: “DU” in order to query all paper accounts.

request_url 
 f"{baseUrl}/iserver/account/search/U123"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/search/U123 \
--request GET

 

Response Object

matchedAccounts: List of objects.
Contains a series of objects that pertain to the account information requested.
[{
accountId: String.
Returns a matching account ID that corresponds to the matching value.

alias: String.
Returns the corresponding alias or alternative name for the specific account ID. May be a duplicate of the accountId value in most cases.

allocationId: String.
Returns the allocation identifier used internally for the account.
}]
pattern: String.
Displays the searchPattern used for the request.

{
  "matchedAccounts": [
    {
      "accountId": "U1234567",
      "alias": "U1234567",
      "allocationId": "1"
    }
  ],
  "pattern":"U123"
}

 

Set Dynamic Account

Broker accounts configured with the DYNACCT property will not receive account information at login. Instead, they must dynamically query then set their account number.

Important:

This will not function for individual or financial advisor accounts. This will only be functional for IBrokers with the DYNACCT property approved.

Customers without the DYNACCT property will receive the following message

{
    "error": "Details currently unavailable. Please try again later and contact client services if the issue persists.",
    "statusCode": 503
}

 

Set the active dynamic account. Values retrieved from Search Dynamic Account

POST /iserver/dynaccount

 

Request Object

Body Params

acctId: String. Required
The account ID that should be set for future requests.

request_url = f"{baseUrl}/iserver/dynaccount"
json_content = {
  "acctId": "U1234567
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/dynaccount \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "acctId": "U1234567
}'

 

Response Object

set: bool.
Confirms if the account change was fully set.

acctId: String.
The account ID that was set for future use.

{
  "set": "true",
  "acctId": "U1234567",
}

 

Signatures and Owners

Receive a list of all applicant names on the account and for which account and entity is represented.

GET /acesws/{{ accountID }}/signatures-and-owners

 

Request Object

Path Params

accountId: String. Required
Pass the account identifier to receive information for.
Valid Structure: “U1234567”

request_url = f"{baseUrl}/acesws/U1234567/signatures-and-owners"
request.get(url=request_url)

 

curl \
--url {{baseUrl}}/acesws/U1234567/signatures-and-owners \
--request GET

 

Response Object

accountId: String.
Specified account identifier in the request.

users: Array of Objects.
Returns all usernames and their information affiliated with the account.
[{
roleId: String.
Returns the role of the username as it relates to the account.

hasRightCodeInd: bool.
Internal use only.

username: String.
Returns the username for the particular user under the account.

entity: Object.
Provides information about the particular entity.
{
firstName: String.
Returns the first name of the user.

lastName: String.
Returns the last name of the user.

entityType: String.
Returns the type of entity assigned to the user.
Valid Value: “INDIVIDUAL”, “Joint”, “ORG”

entityName: String.
Returns the full entity’s name, concatenating the first and last name fields.
}}]

applicant: Object.
Provides information about the individual listed for the account.
{
signatures: Array of Strings.
Returns all names attached to the account.
}

{
  "accountId": "U1234567",
  "users": [
    {
      "roleId": "OWNER",
      "hasRightCodeInd": true,
      "userName": "user1234",
      "entity": {
        "firstName": "John",
        "lastName": "Smith",
        "entityType": "INDIVIDUAL",
        "entityName": "John Smith"
      }
    },
    {
      "roleId": "Trustee",
      "hasRightCodeInd": False,
      "userName": "user5678",
      "entity": {
        "firstName": "Jane",
        "lastName": "Doe",
        "entityType": "INDIVIDUAL",
        "entityName": "Jane Doe"
      }
    }
  ],
  "applicant": {
    "signatures": [
      "John Smith",
      "Jane Doe"
    ]
  }
}

 

Switch Account

Switch the active account for how you request data.

Only available for financial advisors and multi-account structures.

POST /iserver/account

 

Request Object:

Body Parameters

acctId: String. Required
Identifier for the unique account to retrieve information from.
Value Format: “DU1234567”

 

request_url = f"{baseUrl}/iserver/account"
json_content = {
  "acctId": "U1234567,
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/account \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "acctId": "U1234567,
}'

 

Response Object:

set: bool.
Confirms that the account change was set.

acctId: String.
Confirms the account switched to.

{
    "set": true,
    "acctId": "U1234567
}

 

Receive Brokerage Accounts

Returns 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.

GET /iserver/accounts

Request Object:

No parameters necessary.

request_url = f"{baseUrl}/iserver/accounts" 
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/accounts \ 
--request GET

 

Response Object:

accounts: Array of Strings.
Returns an array of all accessible accountIds.

acctProps: Json Object.
Returns an json object for each accessible account’s properties.

hasChildAccounts: bool.
Returns whether or not child accounts exist for the account.

supportsCashQty: bool
Returns whether or not the account can use Cash Quantity for trading.

supportsFractions: bool.
Returns whether or not the account can submit fractional share orders.

aliases: JSON Object.
Returns any available aliases for the account.

allowFeatures: JSON object
JSON of allowed features for the account.

showGFIS: bool.
Returns if the account can access market data.

showEUCostReport: bool.
Returns if the account can view the EU Cost Report

allowFXConv: bool.
Returns if the account can convert currencies.

allowFinancialLens: bool.
Returns if the account can access the financial lens.

allowMTA: bool.
Returns if the account can use mobile trading alerts.

allowTypeAhead: bool.
Returns if the account can use Type-Ahead support for Client Portal.

allowEventTrading: bool.
Returns if the account can use Event Trader.

snapshotRefreshTimeout: int.
Returns the snapshot refresh timeout window for new data.

liteUser: bool.
Returns if the account is an IBKR Lite user.

showWebNews: bool.
Returns if the account can use News feeds via the web.
research: bool.

debugPnl: bool.
Returns if the account can use the debugPnl endpoint.

showTaxOpt: bool.
Returns if the account can use the Tax Optimizer tool

showImpactDashboard: bool.
Returns if the account can view the Impact Dashboard.

allowDynAccount: bool.
Returns if the account can use dynamic account changes.

allowCrypto: bool.
Returns if the account can trade crypto currencies.

allowedAssetTypes: bool.
Returns a list of asset types the account can trade.

chartPeriods: Json Object.
Returns available trading times for all available security types.

groups: Array.
Returns an array of affiliated groups.

profiles: Array.
Returns an array of affiliated profiles.

selectedAccount: String.
Returns currently selected account. See Switch Account for more details.

serverInfo: JSON Object.
Returns information about the IBKR session. Unrelated to Client Portal Gateway.

sessionId: String.
Returns current session ID.

isFT: bool.
Returns fractional trading access.

isPaper: bool.
Returns account type status.

{
  "accounts": [
    "U1234567"
  ],
  "acctProps": {
    "U1234567": {
      "hasChildAccounts": false,
      "supportsCashQty": true,
      "noFXConv": false,
      "isProp": false,
      "supportsFractions": true,
      "allowCustomerTime": false
    }
  },
  "aliases": {
    "U1234567": "U1234567"
  },
  "allowFeatures": {
    "showGFIS": true,
    "showEUCostReport": false,
    "allowEventContract": true,
    "allowFXConv": true,
    "allowFinancialLens": false,
    "allowMTA": true,
    "allowTypeAhead": true,
    "allowEventTrading": true,
    "snapshotRefreshTimeout": 30,
    "liteUser": false,
    "showWebNews": true,
    "research": true,
    "debugPnl": true,
    "showTaxOpt": true,
    "showImpactDashboard": true,
    "allowDynAccount": false,
    "allowCrypto": false,
    "allowedAssetTypes": "STK,CRYPTO"
  },
  "chartPeriods": {
    "STK": [
      "*"
    ],
    "CRYPTO": [
      "*"
    ]
  },
  "groups": [],
  "profiles": [],
  "selectedAccount": "U1234567",
  "serverInfo": {
    "serverName": "JifN17091",
    "serverVersion": "Build 10.25.0p, Dec 5, 2023 5:48:12 PM"
  },
  "sessionId": "1234a5b.12345678",
  "isFT": false,
  "isPaper": false
}

 

Option Chains

Option Chains are not through a singular request. However, they can be retrieved through a specific process in the Client Portal API. The steps below the standard procedure to retrieve a range of option conIds that can be filtered into market data.

Step One: Instantiate the Option Chain

To begin, users must first make a call to the /iserver/secdef/search endpoint for the underlying symbol. This is required for all future steps every time the user does not know the final derivative’s conId.

This must always be called before proceeding, even if you are aware of the conId and expiration dates.

request_url = f"{baseUrl}/iserver/secdef/search?symbol=SPX"
requests.get(url=request_url)

 

curl --insecure \
--url https://localhost:5000/v1/api/iserver/secdef/search?symbol=SPX \
--request GET

 

In the response, we are able to see two important values returned. The first, we can find our ConID for the underlying, 416904. We will need this for our future requests.

We can also see under “sections”::”secType”:”OPT, “months” we will see all of the contract expirations months. This will be required to build our option chain in the next request.

[
  {
    "conid": "416904",
    "companyHeader": "S&P 500 Stock Index - CBOE",
    "companyName": "S&P 500 Stock Index",
    "symbol": "SPX",
    "description": "CBOE",
    "restricted": "IND",
    "fop": null,
    "opt": "20240102;{..};20291220",
    "war": "20231130;{..};20271216",
    "sections": [
      {...},
      {
        "secType": "OPT",
        "months": "JAN24;FEB24;MAR24;APR24;MAY24;JUN24;JUL24;AUG24;SEP24;OCT24;NOV24;DEC24;JAN25;MAR25;JUN25;DEC25;DEC26;DEC27;DEC28;DEC29",
        "exchange": "SMART;CBOE;IBUSOPT"
      },
      {...}
    ]
  }
]

 

Step Two: Find Potential Strikes

After querying the /iserver/secdef/search endpoint, developers should now call the /iserver/secdef/strikes endpoint. To receive the appropriate strikes, the conId, secType, and expiration month should be specified.

This must always be called before proceeding, even if you are aware of the strikes.

Note: For Futures Options, the conId of the Index should be specified, along with the explicit exchange being listed. As an example, CL futures options should specify “exchange=NYMEX” as an additional query parameter.

request_url = f"{baseUrl}/iserver/secdef/strikes?conid=416904&sectype=OPT&month=JAN25"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/secdef/strikes?conid=416904&secType=OPT&month=JAN25 \
--request GET

 

As a response, an object containing arrays of all Call and Put strikes will be returned. This will only return potential strike prices. This does not necessarily indicate. These strikes should be confirmed with our /info endpoint to confirm if the strike is valid.

{
  "call": [
    200.0,
  {...},
    7800.0
  ],
  "put": [
    200.0,
  {...},
    7800.0
  ]
}

 

Step Three: Validate The Contract

After calling the /search and /strikes endpoints, users can use the /iserver/secdef/info endpoint to validate the derivative conId. This endpoint should be called for each strike and right combination of interest.

Note: For Futures Options, the conId of the Index should be specified, along with the explicit exchange being listed. As an example, CL futures options should specify “exchange=NYMEX” as an additional query parameter.

request_url = f"{baseUrl}/iserver/secdef/info?conid=416904&secType=OPT&month=JAN25&strike=3975&right=P
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/secdef/info?conid=416904&secType=OPT&month=JAN25&strike=3975&right=P \
--request GET

 

While all of the information is relevant, it is most important to save the conId in order to track the contract itself. For the lifespan of the Option, this conId will remain constant. This will also be used for all subsequent requests for market data or order placement.

[
  {
    "conid": 654371995,
    "symbol": "SPX",
    "secType": "OPT",
    "exchange": "SMART",
    "listingExchange": null,
    "right": "P",
    "strike": 3975.0,
    "currency": "USD",
    "cusip": null,
    "coupon": "No Coupon",
    "desc1": "SPX",
    "desc2": "JAN 16 '25 3975 Put (AM)",
    "maturityDate": "20250116",
    "multiplier": "100",
    "tradingClass": "SPX",
    "validExchanges": "SMART,CBOE,IBUSOPT"
  }
]

 

Final Steps

After confirming all of our interested strikes to retrieve our conIds, we officially have our option chain established. From there, users may be interested to send requests to the /iserver/marketdata/snapshot endpoint in bulk by comma separating the “conids” list.

Alternatively, users that already are aware of the market data potentially through other means can look to start placing orders using the /iserver/account/{accountId}/orders endpoint.

Contract

Search the security definition by Contract ID

Returns a list of security definitions for the given conids

GET /trsrv/secdef

 

Request Object

Query Prams

conids: int*. Required
A comma separated series of contract IDs.
Value Format: 1234

request_url = f"{baseUrl}/trsrv/secdef?conids=265598"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/trsrv/secdef?conids=265598 \
--request GET

 

Response Object

secdef: array.
Returns the contents of the request with the array.

conid: int.
Returns the conID

currency: String.
Returns the traded currency for the contract.

time: int.
Returns amount of time in ms to generate the data.

chineseName: String.
Returns the Chinese characters for the symbol.

allExchanges: String*.
Returns a series of exchanges the given symbol can trade on.

listingExchange: String.
Returns the primary or listing exchange the contract is hosted on.

countryCode: String.
Returns the country code the contract is traded on.

name: String.
Returns the comapny name.

assetClass: String.
Returns the asset class or security type of the contract.

expiry: String.
Returns the expiry of the contract. Returns null for non-expiry instruments.

lastTradingDay: String.
Returns the last trading day of the contract.

group: String.
Returns the group or industry the contract is affilated with.

putOrCall: String.
Returns if the contract is a Put or Call option.

sector: String.
Returns the contract’s sector.

sectorGroup: String.
Returns the sector’s group.

strike: int.
Returns the strike of the contract.

ticker: String.
Returns the ticker symbol of the traded contract.

undConid: int.
Returns the contract’s underlyer.

multiplier: float,
Returns the contract multiplier.

type: String.
Returns stock type.

hasOptions: bool.
Returns if contract has tradable options contracts.

fullName: String.
Returns symbol name for requested contract.

isUS: bool.
Returns if the contract is US based or not.

incrementRules & displayRule: Array.
Returns rules regarding incrementation for order placement. Not functional for all exchanges. Please see /iserver/contract/rules for more accurate rule details.

isEventContract: bool.
Returns if the contract is an event contract or not.

pageSize: int.
Returns the content size of the request.

{
  "secdef": [
    {
      "conid": 265598,
      "currency": "USD",
      "time": 43,
      "chineseName": "苹果公司",
      "allExchanges": "AMEX,NYSE,CBOE,PHLX,CHX,ARCA,ISLAND,ISE,IDEAL,NASDAQQ,NASDAQ,DRCTEDGE,BEX,BATS,NITEECN,EDGEA,CSFBALGO,JEFFALGO,NYSENASD,PSX,BYX,ITG,PDQ,IBKRATS,CITADEL,NYSEDARK,MIAX,IBDARK,CITADELDP,NASDDARK,IEX,WEDBUSH,SUMMER,WINSLOW,FINRA,LIQITG,UBSDARK,BTIG,VIRTU,JEFF,OPCO,COWEN,DBK,JPMC,EDGX,JANE,NEEDHAM,FRACSHARE,RBCALGO,VIRTUDP,BAYCREST,FOXRIVER,MND,NITEEXST,PEARL,GSDARK,NITERTL,NYSENAT,IEXMID,HRT,FLOWTRADE,HRTDP,JANELP,PEAK6,IMCDP,CTDLZERO,HRTMID,JANEZERO,HRTEXST,IMCLP,LTSE,SOCGENDP,MEMX,INTELCROS,VIRTUBYIN,JUMPTRADE,NITEZERO,TPLUS1,XTXEXST,XTXDP,XTXMID,COWENLP,BARCDP,JUMPLP,OLDMCLP,RBCCMALP,WALLBETH,IBEOS,JONES,GSLP,BLUEOCEAN,USIBSILP,OVERNIGHT,JANEMID,IBATSEOS,HRTZERO,VIRTUALGO",
      "listingExchange": "NASDAQ",
      "countryCode": "US",
      "name": "APPLE INC",
      "assetClass": "STK",
      "expiry": null,
      "lastTradingDay": null,
      "group": "Computers",
      "putOrCall": null,
      "sector": "Technology",
      "sectorGroup": "Computers",
      "strike": "0",
      "ticker": "AAPL",
      "undConid": 0,
      "multiplier": 0.0,
      "type": "COMMON",
      "hasOptions": true,
      "fullName": "AAPL",
      "isUS": true,
      "incrementRules": [
        {
          "lowerEdge": 0.0,
          "increment": 0.01
        }
      ],
      "displayRule": {
        "magnification": 0,
        "displayRuleStep": [
          {
            "decimalDigits": 2,
            "lowerEdge": 0.0,
            "wholeDigits": 4
          }
        ]
      },
      "isEventContract": false,
      "pageSize": 100
    }
  ]
}

 

All Conids by Exchange

Send 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.

GET /trsrv/all-conids

 

Request Object

Query Params

exchange: String. Required
Specify a single exchange to receive conids for.

request_url = f"{baseUrl}/trsrv/all-conids?exchange=AMEX"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/trsrv/all-conids?exchange=AMEX \
--request GET

 

Response Object

ticker: String.
Returns the ticker symbol of the contract

conid: int.
Returns the contract identifier of the returned contract.

exchange: String.
Returns the exchanger of the returned contract.

[
  {
    "ticker": "BMO",
    "conid": 5094,
    "exchange": "NYSE"
  },
  {...},
  {
    "ticker": "ZKH",
    "conid": 671347171,
    "exchange": "NYSE"
  }
]

 

Contract information by Contract ID

Requests full contract details for the given conid

GET /iserver/contract/{conid}/info

 

Request Object

Path Params:

conid: String.
Contract ID for the desired contract information.

request_url = f"{baseUrl}/iserver/contract/265598/info"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/contract/265598/info \ 
--request GET

 

Response Object

conid: int.
Contract ID of the requested contract.

ticker: String.
Ticker symbol of the requested contract.

secType: String.
Security type of the requested contract.

listingExchange: String.
Primary exchange of the requested contract.

exchange: String.
Traded exchange of the requested contract set in the request.

companyName: String.
Company name of the requested contract.

currency: String.
National currency of the requested contract.

validExchanges: String.
All valid exchanges of the requested contract.

priceRendering: String.
Render price of the requested contract.

maturityDate: String.
Maturity, or expiration date, of the requested contract.

right: String.
Right, put or call, of the requested contract.

strike: int.
Strike price of the requested contract.

{
  "cfi_code": "",
  "symbol": "AAPL",
  "cusip": null,
  "expiry_full": null,
  "con_id": 265598,
  "maturity_date": null,
  "industry": "Computers",
  "instrument_type": "STK",
  "trading_class": "NMS",
  "valid_exchanges": "SMART,AMEX,NYSE,CBOE,PHLX,ISE,CHX,ARCA,ISLAND,DRCTEDGE,BEX,BATS,EDGEA,JEFFALGO,BYX,IEX,EDGX,FOXRIVER,PEARL,NYSENAT,LTSE,MEMX,TPLUS1,IBEOS,OVERNIGHT,PSX",
  "allow_sell_long": false,
  "is_zero_commission_security": false,
  "local_symbol": "AAPL",
  "contract_clarification_type": null,
  "classifier": null,
  "currency": "USD",
  "text": null,
  "underlying_con_id": 0,
  "r_t_h": true,
  "multiplier": null,
  "underlying_issuer": null,
  "contract_month": null,
  "company_name": "APPLE INC",
  "smart_available": true,
  "exchange": "SMART",
  "category": "Computers"
}

 

Currency Pairs

Obtains available currency pairs corresponding to the given target currency.

GET /iserver/currency/pairs

 

Request Object

Query Params

currency: String. Required
Specify the target currency you would like to receive official pairs of.
Valid Structure: “USD”

request_url = f"{baseUrl}/iserver/currency/pairs?currency=USD"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/currency/pairs?currency=USD \
--request GET

 

Response Object

{{currency}}: List of Objects.
[{
symbol: String.
The official symbol of the given currency pair.

conid: int.
The official contract identifier of the given currency pair.

ccyPair: String.
Returns the counterpart of
}]

{
  "USD": [
    {
      "symbol": "USD.SGD",
      "conid": 37928772,
      "ccyPair": "SGD"
    },
	{...},
    {
      "symbol": "USD.RUB",
      "conid": 28454968,
      "ccyPair": "RUB"
    }
  ]
}

 

Currency Exchange Rate

Obtains the exchange rates of the currency pair.

GET /iserver/exchangerate

 

Request Object

Query Params

Source: String. Required
Specify the base currency to request data for.
Valid Structure: “AUD”

Target: String. Required
Specify the quote currency to request data for.
Valid Structure: “USD”

request_url = f"{baseUrl}/iserver/exchangerate?target=AUD&source=USD"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/exchangerate?target=AUD&source=USD \
--request GET

 

Response Object

rate: float.
Returns the exchange rate for the currency pair.

{
    "rate": 0.67005002
}

 

Find all Info and Rules for a given contract

Returns both contract info and rules from a single endpoint.
For only contract rules, use the endpoint /iserver/contract/rules.
For only contract info, use the endpoint /iserver/contract/{conid}/info.

GET /iserver/contract/{{ conid }}/info-and-rules

 

Request Object

Path Parameters

coind: String. Required
Contract identifier for the given contract.

Query Parameters

isBuy: bool.
Indicates whether you are searching for Buy or Sell order rules.
Set to true for Buy Orders, set to false for Sell Orders

request_url = f"{baseUrl}/iserver/contract/265598/info-and-rules?isBuy=true"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/contract/265598/info-and-rules?isBuy=true \ 
--request GET

 

Response Object

cfi_code: String.
Classification of Financial Instrument codes

symbol: String.
Underlying symbol

cusip: String.
Returns the CUSIP for the given instrument.
Only used in BOND trading.

expiry_full: String.
Returns the expiration month of the contract.
Formatted as “YYYYMM”

con_id: int.
Indicates the contract identifier of the given contract.

maturity_date: String.
Indicates the final maturity date of the given contract.
Formatted as “YYYYMMDD”

industry: String.
Specific group of companies or businesses.

instrument_type: String.
Asset class of the instrument.

trading_class: String.
Designated trading class of the contract.

valid_exchanges: String.
Comma separated list of support exchanges or trading venues.

allow_sell_long: bool.
Allowed to sell shares you own.

is_zero_commission_security: bool.
Indicates if the contract supports zero commission trading.

local_symbol: String.
Contract’s symbol from primary exchange. For options it is the OCC symbol.

contract_clarification_type: null

classifier: null.

currency: String.
Base currency contract is traded in.

text: String.
Indicates the display name of the contract, as shown with Client Portal.

underlying_con_id: int.
Underlying contract identifier for the requested contract.

r_t_h: bool.
Indicates if the contract can be traded outside regular trading hours or not.

multiplier: String.
Indicates the multiplier of the contract.

underlying_issuer: String.
Indicates the issuer of the underlying.

contract_month: String.
Indicates the year and month the contract expires.
Value Format: “YYYYMM”

company_name: String.
Indicates the name of the company or index.

smart_available: bool.
Indicates if the contract can be smart routed or not.

exchange: String.
Indicates the primary exchange for which the contract can be traded.

category: String.
Indicates the industry category of the instrument.

rules: Object.
See the /iserver/contract/rules endpoint.

{
  "cfi_code": "",
  "symbol": "AAPL",
  "cusip": null,
  "expiry_full": null,
  "con_id": 265598,
  "maturity_date": null,
  "industry": "Computers",
  "instrument_type": "STK",
  "trading_class": "NMS",
  "valid_exchanges": "SMART,AMEX,NYSE,CBOE,PHLX,ISE,CHX,ARCA,ISLAND,DRCTEDGE,BEX,BATS,EDGEA,JEFFALGO,BYX,IEX,EDGX,FOXRIVER,PEARL,NYSENAT,LTSE,MEMX,TPLUS1,IBEOS,OVERNIGHT,PSX",
  "allow_sell_long": false,
  "is_zero_commission_security": false,
  "local_symbol": "AAPL",
  "contract_clarification_type": null,
  "classifier": null,
  "currency": "USD",
  "text": null,
  "underlying_con_id": 0,
  "r_t_h": true,
  "multiplier": null,
  "underlying_issuer": null,
  "contract_month": null,
  "company_name": "APPLE INC",
  "smart_available": true,
  "exchange": "SMART",
  "category": "Computers",
  "rules": {
    "algoEligible": true,
    "overnightEligible": true,
    "costReport": false,
    "canTradeAcctIds": [
      "U1234567"
    ],
    "error": null,
    "orderTypes": [
      "limit",
      "midprice",
      "market",
      "stop",
      "stop_limit",
      "mit",
      "lit",
      "trailing_stop",
      "trailing_stop_limit",
      "relative",
      "marketonclose",
      "limitonclose"
    ],
    "ibAlgoTypes": [
      "limit",
      "stop_limit",
      "lit",
      "trailing_stop_limit",
      "relative",
      "marketonclose",
      "limitonclose"
    ],
    "fraqTypes": [
      "limit",
      "market",
      "stop",
      "stop_limit",
      "mit",
      "lit",
      "trailing_stop",
      "trailing_stop_limit"
    ],
    "forceOrderPreview": false,
    "cqtTypes": [
      "limit",
      "market",
      "stop",
      "stop_limit",
      "mit",
      "lit",
      "trailing_stop",
      "trailing_stop_limit"
    ],
    "orderDefaults": {
      "LMT": {
        "LP": "197.93"
      }
    },
    "orderTypesOutside": [
      "limit",
      "stop_limit",
      "lit",
      "trailing_stop_limit",
      "relative"
    ],
    "defaultSize": 100,
    "cashSize": 0.0,
    "sizeIncrement": 100,
    "tifTypes": [
      "IOC/MARKET,LIMIT,RELATIVE,MARKETONCLOSE,MIDPRICE,LIMITONCLOSE,MKT_PROTECT,STPPRT,a",
      "GTC/o,a",
      "OPG/LIMIT,MARKET,a",
      "GTD/o,a",
      "DAY/o,a"
    ],
    "tifDefaults": {
      "TIF": "DAY",
      "SIZE": "100.00"
    },
    "limitPrice": 197.93,
    "stopprice": 197.93,
    "orderOrigination": null,
    "preview": true,
    "displaySize": null,
    "fraqInt": 4,
    "cashCcy": "USD",
    "cashQtyIncr": 500,
    "priceMagnifier": null,
    "negativeCapable": false,
    "incrementType": 1,
    "incrementRules": [
      {
        "lowerEdge": 0.0,
        "increment": 0.01
      }
    ],
    "hasSecondary": true,
    "increment": 0.01,
    "incrementDigits": 2
  }
}

 

Search Algo Params by Contract ID

Returns supported IB Algos for contract.

A pre-flight request must be submitted before retrieving information

GET /iserver/contract/{{ conid }}/algos

 

Request Object

Path Parameters

conid: String. Required
Contract identifier for the requested contract of interest.

Query Parameters

algos: String. Optional
List of algo ids delimited by “;” to filter by.
Max of 8 algos ids can be specified.
Case sensitive to algo id.

addDescription: String. Optional
Whether or not to add algo descriptions to response. Set to 1 for yes, 0 for no.

addParams: String. Optional
Whether or not to show algo parameters. Set to 1 for yes, 0 for no.

request_url = f"{baseUrl}/iserver/contract/265598/algos?algos=Adaptive;Vwap&addDescription=1&addParams=1"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/contract/265598/algos?algos=Adaptive;Vwap&addDescription=1&addParams=1 \
--request GET

 

Response Object

algos: Array of objects.
Contains all relevant algos for the contract.

[{

name: String.
Common name of the algo.

id: String.
Algo identifier used for requests

parameters: Array of objects.
All parameters relevant to the given algo.
Only returned if addParams=1

[{

guiRank: int.
Positional ranking for the algo. Used for Client Portal.

defaultValue: int.
Default parameter value.

name: String.
Parameter name.

id: String.
Parameter identifier for the algo.

legalStrings: Array
Allowed values for the parameter.

required: String.
States whether the parameter is required for the given algo order to place.
Returns a string representation of a boolean.

valueClassName: String.
Returns the variable type of the parameter.
}]
}]

{
  "algos": [
    {
      "name": "Adaptive",
      "id": "Adaptive",
      "parameters": [
        {
          "guiRank": 1,
          "defaultValue": "Normal",
          "name": "Adaptive order priority/urgency",
          "id": "adaptivePriority",
          "legalStrings": [
            "Urgent",
            "Normal",
            "Patient"
          ],
          "required": "true",
          "valueClassName": "String"
        }
      ]
    },
    {
      "name": "VWAP",
      "id": "Vwap",
      "parameters": [
        {
          "guiRank": 5,
          "defaultValue": false,
          "name": "Attempt to never take liquidity",
          "id": "noTakeLiq",
          "valueClassName": "Boolean"
        },
        {
          "guiRank": 11,
          "defaultValue": false,
          "name": "Opt-out closing auction",
          "id": "optoutClosingAuction",
          "valueClassName": "Boolean"
        },
        {
          "guiRank": 4,
          "defaultValue": false,
          "name": "Allow trading past end time",
          "id": "allowPastEndTime",
          "valueClassName": "Boolean"
        },
        {
          "guiRank": 8,
          "defaultValue": false,
          "name": "Speed up when market approaches limit price",
          "description": "Compensate for decreased fill rate due to presence of limit price.",
          "id": "speedUp",
          "enabledConditions": [
            "MKT:speedUp:=:no"
          ],
          "valueClassName": "Boolean"
        },
        {
          "guiRank": 12,
          "name": "Trade when price is more aggressive than:",
          "description": "Evaluates with bid for buy order and ask for sell order",
          "id": "conditionalPrice",
          "valueClassName": "Double"
        },
        {
          "guiRank": 2,
          "name": "Start Time",
          "description": "Defaults to start of market trading",
          "id": "startTime",
          "valueClassName": "Time"
        },
        {
          "guiRank": 1,
          "minValue": 0.01,
          "maxValue": 50,
          "name": "Max Percentage",
          "description": "From 0.01 to 50.0",
          "id": "maxPctVol",
          "valueClassName": "Double"
        },
        {
          "guiRank": 3,
          "name": "End Time",
          "description": "Defaults to end of market trading",
          "id": "endTime",
          "valueClassName": "Time"
        }
      ]
    }
  ]
}

 

Search Bond Filter Information

Request a list of filters relating to a given Bond issuerID. The issuerId is retrieved from /iserver/secdef/search and can be used in /iserver/secdef/info?issuerId={{ issuerId }} for retrieving conIds.

/iserver/secdef/bond-filters

 

Request Object

Query Params

symbol: String. Required
This should always be set to “BOND”

issuerId: String. Required
Specifies the issuerId value used to designate the bond issuer type.

request_url = f"{baseUrl}/iserver/secdef/bond-filters?symbol=BOND&issuerId=e1400715"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/secdef/bond-filters?symbol=BOND&issuerId=e1400715 \
--request GET

 

bondFilters: Array of Objects.
Contains all filters pertaining to the given issuerId.
[{
displayText: String.
An identifier used to document returned options/values. This can be thought of as a key value.

columnId: int.
Used for user interfaces. Internal use only.

options: Array of objects.
Contains all objects with values corresponding to the parent displayText key.
[{
text: String.
In some instances, a text value will be returned, which indicates the standardized value format such as plaintext dates, rather than solely numerical values.

value: String.
Returns value directly correlating to the displayText key. This may include exchange, maturity date, issue date, coupon, or currency.

}]

}]

{
  "bondFilters": [
    {
      "displayText": "Exchange",
      "columnId": 0,
      "options": [
      {
        "value": "SMART"
      }]
    },
    {
      "displayText": "Maturity Date",
      "columnId": 27,
      "options": [
        {
          "text": "Jan 2025",
          "value": "202501"
      }]
    },
    {
      "displayText": "Issue Date",
      "columnId": 28,
      "options": [{
        "text": "Sep 18 2014",
        "value": "20140918"
      }]
    },
    {
      "displayText": "Coupon",
      "columnId": 25,
      "options": [{
        "value": "1.301"
      }]
    },
    {
      "displayText": "Currency",
      "columnId": 5,
      "options": [{
        "value": "EUR"
      }]
    }
  ]
}

 

Search Contract by Symbol

Search by underlying symbol or company name. Relays back what derivative contract(s) it has. This endpoint must be called before using /secdef/info.
If company name is specified will only receive limited response: conid, companyName, companyHeader and symbol.

For bonds, enter the family type in the symbol field to receive the issuerID used in the /iserver/secdef/info endpoint.

GET /iserver/secdef/search

 

Request Object

Query Params

symbol: String. Required
Underlying symbol of interest. May also pass company name if ‘name’ is set to true, or bond issuer type to retrieve bonds.

name: bool.
Determines if symbol reflects company name or ticker symbol.

secType: String.
Valid Values: “STK”, “IND”, “BOND”
Declares underlying security type.

 

request_url = f"{baseUrl}/iserver/secdef/search?symbol=Interactive Brokers&name=true"
requests.get(url=request_url)

 

curl --insecure \
--url https://localhost:5000/v1/api/iserver/secdef/search?symbol=Interactive Brokers&name=true \
--request GET

 

Response Object

“conid”: String.
Conid of the given contract.

“companyHeader”: String.
Extended company name and primary exchange.

“companyName”: String.
Name of the company.

“symbol”: String.
Company ticker symbol.

“description”: String.
Primary exchange of the contract.

“restricted”: bool.
Returns if the contract is available for trading.

“fop”: String.
Returns a string of dates, separated by semicolons.
Value Format: “YYYYMMDD;YYYYMMDD;YYYYMMDD”

“opt”: String.
Returns a string of dates, separated by semicolons.
Value Format: “YYYYMMDD;YYYYMMDD;YYYYMMDD”

“war”: String.
Returns a string of dates, separated by semicolons.
Value Format: “YYYYMMDD;YYYYMMDD;YYYYMMDD”

“sections”: Array of objects

“secType”: String.
Given contracts security type.

“months”: String.
Returns a string of dates, separated by semicolons.
Value Format: “JANYY;FEBYY;MARYY”

“symbol”: String.
Symbol of the instrument.

“exchange”: String.
Returns a string of exchanges, separated by semicolons.
Value Format: “EXCH;EXCH;EXCH”

Unique for Bonds
“issuers”: Array of objects
Array of objects containing the id and name for each bond issuer.

“id”: String.
Issuer Id for the given contract.

“name”: String.
Name of the issuer.

“bondid”: int.
Bond type identifier.

“conid”: String.
Contract ID for the given bond.

“companyHeader”: String.
Name of the bond type
Value Format: “Corporate Fixed Income”

“companyName”: null
Returns ‘null’ for bond contracts.

“symbol”:null
Returns ‘null’ for bond contracts.

“description”:null
Returns ‘null’ for bond contracts.

“restricted”:null
Returns ‘null’ for bond contracts.

“fop”:null
Returns ‘null’ for bond contracts.

“opt”:null
Returns ‘null’ for bond contracts.

“war”:null
Returns ‘null’ for bond contracts.

“sections”: Array of objects
Only relays “secType”:”BOND” in the Bonds section.

[
  {
    "conid": "43645865",
    "companyHeader": "IBKR INTERACTIVE BROKERS GRO-CL A (NASDAQ) ",
    "companyName": "INTERACTIVE BROKERS GRO-CL A (NASDAQ)",
    "symbol": "IBKR",
    "description": null,
    "restricted": null,
    "fop": null,
    "opt": null,
    "war": null,
    "sections": [],
    "secType": "STK"
  }
]

 

Search Contract Rules

Returns trading related rules for a specific contract and side.

POST /iserver/contract/rules

 

Request Object

Body Parameters

conid: Number. Required
Contract identifier for the interested contract.

exchange: String.
Designate the exchange you wish to receive information for in relation to the contract.

isBuy: bool.
Side of the market rules apply too. Set to true for Buy Orders, set to false for Sell Orders
Defaults to true or Buy side rules.

modifyOrder: bool.
Used to find trading rules related to an existing order.

orderId: Number. Required for modifyOrder:true
Specify the order identifier used for tracking a given order.

request_url = f"{baseUrl}/iserver/contract/rules"
json_content = {
  "conid": 265598,
  "exchange": "SMART",
  "isBuy": true,
  "modifyOrder": true,
  "orderId": 1234567890
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/contract/rules \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "conid": 265598,
  "exchange": "SMART",
  "isBuy": true,
  "modifyOrder": true,
  "orderId": 1234567890
}'

 

Response Object

algoEligible: bool.
Indicates if the contract can trade algos or not.

overnightEligible: bool.
Indicates if outsideRTH trading is permitted for the instrument

costReport: bool.
Indicates whether or not a cost report has been requested (Client Portal only).

canTradeAcctIds: Array of Strings.
Indicates permitted accountIDs that may trade the contract.

error: String.
If rules information can not be received for any reason, it will be expressed here.

orderTypes: Array of Strings
Indicates permitted order types for use with standard quantity trading.

ibAlgoTypes: Array of Strings.
Indicates permitted algo types for use with the given contract.

fraqTypes: Array of Strings.
Indicates permitted order types for use with fractional trading.

forceOrderPreview: bool.
Indicates if the order preview is forced upon the user before submission.

cqtTypes: Array of Strings.
Indicates accepted order types for use with cash quantity.

orderDefaults: Object of objects
Indicates default order type for the given security type.

orderTypesOutside: Array of Strings.
Indicates permitted order types for use outside of regular trading hours.

defaultSize: int.
Default total quantity value for orders.

cashSize: float.
Default cash value quantity.

sizeIncrement: int.
Indicates quantity increase for the contract.

tifTypes: Array of Strings.
Indicates allowed tif types supported for the contract.

tifDefaults: Object.
Object containing details about your TIF value defaults.
These defaults can be viewed and modified in TWS’s within the Global Configuration.

limitPrice: float.
Default limit price for the given contract.

stopprice: float.
Default stop price for the given contract.

orderOrigination: String.
Order origin designation for US securities options and Options Clearing Corporation

preview: bool.
Indicates if the order preview is required (for client portal only)

displaySize: int.

fraqInt: int.
Indicates decimal places for fractional order size

cashCcy: String.
Indicates base currency for the instrument.

cashQtyIncr: int.
Indicates cash quantity increment rules.

priceMagnifier: int.
Signifies the magnifier of a given contract.
This is separate from the price multiplier, and will typically return ‘null’

negativeCapable: bool.
Indicates if the value of the contract can be negative (true) or if it is always positive (false).

incrementType: int.
Indicates the type of increment style.

incrementRules: Array of objects.
Indicates increment rule values including lowerEdge and increment value.

hasSecondary: bool.

modTypes: Array of Strings.
Lists the available order types supported when modifying the order.

increment: float.
Minimum increment values for prices

incrementDigits: int.
Number of decimal places to indicate the increment value.

{
  "algoEligible": true,
  "overnightEligible": true,
  "costReport": false,
  "canTradeAcctIds": [
    "U1234567"
  ],
  "error": null,
  "orderTypes": [
    "limit",
    "midprice",
    "market",
    "stop",
    "stop_limit",
    "mit",
    "lit",
    "trailing_stop",
    "trailing_stop_limit",
    "relative",
    "marketonclose",
    "limitonclose"
  ],
  "ibAlgoTypes": [
    "limit",
    "stop_limit",
    "lit",
    "trailing_stop_limit",
    "relative",
    "marketonclose",
    "limitonclose"
  ],
  "fraqTypes": [],
  "forceOrderPreview": false,
  "cqtTypes": [
    "limit",
    "market",
    "stop",
    "stop_limit",
    "mit",
    "lit",
    "trailing_stop",
    "trailing_stop_limit"
  ],
  "orderDefaults": {
    "LMT": {
      "LP": "549000.00"
    }
  },
  "orderTypesOutside": [
    "limit",
    "stop_limit",
    "lit",
    "trailing_stop_limit",
    "relative"
  ],
  "defaultSize": 100,
  "cashSize": 0.0,
  "sizeIncrement": 1,
  "tifTypes": [
    "IOC/MARKET,LIMIT,RELATIVE,MARKETONCLOSE,MIDPRICE,LIMITONCLOSE,MKT_PROTECT,STPPRT,a",
    "GTC/o,a",
    "OPG/LIMIT,MARKET,a",
    "GTD/o,a",
    "DAY/o,a"
  ],
  "tifDefaults": {
    "TIF": "DAY",
    "SIZE": "100.00"
  },
  "limitPrice": 549000.0,
  "stopprice": 549000.0,
  "orderOrigination": null,
  "preview": true,
  "displaySize": null,
  "fraqInt": 0,
  "cashCcy": "USD",
  "cashQtyIncr": 500,
  "priceMagnifier": null,
  "negativeCapable": false,
  "incrementType": 1,
  "incrementRules": [
    {
      "lowerEdge": 0.0,
      "increment": 0.01
    }
  ],
  "hasSecondary": true,
  "increment": 0.01,
  "incrementDigits": 2
}

 

Search SecDef information by conid

Provides Contract Details of Futures, Options, Warrants, Cash and CFDs based on conid.

For all instruments, /iserver/secdef/search must be called first.

For derivatives such as Options, Warrants, and Futures Options, you will need to query /iserver/secdef/strikes as well.

GET /iserver/secdef/info

 

Request Object

Query Parameters

conid: String. Required
Contract identifier of the underlying. May also pass the final derivative conid directly.

sectype: String. Required
Security type of the requested contract of interest.

month: String. Required for Derivatives
Expiration month for the given derivative.

exchange: String. Optional
Designate the exchange you wish to receive information for in relation to the contract.

strike: String. Required for Options and Futures Options
Set the strike price for the requested contract details

right: String. Required for Options
Set the right for the given contract.
Value Format: “C” for Call or “P” for Put.

issuerId: String. Required for Bonds
Set the issuerId for the given bond issuer type.
Example Format: “e1234567”

request_url = f"{baseUrl}/iserver/secdef/info?conid=265598&secType=OPT&month=JAN24&strike=195&right=P"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/secdef/info?conid=265598&secType=OPT&month=JAN24&strike=195&right=P \
--request GET

 

Response Object

conid: int.
Contract Identifier of the given contract

ticker: String
Ticker symbol for the given contract

secType: String.
Security type for the given contract.

listingExchange: String.
Primary listing exchange for the given contract.

exchange: String.
Exchange requesting data for.

companyName: String.
Name of the company for the given contract.

currency: String
Traded currency allowed for the given contract.

validExchanges: String*
Series of all valid exchanges the contract can be traded on in a single comma-separated string.
priceRendering: null.

maturityDate: String
Date of expiration for the given contract.

right: String.
Right (P or C) for the given contract.

strike: Float.
Returns the given strike value for the given contract.

[
  {
    "conid": 667629330,
    "symbol": "AAPL",
    "secType": "OPT",
    "exchange": "SMART",
    "listingExchange": null,
    "right": "P",
    "strike": 195.0,
    "currency": "USD",
    "cusip": null,
    "coupon": "No Coupon",
    "desc1": "AAPL",
    "desc2": "JAN 05 '24 195 Put",
    "maturityDate": "20240105",
    "multiplier": "100",
    "tradingClass": "AAPL",
    "validExchanges": "SMART,AMEX,CBOE,PHLX,PSE,ISE,BOX,BATS,NASDAQOM,CBOE2,NASDAQBX,MIAX,GEMINI,EDGX,MERCURY,PEARL,EMERALD,MEMX,IBUSOPT"
  }
]

 

Search Strikes by Underlying Contract ID

Query to receive a list of potential strikes supported for a given underlying.

This endpoint will always return empty arrays unless  /iserver/secdef/search is called for the same underlying symbol beforehand.

 

GET /iserver/secdef/strikes

Request Object

Query Parameters

conid: String. Required
Contract Identifier number for the underlying

sectype: String. Required
Security type of the derivatives you are looking for.
Value Format: “OPT” or “WAR”

month: String. Required
Expiration month and year for the given underlying
Value Format: {3 character month}{2 character year}
Example: AUG23

exchange: String. Optional
Exchange from which derivatives should be retrieved from.
Default value is set to SMART

request_url = f"{baseUrl}/iserver/secdef/strikes?conid=265598&sectype=OPT&month=JAN24&exchange=SMART"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/secdef/strikes?conid=265598&sectype=OPT&month=JAN24&exchange=SMART \
--request GET

 

Response Object

call: Array of Floats
Array containing a series of comma separated float values representing potential call strikes for the instrument.

put: Array of Floats
Array containing a series of comma separated float values representing potential put strikes for the instrument.

{
  "call":[
    185.0,
    190.0,
    195.0,
    200.0
  ],
  "put":[
    185.0,
    190.0,
    195.0,
    200.0
  ]
}

 

Security Future by Symbol

Returns a list of non-expired future contracts for given symbol(s)

GET /trsrv/futures

 

Request Object

Query Params

symbols: String. Required
Indicate the symbol(s) of the underlier you are trying to retrieve futures on. Accepts comma delimited string of symbols.

request_url = f"{baseUrl}/trsrv/futures?symbols=ES,MES"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/trsrv/futures?symbols=ES,MES \
--request GET

 

Response Body

symbol: Array
Displayed as the string of your symbol
Contains a series of objects for each symbol that matches the requested.

symbol: String.
The requested symbol value.

conid: int.
Contract identifier for the specific symbol

underlyingConid: int.
Contract identifier for the future’s underlying contract.

expirationDate: int.
Expiration date of the specific future contract.

ltd: int.
Last trade date of the future contract.

shortFuturesCutOff: int.
Represents the final day for contract rollover for shorted futures.

longFuturesCutOff: int.
Represents the final day for contract rollover for long futures.

{
  "ES": [
    {
      "symbol": "ES",
      "conid": 495512552,
      "underlyingConid": 11004968,
      "expirationDate": 20231215,
      "ltd": 20231214,
      "shortFuturesCutOff": 20231214,
      "longFuturesCutOff": 20231214
    },
    {...}
  ],
  "MES": [
    {
      "symbol": "MES",
      "conid": 586139726,
      "underlyingConid": 362673777,
      "expirationDate": 20231215,
      "ltd": 20231215,
      "shortFuturesCutOff": 20231215,
      "longFuturesCutOff": 20231215
    },
    {...}
  ]
}

 

Security Stocks by Symbol

Returns an object contains all stock contracts for given symbol(s)

GET /trsrv/stocks

 

Request Object

Query Params

symbols: String.
Comma-separated list of stock symbols. Symbols must contain only capitalized letters.

request_url = f"{baseUrl}/trsrv/stocks?symbols=AAPL,IBKR"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/trsrv/stocks?symbols=AAPL,IBKR\
--request GET

 

Response Object

symbol: Array of Json
Contains a series of Json for all contracts that match the symbol.

name: String.
Full company name for the given contract.

chineseName: String.
Chinese name for the given company.

assetClass: String.
Asset class for the given company.

contracts: Array.
A series of arrays pertaining to the same company listed by “name”.
Typically differentiated based on currency of the primary exchange.

conid: int.
Contract ID for the specific contract.

exchange: String.
Primary exchange for the given contract.

isUS: bool.
States whether the contract is hosted in the United States or not.

{
  "AAPL": [
    {
      "name": "APPLE INC",
      "chineseName": "苹果公司",
      "assetClass": "STK",
      "contracts": [
        {
          "conid": 265598,
          "exchange": "NASDAQ",
          "isUS": true
        },
        {
          "conid": 38708077,
          "exchange": "MEXI",
          "isUS": false
        },
        {
          "conid": 273982664,
          "exchange": "EBS",
          "isUS": false
        }
      ]
    },
    {
      "name": "LS 1X AAPL",
      "chineseName": null,
      "assetClass": "STK",
      "contracts": [
        {
          "conid": 493546048,
          "exchange": "LSEETF",
          "isUS": false
        }
      ]
    },
    {
      "name": "APPLE INC-CDR",
      "chineseName": "苹果公司",
      "assetClass": "STK",
      "contracts": [
        {
          "conid": 532640894,
          "exchange": "AEQLIT",
          "isUS": false
        }
      ]
    }
  ]
}

 

Trading Schedule by Symbol

Returns the trading schedule up to a month for the requested contract

GET /trsrv/secdef/schedule

 

Request Object

Query Params

assetClass: String. Required
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

symbol: String. Required
Specify the symbol for your contract.

exchange: String.
Specify the primary exchange of your contract.

exchangeFilter: String.
Specify all exchanges you want to retrieve data from.

request_url = f"{baseUrl}/trsrv/schedule?assetClass=STK&symbol=AAPL&exchange=ISLAND&exchangeFilter=ISLAND,NYSE,AMEX"
requests.get(url=requests_url)

 

curl \
--url {{baseUrl}}/trsrv/schedule?assetClass=STK&symbol=AAPL&exchange=ISLAND&exchangeFilter=ISLAND,NYSE,AMEX \
--request GET

 

Response Object

id: String.
Exchange parameter id

tradeVenueId: String.
Reference on a trade venue of given exchange parameter

schedules: Array of Objets.
Always contains at least one ‘tradingTime’ and zero or more ‘sessionTime’ tags

clearingCycleEndTime: int.
End of clearing cycle.

tradingScheduleDate: int.
Date of the clearing schedule.
20000101 stands for any Sat, 20000102 stands for any Sun, … 20000107 stands for any Fri. Any other date stands for itself.

sessions: Object.
description: String.
If the LIQUID hours differs from the total trading day then a separate ‘session’ tag is returned.

openingTime: int.
Opening date time of the session.

closingTime: int.
Closing date time of the sesion.

prop: String.
If the whole trading day is considered LIQUID then the value ‘LIQUID’ is returned.

tradingTimes: Object.
Object containing trading times.

description: String
Returns tradingTime in exchange time zone.

openingTime: int.
Opening time of the trading day.

closingTime: int.
Closing time of the trading day.

cancelDayOrders: string.
Cancel time for day orders.

[
  {
    "id": "p102082",
    "tradeVenueId": "v13133",
    "timezone": "America/New_York",
    "schedules": [      
      {
        "clearingCycleEndTime": "2000",
        "tradingScheduleDate": "20000103",
        "sessions": [
          {
            "openingTime": "0930",
            "closingTime": "1600",
            "prop": "LIQUID"
          }
        ],
        "tradingtimes": [
          {
            "openingTime": "0400",
            "closingTime": "2000",
            "cancelDayOrders": "Y"
          }
        ]
      },
      {...}
    ]
  }
]

 

FA Allocation Management

Allocatable Sub-Accounts

Retrieves a list of all sub-accounts and returns their net liquidity and available equity for advisors to make decisions on what accounts should be allocated and how.

GET /iserver/account/allocation/accounts

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/iserver/account/allocation/accounts" 
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/allocation/accounts \
--request GET

 

Response Object

accounts: Array of objects.
Array containing all sub-accounts held by the advisor.
[{
data: Array of objects.
Contains Net liquidation and available equity of the given account Id.
[{
value: String.
Contains the price value affiliated with the key.

key: String.
Defines the value of the object.
Expected values: “AvailableEquity”, “NetLiquidation”
}]
name: String.
Returns the account ID affiliated with the balance data.
}]

{
  "accounts": [
    {
      "data": [
        {
          "value": "2677.89",
          "key": "NetLiquidation"
        },
        {
          "value": "2134.76",
          "key": "AvailableEquity"
        }
      ],
      "name": "U123456"
    },
    {
      "data": [
        {
          "value": "1200.88",
          "key": "NetLiquidation"
        },
        {
          "value": "1000.56",
          "key": "AvailableEquity"
        }
      ],
      "name": "U456789"
    }
  ]
}

 

List All Allocation Groups

Retrieves a list of all of the advisor’s allocation groups. This describes the name of the allocation group, number of subaccounts within the group, and the method in use for the group.

GET /iserver/account/allocation/group

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/iserver/account/allocation/group" 
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/allocation/group \
--request GET

 

Response Object

data: Array of objects.
Contains object pairs for each allocation groups
[{
allocation_method: String.
Uses the Allocation Method Code to represent which method is implemented.

size: int.
Represents the total number of sub-accounts within the group.

name: String.
The name set for the given allocation group.
}]

{
  "data": [
    {
      "allocation_method": "N",
      "size": 10,
      "name": "Group_1_NetLiq"
    }
  ]
}

 

Retrieve Single Allocation Group

Retrieves the configuration of a single account group. This describes the name of the allocation group, the specific accounts contained in the group, and the allocation method in use along with any relevant quantities.

POST /iserver/account/allocation/group/single

 

Request Object

Body Params

name: String. Required.
Name of an existing allocation group.

request_url = f"{baseUrl}/iserver/account/allocation/group/single" 
json_content ={
  "name":"Group_1_NetLiq"
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/account/allocation/group/single \
--request POST
--header 'Content-Type:application/json' \
--data '{"name":"Group_1_NetLiq"}'

 

Response Object

{
name:
String. Required Required
Name used to refer to your allocation group. This will be used while placing orders.

accounts: Array of objects. Required
Contains a series of objects depicting which accounts are involved and, for user-defined allocation methods, the distribution value for each sub-account.
[
{
name: String. Required
The accountId of a given sub-account.
Value Format: “U1234567”

amount: Number.
The total distribution value for each sub-account for user-defined allocation methods.
}
]
default_method: String.
Specify the allocation method code for the allocation group.
See Allocation Method Codes for more details.
}

{
  "name": "Group_1_NetLiq",
  "accounts": [
    {
      "amount": 1,
      "name": "DU1234567"
    },
    {
      "amount": 5,
      "name": "DU9876543"
    }
  ],
  "default_method": "R"
}

Add Allocation Group

Add a new allocation group. This group can be used to trade

POST /iserver/account/allocation/group

 

Request Object

Body Params

name: String. Required Required
Name used to refer to your allocation group. This will be used while placing orders.

accounts: Array of objects. Required
Contains a series of objects depicting which accounts are involved and, for user-defined allocation methods, the distribution value for each sub-account.
[{
name: String. Required
The accountId of a given sub-account.
Value Format: “U1234567”

amount: Number.
The total distribution value for each sub-account for user-defined allocation methods.
}]
default_method: String.
Specify the allocation method code for the allocation group.
See Allocation Method Codes for more details.

request_url = f"{baseUrl}/iserver/account/allocation/group"
json_content = {
  "name":"Group_1_NetLiq",
  "accounts":[{
    "name":"U1234567",
    "amount":10
  },{
    "name":"U2345678",
    "amount":5
  }],
  "default_method":"N"
}
requests.post(url=request_url, json=json_content

 

curl \
--url {{baseUrl}}/iserver/account/allocation/group \
--request POST
--header 'Content-Type:application/json' \
--data '{
  "name":"Group_1_NetLiq",
  "accounts":[{
    "name":"U1234567",
    "amount":10
  },{
    "name":"U2345678",
    "amount":5
  }],
  "default_method":"N"
}'

 

Response Object

success: bool.
Confirms that the allocation group was properly set.

{
  "success": true
}

 

Modify Allocation Group

Modify an existing allocation group.

PUT /iserver/account/allocation/group

 

Request Object

Body Params

name: String. Required Required
Name used to refer to your allocation group. If prev_name is specified, this will become the new name of the group.

prev_name: String.
Name used to refer to your existing allocation group.
Only use this when updating the group name.

accounts: Array of objects. Required
Contains a series of objects depicting which accounts are involved and, for user-defined allocation methods, the distribution value for each sub-account.
[{
name: String. Required
The accountId of a given sub-account.
Value Format: “U1234567”

amount: Number.
The total distribution value for each sub-account for user-defined allocation methods.
}]
default_method: String. Required
Specify the allocation method code for the allocation group.
See Allocation Method Codes for more details.

request_url = f"{baseUrl}/iserver/account/allocation/group"
json_content = {
  "name":"Group_1_NetLiq",
  "accounts":[{
    "name":"U1234567",
    "amount":15
  },{
    "name":"U2345678",
    "amount":10
  }],
  "default_method":"N"
}
requests.put(url=request_url, json=json_content

 

curl \
--url {{baseUrl}}/iserver/account/allocation/group \
--request PUT
--header 'Content-Type:application/json' \
--data '{
  "name":"new_test_group",
  "prev_name":"Group_1_NetLiq",
  "accounts":[{
    "name":"U1234567",
    "amount":10
  },{
    "name":"U2345678",
    "amount":5
  }],
  "default_method":"A"
}'

 

Response Object

success: bool.
Confirms that the allocation group was properly set.

{
  "success": true
}

 

Delete Allocation Group

Remove an existing allocation group. This group will no longer be accessible.

POST /iserver/account/allocation/group/delete

 

Request Object

Body Params

name: String. Required Required
Name used to refer to your allocation group.

request_url = f"{baseUrl}/iserver/account/allocation/group/delete"
json_content = {
  "name":"Group_1_NetLiq",
}
requests.post(url=request_url, json=json_content

 

curl \
--url {{baseUrl}}/iserver/account/allocation/group/delete \
--request POST
--header 'Content-Type:application/json' \
--data '{
  "name":"Group_1_NetLiq",
}'

 

Response Object

success: bool.
Confirms that the allocation group was properly set.

{
  "success": true
}

 

Retrieve Allocation Presets

Retrieve the preset behavior for allocation groups for specific events.

GET /iserver/account/allocation/presets

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/iserver/marketdata/unsubscribeall"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/allocation/presets \
--request GET

 

Response Object

group_auto_close_positions: bool.

default_method_for_all: String.

profiles_auto_close_positions: bool.

strict_credit_check: bool.

group_proportional_allocation: bool.

{
  "group_auto_close_positions": false,
  "default_method_for_all": "N",
  "profiles_auto_close_positions": false,
  "strict_credit_check": false,
  "group_proportional_allocation": false
}

Set Allocation Presets

Set the preset behavior for allocation groups for specific events.

POST /iserver/account/allocation/presets

 

Request Object

Body Params

default_method_for_all: String. Required
Set the default allocation method to be used for all allocation groups without a set value.

group_auto_close_positions: bool. Required

profiles_auto_close_positions: bool. Required

strict_credit_check: bool. Required

group_proportional_allocation: bool. Required

request_url = f"{baseUrl}/iserver/account/allocation/presets" 
json_content = {
  "default_method_for_all": "E",
  "group_auto_close_positions": true,
  "profiles_auto_close_positions": true,
  "strict_credit_check": false,
  "group_proportional_allocation": false
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/account/allocation/presets \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "default_method_for_all": "E",
  "group_auto_close_positions": true,
  "profiles_auto_close_positions": true,
  "strict_credit_check": false,
  "group_proportional_allocation": false
}'

 

Response Object

success: bool.
Confirms that the preset was properly set.

{
  "success": true
}

Allocation Method Codes

Interactive Brokers supports two forms of allocation methods. Allocation methods that have calculations completed by Interactive Brokers, and a set of allocation methods calculated by the user and then specified.

IB-computed allocation methods

Method Code
Available Equity A
Equal E
Net Liquidation Value N

User-specified allocation methods

Formerly known as Allocation Profiles
Method Code
Cash Quantity C
Percentages P
Ratios R
Shares S

Allocation Preset Combinations

In order to attain specific allocation behaviors, a combination of various settings must be specified. The tables below detail what settings must be used.Interactive Brokers supports two forms of allocation methods. Allocation methods that have calculations completed by Interactive Brokers, and a set of allocation methods calculated by the user and then specified.

The preset settings are based on the Advisor Presets setting built in TWS.
Every time a user logs in to TWS, the presets established in the CPAPI will update to reflect the settings in TWS.
Presets adjusted in the Client Portal API will not adjust the settings in TWS.

IB-computed allocation methods

Intended Behavior Proportional Allocation Closing Behavior
Make positions be proportional based on method group_proportional_allocation=false group_auto_close_positions=true
Distribute shares based on method selected group_proportional_allocation=true group_auto_close_positions=true
Distribute shares based on method selected, do not prioritize accounts that are closing position group_proportional_allocation=true group_auto_close_positions=false

User-specified allocation methods

Formerly known as Allocation Profiles
Intended Behavior Closing Behavior
Distribute shares based on method selected profile_auto_close_positions=true
Distribute shares based on method selected, do not prioritize accounts that are closing position profile_auto_close_positions=false

FYIs and Notifications

Unread Bulletins

Returns the total number of unread fyis

GET /fyi/unreadnumber

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/fyi/unreadnumber"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/fyi/unreadnumber \
--request GET

 

Response Object

BN: int.
Returns the number of unread bulletins.

{
  "BN": 4
}

 

Get a List of Subscriptions

Return the current choices of subscriptions for notifications.

GET /fyi/settings

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/fyi/settings"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/fyi/settings \
--request GET

 

Response Object

A: int.
Returns if the subscription can be modified.
Only returned if the subscription can be modified.
See /fyi/settings/{typecode} for how to modify.

FC: String.
Fyi code for enabling or disabling the notification.

H: int.
Disclaimer if the notification was read.
Value Format: 0: Unread; 1: Read

FD: String.
Returns a detailed description of the topic.

FN: String.
Returns a human readable title for the notification.

[
  {
    "FC": "M8",
    "H": 0,
    "A": 1,
    "FD": "Notify me when I establish position subject to US dividend tax withholding 871(m) rules.",
    "FN": "871(m) Trades"
  },
  {
    "FC": "AA",
    "H": 0,
    "A": 1,
    "FD": "Notifications related to account activity such as funding, application, trading and market data permission status",
    "FN": "Account Activity"
  },
  {...}
]

 

Enable/Disable Specified Subscription

Configure which typecode you would like to enable/disable.

POST /fyi/settings/{{ typecode }}

 

Request Object

Path Params

typecode: String. Required
Code used to signify a specific type of FYI template.
See Typecode section for more details.

Body Params

enabled: bool. Required
Enable or disable the subscription.
See available typecodes under FYI Typecodes
Value format: true: Enable; false: Disable

request_url = f"{baseUrl}/fyi/settings/SM"
json_content ={"enabled":true}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/fyi/settings/SM \
--request POST \
--data '{"enabled":true}'

 

Response Object

V: int.
Returns 1 to state message was acknowledged.

T: int.
Returns the time in ms to complete the edit.

{
  "V": 1,
  "T": 10
}

 

FYI Typecodes

Many FYI endpoints reference a “typecode” value. The table below lists the available codes and what they correspond to.

Typecode Description
BA Borrow Availability
CA Comparable Algo
DA Dividends Advisory
EA Upcoming Earnings
MF Mutual Fund Advisory
OE Option Expiration
PR Portfolio Builder Rebalance
SE Suspend Order on Economic Event
SG Short Term Gain turning Long Term
SM System Messages
T2 Assignment Realizing Long-Term Gains
TO Takeover
UA User Alert
M8 M871 Trades
PS Platform Use Suggestions
DL Unexercised Option Loss Prevention Reminder
PT Position Transfer
CB Missing Cost Basis
MS Milestones
TD MiFID || 10% Deprecation Notice
ST Save Taxes
TI Trade Idea
CT Cash Transfer

Get disclaimer for a certain kind of fyi

Receive additional disclaimers based on the specified typecode.

GET /fyi/disclaimer/{typecode}

 

Request Object

Path Params

typecode: String. Required
Code used to signify a specific type of FYI template.
See FYI Typecodes section for more details.

request_url = f"{baseUrl}/fyi/disclaimer/SM"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/fyi/disclaimer/SM\
--request GET

 

Response Object

FC: String.
Returns the Typecode for the given disclaimer.

DT: String.
Returns the Disclaimer message

{
  "FC": "SM",
  "DT": "This communication is provided for information purposes only and is not intended as a recommendation or a solicitation to buy, sell or hold any investment product. Customers are solely responsible for their own trading decisions."
}

 

Mark Disclaimer Read

Mark disclaimer message read.

PUT /fyi/disclaimer/{typecode}

 

Request Object

Path Params

typecode: String. Required
Code used to signify a specific type of FYI template.
See Typecode section for more details.

request_url = f"{baseUrl}/fyi/disclaimer/CT"
json_content = {}
requests.put(url=request_url, json=json_content

 

curl \
--url {{baseUrl}}/fyi/disclaimer/CT \
--request PUT \
--data ''

 

Response Object

V: int.
Returns 1 to state message was acknowledged.

T: int.
Returns the time in ms to complete the edit.

{
  "V": 1,
  "T": 10
}

 

Get Delivery Options

Options for sending fyis to email and other devices

GET /fyi/deliveryoptions

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/fyi/deliveryoptions"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/fyi/deliveryoptions \
--request GET

 

Response Object

M: int.
Email option is enabled or not.
Value Format: 0: Email Disabled; 1: Email Enabled.

E: Array.
Returns an array of device information.
[{
NM: String.
Returns the human readable device name.

I: String.
Returns the deice identifier.

UI: String.
Returns the unique device ID.

A: String.
Device is enabled or not.
Value Format: 0: Disabled; 1: Enabled.
}]

{
  "E": [
    {
      "NM": "iPhone",
      "I": "apn://mtws@1234E5E67D8A9012EC3E45D6E7D89A01F2345CDBBB678B9BE0FB12345AF6D789",
      "UI": "apn://mtws@1234E5E67D8A9012EC3E45D6E7D89A01F2345CDBBB678B9BE0FB12345AF6D789",
      "A": 1
    }
  ],
  "M": 1
}

 

Enable/Disable Device Option

Choose whether a particular device is enabled or disabled.

POST /fyi/deliveryoptions/device

 

Request Object

Body Params

devicename: String. Required
Human readable name of the device.

deviceId: String. Required
ID Code for the specific device.

uiName: String. Required
Title used for the interface system.

enabled: bool. Required
Specify if the device should be enabled or disabled.

request_url = f"{baseUrl}/fyi/deliveryoptions/device"
json_content = {
    "deviceName": "iPhone",
    "deviceId": "apn://mtws@1234E5E67D8A9012EC3E45D6E7D89A01F2345CDBBB678B9BE0FB12345AF6D789",
    "uiName": "apn://mtws@1234E5E67D8A9012EC3E45D6E7D89A01F2345CDBBB678B9BE0FB12345AF6D789",
    "enabled": True
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/fyi/deliveryoptions/device \
--request POST \
--data '{
    "deviceName": "iPhone",
    "deviceId": "apn://mtws@1234E5E67D8A9012EC3E45D6E7D89A01F2345CDBBB678B9BE0FB12345AF6D789",
    "uiName": "apn://mtws@1234E5E67D8A9012EC3E45D6E7D89A01F2345CDBBB678B9BE0FB12345AF6D789",
    "enabled": True
}'

 

Response Object

V: int.
Returns 1 to state message was acknowledged.

T: int.
Returns the time in ms to complete the edit.

{
  "V": 1,
  "T": 10
}

 

Delete a Device

Delete a specific device from our saved list of notification devices.

DELETE /fyi/deliveryoptions/{{ deviceId }}

 

Request Object

Path Params

deviceId: String. Required
Display the device identifier to delete from IB’s saved list.
Can be retrieved from /fyi/deliveryoptions.

request_url = f"{baseUrl}/fyi/deliveryoptions/1" 
requests.delete(url=request_url)

 

curl \
--url {{baseUrl}}/fyi/deliveryoptions/1 \ 
--request DELETE

 

Response Object

No response message is returned. Instead, you will only receive an empty string with a 200 OK status code indicating a successfully deleted account.

Enable/Disable Email Option

Enable or disable your account’s primary email to receive notifications.

PUT /fyi/deliveryoptions/email

 

Request Object

Query Params

enabled: String. Required
Enable or disable your email.
Value format: true: Enable; false: Disable

request_url = f"{baseUrl}/fyi/deliveryoptions/email?enabled=true"
json_content = {}
requests.put(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/fyi/deliveryoptions/email?enabled={{ enabled }} \
--request PUT \
--data ""

 

Response Object

V: int.
Returns 1 to state message was acknowledged.

T: int.
Returns the time in ms to complete the edit.

{
  "V": 1,
  "T": 10
}

 

Get a list of notifications

Get a list of available notifications.

GET /fyi/notifications

 

Request Object

Query Params

max: String.
Specify the maximum number of notifications to receive.
Can request a maximum of 10 notifications.

request_url = f"{baseUrl}/fyi/notifications?max=10" 
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/fyi/notifications?max=10 \ 
--request GET

 

Response Object

D: String.
Notification date

ID: String.
Unique way to reference the notification.

FC: String.
FYI code, we can use it to find whether the disclaimer is accepted or not in settings

MD: String.
Content of notification.

MS: String.
Title of notification.

R: string.
Return if the notification was read or not.
Value Format: 0: Disabled; 1: Enabled.

[{
  "R": 0,
  "D": "1702469440.0",
  "MS": "IBKR FYI: Option Expiration Notification",
  "MD": "One or more option contracts in your portfolio are set to expire shortly.  
- QQQ 15DEC2023 385 P in Account(Qty): U****7890(6)
- QQQ 15DEC2023 387 P in Account(Qty): D****0685(-6)

Please use the Option Rollover tool to roll existing contracts into contracts with an expiration, strike and price condition of your preference.", "ID": "2023121370119463", "HT": 0, "FC": "OE" }]

 

Mark Notification Read

Mark a particular notification message as read or unread.

PUT /fyi/notifications/{notificationID}

 

Request Object

Path Params

notificationId: String. Required
Code used to signify a specific notification to mark.

request_url = f"{baseUrl}/fyi/notifications/more?id=12345678901234567"
json_content = {}
requests.put(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/fyi/notifications/12345678901234567 \
--request PUT \
--data ""

 

Response Object

V: int.
Returns 1 to state message was acknowledged.

T: int.
Returns the time in ms to complete the edit.

P: Object.
Returns details about the notification read status.

R: int.
Returns if the message was read (1) or unread (0).

ID: String.
Returns the ID for the notification..

{
  "V": 1,
  "T": 5,
  "P": {
    "R": 1,
    "ID": "12345678901234567"
  }
}

 

Market Data

Live Market Data Snapshot

Get Market Data for the given conid(s).

A pre-flight request must be made prior to ever receiving data. For some fields, it may take more than a few moments to receive information.

See response fields for a list of available fields that can be request via fields argument.

The endpoint /iserver/accounts must be called prior to /iserver/marketdata/snapshot.

For derivative contracts the endpoint /iserver/secdef/search must be called first.

GET /iserver/marketdata/snapshot

 

Request Object

Query Parameters

conids: String. Required
Contract identifier for the contract of interest.
May provide a comma-separated series of contract identifiers.

fields: String. Required
Specify a series of tick values to be returned.
May provide a comma-separated series of field ids.
See Market Data Fields for more information.

request_url = f"{baseUrl}/iserver/marketdata/snapshot?conids=265598,8314&fields=31,84,86"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/marketdata/snapshot?conids=265598,8314&fields=31,84,86 \ 
--request GET

 

Response Object

server_id: String.
Returns the request’s identifier.

conidEx: String.
Returns the passed conid field. May include exchange if specified in request.

conid: int.
Returns the contract id of the request

_updated: int*.
Returns the epoch time of the update in a 13 character integer .

6119: String.
Field value of the server_id. Returns the request’s identifier.

fields*: String.
Returns a response for each request. Some fields not be as readily available as others. See the Market Data section for more details.

6509: String.
Returns a multi-character value representing the Market Data Availability.

[
  {
    "_updated": 1702334859712,
    "conidEx": "265598",
    "conid": 265598,
    "server_id": "q1",
    "6119": "serverId",
    "31": "193.18",
    "84": "193.06",
    "86":"193.14", 
    "6509": "RpB"
  }
]

 

Regulatory Snapshot

WARNING: Each regulatory snapshot made will incur a fee of $0.01 USD to the account. This applies to both live and paper accounts.

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. For instance, for NYSE stocks this subscription is known as “Network A”, for ARCA/AMEX stocks it is called “Network B” and for NASDAQ stocks it is “Network C”. Each subscription is added a la carte and has a separate market data fee.

Alternatively, there is also a “US Securities Snapshot Bundle” subscription which does not provide streaming data but which allows for real time calculated snapshots of US market NBBO prices. Making a request with this endpoint, the returned value is a calculation of the current market state based on data from all available exchanges.

The following table lists the cost and maximum allocation for regulatory snapshot quotes:

Listed Network Feed Price per reqSnapshot request Pro or non-Pro Max reqSnapshot request
NYSE (Network A/CTA) 0.01 USD Pro 4500
NYSE (Network A/CTA) 0.01 USD Non-Pro 150
AMEX (Network B/CTA) 0.01 USD Pro 2300
AMEX (Network B/CTA) 0.01 USD Non-Pro 150
NASDAQ (Network C/UTP) 0.01 USD Pro 2300
NASDAQ (Network C/UTP) 0.01 USD Non-Pro 150

Send 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.

GET /md/regsnapshot

 

Request Object

Query Params

conid: String. Required
Provide the contract identifier to retrieve market data for.

request_url = f"{baseUrl}/md/regsnapshot?conid=265598"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/md/regsnapshot?conid=265598 \
--request GET

 

Response Object

Note: The integer fields returned below also correspond to the Market Data Field values used for the standard /iserver/marketdata/snapshot endpoint.

conid: int.
Returns the contract ID of the request.

conidEx: String.
Returns the contract ID of the request type.

BboExchange: String.
Color for Best Bid/Offer Exchange in hex code

HasDelayed: false,
Returns if the data is live (false) or delayed (true).

84: float.
Returns the Bid value.

86: float.
Returns the Ask value.

88: int.
Returns the Bid size.

85: int.
Returns the Ask size.

BestBidExch: int.
Returns the exchange identifier of the current best bid value.
Internal use only.

BestAskExch: int.
Returns the exchange identifier of the current best Ask value.
Internal use only.

31: float.
Returns the exchange identifier of the most recent Last value.
Internal use only.

7059: int.
Returns the last traded size.

LastExch: int.
Returns the exchange of the last exchange as a binary integer*
Internal use only.

7057: String.
Returns the series of character codes for the Ask exchange.

7068: String.
Returns the series of character codes for the Bid exchange.

7058: String.
Returns the series of character codes for the Last exchange.

{
  "conid": conid,
  "conidEx": "conidEx",
  "BboExchange": "BboExchange",
  "HasDelayed": HasDelayed,
  "84": "Bid",
  "86": "Ask",
  "88": Bid_Size,
  "85": Ask_Size,
  "BestBidExch": BestBidExch,
  "BestAskExch": BestAskExch,
  "31": "Last",
  "7059": Last_Size,
  "LastExch": LastExch,
  "7057": "Ask Exch",
  "7068": "Bid Exch",
  "7058": "Last_Exch"
}

 

Market Data Availability

The field may contain three chars.

First character defines market data timeline. This includes:  R = RealTime, D = Delayed, Z = Frozen, Y = Frozen Delayed, N = Not Subscribed.

Second character defines the data structure. This includes: P = Snapshot, p = Consolidated.

Third character defines the type of data: This will always return: B = Book

Code Name Description
R RealTime Data is relayed back in real time without delay, market data subscription(s) are required.
D Delayed Data is relayed back 15-20 min delayed.
Z Frozen Last recorded data at market close, relayed back in real time.
Y Frozen Delayed Last recorded data at market close, relayed back delayed.
N Not Subscribed User does not have the required market data subscription(s) to relay back either real time or delayed data.
P Snapshot Snapshot request is available for contract.
p Consolidated Market data is aggregated across multiple exchanges or venues.
B Book Top of the book data is available for contract.
d Performance Details Enabled Additional performance details are available for this contract. Internal use intended.

Market Data Fields

Field Return Type Value Description
31 string Last Price The last price at which the contract traded. May contain one of the following prefixes: C – Previous day’s closing price. H – Trading has halted.
55 string Symbol
58 string Text
70 string High Current day high price
71 string Low Current day low price
73 string Market Value The current market value of your position in the security. Market Value is calculated with real time market data (even when not subscribed to market data).
74 string Avg Price The average price of the position.
75 string Unrealized PnL Unrealized profit or loss. Unrealized PnL is calculated with real time market data (even when not subscribed to market data).
76 string Formatted position
77 string Formatted Unrealized PnL
78 string Daily PnL Your profit or loss of the day since prior close. Daily PnL is calculated with real time market data (even when not subscribed to market data).
79 string Realized PnL Realized profit or loss. Realized PnL is calculated with real time market data (even when not subscribed to market data).
80 string Unrealized PnL % Unrealized profit or loss expressed in percentage.
82 string Change The difference between the last price and the close on the previous trading day
83 string Change % The difference between the last price and the close on the previous trading day in percentage.
84 string Bid Price The highest-priced bid on the contract.
85 string Ask Size The number of contracts or shares offered at the ask price. For US stocks, the number displayed is divided by 100.
86 string Ask Price The lowest-priced offer on the contract.
87 string Volume Volume for the day, formatted with ‘K’ for thousands or ‘M’ for millions. For higher precision volume refer to field 7762.
88 string Bid Size The number of contracts or shares bid for at the bid price. For US stocks, the number displayed is divided by 100.
6004 string Exchange
6008 integer Conid Contract identifier from IBKR’s database.
6070 string SecType The asset class of the instrument.
6072 string Months
6073 string Regular Expiry
6119 string Marker for market data delivery method (similar to request id)
6457 integer Underlying Conid. Use /trsrv/secdef to get more information about the security
6508 string Service Params.
6509 string Market Data Availability. The field may contain three chars. First char defines: R = RealTime, D = Delayed, Z = Frozen, Y = Frozen Delayed, N = Not Subscribed, i – incomplete, v – VDR Exempt (Vendor Display Rule 603c). Second char defines: P = Snapshot, p = Consolidated. Third char defines: B = Book. RealTime Data is relayed back in real time without delay, market data subscription(s) are required. Delayed – Data is relayed back 15-20 min delayed. Frozen – Last recorded data at market close, relayed back in real time. Frozen Delayed – Last recorded data at market close, relayed back delayed. Not Subscribed – User does not have the required market data subscription(s) to relay back either real time or delayed data. Snapshot – Snapshot request is available for contract. Consolidated – Market data is aggregated across multiple exchanges or venues. Book – Top of the book data is available for contract.
7051 string Company name
7057 string Ask Exch Displays the exchange(s) offering the SMART price. A=AMEX, C=CBOE, I=ISE, X=PHLX, N=PSE, B=BOX, Q=NASDAQOM, Z=BATS, W=CBOE2, T=NASDAQBX, M=MIAX, H=GEMINI, E=EDGX, J=MERCURY
7058 string Last Exch Displays the exchange(s) offering the SMART price. A=AMEX, C=CBOE, I=ISE, X=PHLX, N=PSE, B=BOX, Q=NASDAQOM, Z=BATS, W=CBOE2, T=NASDAQBX, M=MIAX, H=GEMINI, E=EDGX, J=MERCURY
7059 string Last Size The number of unites traded at the last price
7068 string Bid Exch Displays the exchange(s) offering the SMART price. A=AMEX, C=CBOE, I=ISE, X=PHLX, N=PSE, B=BOX, Q=NASDAQOM, Z=BATS, W=CBOE2, T=NASDAQBX, M=MIAX, H=GEMINI, E=EDGX, J=MERCURY
7084 string Implied Vol./Hist. Vol % The ratio of the implied volatility over the historical volatility, expressed as a percentage.
7085 string Put/Call Interest Put option open interest/call option open interest for the trading day.
7086 string Put/Call Volume Put option volume/call option volume for the trading day.
7087 string Hist. Vol. % 30-day real-time historical volatility.
7088 string Hist. Vol. Close % Shows the historical volatility based on previous close price.
7089 string Opt. Volume Option Volume
7094 string Conid + Exchange
7184 string canBeTraded If contract is a trade-able instrument. Returns 1(true) or 0(false).
7219 string Contract Description
7220 string Contract Description
7221 string Listing Exchange
7280 string Industry Displays the type of industry under which the underlying company can be categorized.
7281 string Category Displays a more detailed level of description within the industry under which the underlying company can be categorized.
7282 string Average Volume The average daily trading volume over 90 days.
7283 string Option Implied Vol. % A prediction of how volatile an underlying will be in the future.At the market volatility estimated for a maturity thirty calendar days forward of the current trading day, and based on option prices from two consecutive expiration months. To query the Implied Vol. % of a specific strike refer to field 7633.
7284 string Historical volatility % Deprecated, see field 7087
7285 string Put/Call Ratio
7286 string Dividend Amount Displays the amount of the next dividend.
7287 string Dividend Yield % This value is the toal of the expected dividend payments over the next twelve months per share divided by the Current Price and is expressed as a percentage. For derivatives, this displays the total of the expected dividend payments over the expiry date
7288 string Ex-date of the dividend
7289 string Market Cap
7290 string P/E
7291 string EPS
7292 string Cost Basis Your current position in this security multiplied by the average price and multiplier.
7293 string 52 Week High The highest price for the past 52 weeks.
7294 string 52 Week Low The lowest price for the past 52 weeks.
7295 string Open Today’s opening price.
7296 string Close Today’s closing price.
7308 string Delta The ratio of the change in the price of the option to the corresponding change in the price of the underlying.
7309 string Gamma The rate of change for the delta with respect to the underlying asset’s price.
7310 string Theta A measure of the rate of decline the value of an option due to the passage of time.
7311 string Vega The amount that the price of an option changes compared to a 1% change in the volatility.
7607 string Opt. Volume Change % Today’s option volume as a percentage of the average option volume.
7633 string Implied Vol. % The implied volatility for the specific strike of the option in percentage. To query the Option Implied Vol. % from the underlying refer to field 7283.
7635 string Mark The mark price is, the ask price if ask is less than last price, the bid price if bid is more than the last price, otherwise it’s equal to last price.
7636 string Shortable Shares Number of shares available for shorting.
7637 string Fee Rate Interest rate charged on borrowed shares.
7638 string Option Open Interest
7639 string % of Mark Value Displays the market value of the contract as a percentage of the total market value of the account. Mark Value is calculated with real time market data (even when not subscribed to market data).
7644 string Shortable Describes the level of difficulty with which the security can be sold short.
7655 string Morningstar Rating Displays Morningstar Rating provided value. Requires Morningstar subscription.
7671 string Dividends This value is the total of the expected dividend payments over the next twelve months per share.
7672 string Dividends TTM This value is the total of the expected dividend payments over the last twelve months per share.
7674 string EMA(200) Exponential moving average (N=200).
7675 string EMA(100) Exponential moving average (N=100).
7676 string EMA(50) Exponential moving average (N=50).
7677 string EMA(20) Exponential moving average (N=20).
7678 string Price/EMA(200) Price to Exponential moving average (N=200) ratio -1, displayed in percents.
7679 string Price/EMA(100) Price to Exponential moving average (N=100) ratio -1, displayed in percents.
7724 string Price/EMA(50) Price to Exponential moving average (N=50) ratio -1, displayed in percents.
7681 string Price/EMA(20) Price to Exponential moving average (N=20) ratio -1, displayed in percents.
7682 string Change Since Open The difference between the last price and the open price.
7683 string Upcoming Event Shows the next major company event. Requires Wall Street Horizon subscription.
7684 string Upcoming Event Date The date of the next major company event. Requires Wall Street Horizon subscription.
7685 string Upcoming Analyst Meeting The date and time of the next scheduled analyst meeting. Requires Wall Street Horizon subscription.
7686 string Upcoming Earnings The date and time of the next scheduled earnings/earnings call event. Requires Wall Street Horizon subscription.
7687 string Upcoming Misc Event The date and time of the next shareholder meeting, presentation or other event. Requires Wall Street Horizon subscription.
7688 string Recent Analyst Meeting The date and time of the most recent analyst meeting. Requires Wall Street Horizon subscription.
7689 string Recent Earnings The date and time of the most recent earnings/earning call event. Requires Wall Street Horizon subscription.
7690 string Recent Misc Event The date and time of the most recent shareholder meeting, presentation or other event. Requires Wall Street Horizon subscription.
7694 string Probability of Max Return Customer implied probability of maximum potential gain.
7695 string Break Even Break even points
7696 string SPX Delta Beta Weighted Delta is calculated using the formula; Delta x dollar adjusted beta, where adjusted beta is adjusted by the ratio of the close price.
7697 string Futures Open Interest Total number of outstanding futures contracts
7698 string Last Yield Implied yield of the bond if it is purchased at the current last price. Last yield is calculated using the Last price on all possible call dates. It is assumed that prepayment occurs if the bond has call or put provisions and the issuer can offer a lower coupon rate based on current market rates. The yield to worst will be the lowest of the yield to maturity or yield to call (if the bond has prepayment provisions). Yield to worse may be the same as yield to maturity but never higher.
7699 string Bid Yield Implied yield of the bond if it is purchased at the current bid price. Bid yield is calculated using the Ask on all possible call dates. It is assumed that prepayment occurs if the bond has call or put provisions and the issuer can offer a lower coupon rate based on current market rates. The yield to worst will be the lowest of the yield to maturity or yield to call (if the bond has prepayment provisions). Yield to worse may be the same as yield to maturity but never higher.
7700 string Probability of Max Return Customer implied probability of maximum potential gain.
7702 string Probability of Max Loss Customer implied probability of maximum potential loss.
7703 string Profit Probability Customer implied probability of any gain.
7704 string Organization Type
7705 string Debt Class
7706 string Ratings Ratings issued for bond contract.
7707 string Bond State Code
7708 string Bond Type
7714 string Last Trading Date
7715 string Issue Date
7718 string Beta Beta is against standard index.
7720 string Ask Yield Implied yield of the bond if it is purchased at the current offer. Ask yield is calculated using the Bid on all possible call dates. It is assumed that prepayment occurs if the bond has call or put provisions and the issuer can offer a lower coupon rate based on current market rates. The yield to worst will be the lowest of the yield to maturity or yield to call (if the bond has prepayment provisions). Yield to worse may be the same as yield to maturity but never higher.
7741 string Prior Close Yesterday’s closing price
7762 string Volume Long High precision volume for the day. For formatted volume refer to field 87.
7768 string hasTradingPermissions if user has trading permissions for specified contract. Returns 1(true) or 0(false).
7920 string Daily PnL Raw Your profit or loss of the day since prior close. Daily PnL is calculated with real-time market data (even when not subscribed to market data).
7921 string Cost Basis Raw Your current position in this security multiplied by the average price and and multiplier.

Unavailable Historical Data

  • Bars whose size is 30 seconds or less older than six months
  • Expired futures data older than two years counting from the future’s expiration date.
  • Expired options, FOPs, warrants and structured products.
  • End of Day (EOD) data for options, FOPs, warrants and structured products.
  • Data for expired future spreads
  • Data for securities which are no longer trading.
  • Native historical data for combos. Historical data is not stored in the IB database separately for combos.; combo historical data in TWS or the API is the sum of data from the legs.
  • Historical data for securities which move to a new exchange will often not be available prior to the time of the move.
  • Studies and indicators such as Weighted Moving Averages or Bollinger Bands are not available from the API. VWAP is available.

Historical Market Data

Get historical market Data for given conid, length of data is controlled by ‘period’ and ‘bar’.

Formatted as: min=minute, h=hour, d=day, w=week, m=month, y=year

Note: There’s a limit of 5 concurrent requests. Excessive requests will return a ‘Too many requests’ status 429 response.

GET /iserver/marketdata/history

 

Request Object

Query Params

conid: String. Required
Contract identifier for the ticker symbol of interest.

exchange: String.
Returns the exchange you want to receive data from.

period: String.
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

bar: String. Required
Individual bars of data to be returned.
Possible value– 1min, 2min, 3min, 5min, 10min, 15min, 30min, 1h, 2h, 3h, 4h, 8h, 1d, 1w, 1m

startTime: String
Starting date of the request duration.

outsideRth: bool.
Determine if you want data after regular trading hours.

request_url = f"{baseUrl}/iserver/marketdata/history?conid=265598&exchange=SMART&period=1d&bar=1d&startTime=20230821-13:30:00&outsideRth=true"
requests.get(url=request_url) 

 

 

curl \
--url {{baseUrl}}/iserver/marketdata/history?conid=265598&exchange=SMART&period=1d&bar=1h&startTime=20230821-13:30:00&outsideRth=true \ 
--request GET

 

Response Object

serverId: String.
Internal request identifier.

symbol: String.
Returns the ticker symbol of the contract.

text: String.
Returns the long name of the ticker symbol.

priceFactor: String.
Returns the price increment obtained from the display rules.

startTime: String.
Returns the initial time of the historical data request.
Returned in UTC formatted as YYYYMMDD-HH:mm:ss

high: String.
Returns the High values during this time series with format %h/%v/%t.
%h is the high price (scaled by priceFactor),
%v is volume (volume factor will always be 100 (reported volume = actual volume/100))
%t is minutes from start time of the chart

low: String.
Returns the low value during this time series with format %l/%v/%t.
%l is the low price (scaled by priceFactor),
%v is volume (volume factor will always be 100 (reported volume = actual volume/100))
%t is minutes from start time of the chart

timePeriod: String.
Returns the duration for the historical data request

barLength: int.
Returns the number of seconds in a bar.

mdAvailability: String.
Returns the Market Data Availability.
See the Market Data Availability section for more details.

mktDataDelay: int.
Returns the amount of delay, in milliseconds, to process the historical data request.

outsideRth: bool.
Defines if the market data returned was inside regular trading hours or not.

volumeFactor: int.
Returns the factor the volume is multiplied by.

priceDisplayRule: int.
Presents the price display rule used.
For internal use only.

priceDisplayValue: String.
Presents the price display rule used.
For internal use only.

negativeCapable: bool.
Returns whether or not the data can return negative values.

messageVersion: int.
Internal use only.

data: Array of objects.
Returns all historical bars for the requested period.
[{
o: float.
Returns the Open value of the bar.

c: float.
Returns the Close value of the bar.

h: float.
Returns the High value of the bar.

l: float.
Returns the Low value of the bar.

v: float.
Returns the Volume of the bar.

t: int.
Returns the epoch timestamp of the bar.
}],

points: int.
Returns the total number of data points in the bar.

travelTime: int.
Returns the amount of time to return the details.

{
  "serverId": "20477",
  "symbol": "AAPL",
  "text": "APPLE INC",
  "priceFactor": 100,
  "startTime": "20230818-08:00:00",
  "high": "17510/472117.45/0",
  "low": "17170/472117.45/0",
  "timePeriod": "1d",
  "barLength": 86400,
  "mdAvailability": "S",
  "mktDataDelay": 0,
  "outsideRth": true,
  "tradingDayDuration": 1440,
  "volumeFactor": 1,
  "priceDisplayRule": 1,
  "priceDisplayValue": "2",
  "chartPanStartTime": "20230821-13:30:00",
  "direction": -1,
  "negativeCapable": false,
  "messageVersion": 2,
  "data": [
    {
      "o": 173.4,
      "c": 174.7,
      "h": 175.1,
      "l": 171.7,
      "v": 472117.45,
      "t": 1692345600000
    }
  ],
  "points": 0,
  "travelTime": 48
}

 

500 System Error

error: String.

{
  'error': 'description'
}

 

429 Too many requests

error: String.

{
  'error': 'description'
}

 

Historical Market Data (Beta)

Using a direct connection to the market data farm, will provide a list of historical market data for given conid.

 

GET /hmds/history

 

Request Object

Query Params

conid: String. Required
The contract identifier for which data should be requested.

period: String. Required
The duration for which data should be requested.
Available Values: See HMDS Period Units

bar: String. Required
The bar size for which bars should be returned.
Available Values: See HMDS Bar Sizes

outsideRth: bool.
Define if data should be returned for trades outside regular trading hours.

startTime: String.
Specify the value from where historical data should be taken.
Value Format: UTC; YYYYMMDD-HH:mm:dd
Defaults to the current date and time

direction: String.
Specify the direction from which market data should be returned
Available Values: -1: time from the startTime to now; 1: time from now to the end of the period.
Defaults to 1

barType: String.
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.

request_url = f"{baseUrl}/hmds/history?conid=265598&period=1d&bar=1hrs&outsideRth=true&barType=Last"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/hmds/history?conid=265598&period=1d&bar=1hrs&outsideRth=true&barType=Last \
--request GET

 

Initial Response Object

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.

<html><body><h1>Resource not found</h1></body></html>

 

Response Object

startTime: String.
Returns the initial time of the historical data request.
Returned in UTC formatted as YYYYMMDD-HH:mm:ss

startTimeVal: int.
Returns the initial time of the historical data request.
Returned in epoch time.

endTime: String.
Returns the end time of the historical data request.
Returned in UTC formatted as YYYYMMDD-HH:mm:ss

endTimeVal: int.
Returns the end time of the historical data request.
Returned in epoch time.

data: Array of objects.
Returns all historical bars for the requested period.
[{
t: int.
Returns the epoch timestamp of the bar.

o: float.
Returns the Open value of the bar.

c: float.
Returns the Close value of the bar.

h: float.
Returns the High value of the bar.

l: float.
Returns the Low value of the bar.

v: float.
Returns the Volume of the bar.
}],

points: int.
Returns the total number of data points in the bar.

mktDataDelay: int.
Returns the amount of delay, in milliseconds, to process the historical data request.

{
  "startTime": "20231211-04:00:00",
  "startTimeVal": 1702285200000,
  "endTime": "20231211-17:51:20",
  "endTimeVal": 1702335080000,
  "data": [
    {
      "t": 1702285200000,
      "o": 195.01,
      "c": 194.8,
      "h": 195.01,
      "l": 194.8,
      "v": 1723.0
    },
    {...}
  ],
  "points": 14,
  "mktDataDelay": 0
}

 

HMDS Period & Bar Size

Valid Period Units:

Unit Description
S Seconds
d Day
w Week
m Month
y Year

Note: These units are case sensitive.

Valid Bar Units:

Duration Bar units allowed Bar size Interval (Min/Max)
60 S secs | mins 1 secs -> 1mins
3600 S (1hour) secs | mins | hrs 5 secs -> 1 hours
14400 S (4hours) sec | mins | hrs 10 secs -> 4 hrs
28800 S  (8hours) sec | mins | hrs 30 secs -> 8 hrs
1 d mins | hrs   | d 1 mins-> 1 day
1 w mins | hrs | d | w 3 mins -> 1 week
1 m mins | d | w 30 mins -> 1 month
1 y d | w | m 1 d -> 1 m

Note: These units are case sensitive.

NOTE: Keep in mind that a step size is defined as the ratio between the historical data request’s duration period and its granularity (i.e. bar size). Historical Data requests need to be assembled in such a way that only a few thousand bars are returned at a time.

 

Unsubscribe (Single)

Cancel market data for given conid.

POST /iserver/marketdata/unsubscribe

 

Request Object

Body Params

conid: String. Required
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.

request_url = f"{baseUrl}/iserver/marketdata/unsubscribe" 
json_content ={
  "conid":265598 
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/marketdata/unsubscribe \ 
--request POST
--data '{
  "conid":265598
}'

 

Response Object

success: bool.
Returns a confirmation status of your unsubscribe request. A true response indicates that the market data feed has been successfully cancelled.

{
  "success": true
}

 

Eror Response Object

A status 500 response will be sent when attempting to unsubscribe from a market data feed that is not currently open.

error: String.
Returns an error response with message unknown indicating that the user does not have an existing data feed for the given conid.

{
  "error": "unknown"
}

 

Unsubscribe (All)

Cancel all market data request(s). To cancel market data for a specific conid, see /iserver/marketdata/{conid}/unsubscribe.

GET /iserver/marketdata/unsubscribeall

 

Request Object

No params or arguments should be passed.

request_url = f"{baseUrl}/iserver/marketdata/unsubscribeall"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/marketdata/unsubscribeall \ 
--request GET

 

Response Object

confirmed: String.
Returns a confirmation status of your unsubscribe request.

{
  "unsubscribed": true
}

 

Order Monitoring

Live Orders

This endpoint requires a pre-flight request.
Orders is the list of live orders (cancelled, filled, submitted).

GET /iserver/account/orders

 

Request Object

Query Params

filters: String.
Optionally filter your list of orders by a unique status value. More than one filter can be passed, separated by commas.
For available filters, see Order Status Values

force: bool.
Force the system to clear saved information and make a fresh request for orders. Submission will appear as a blank array.

accountId: String.
For linked accounts, allows users to view orders on sub-accounts as specified.

request_url = f"{baseUrl}/iserver/account/orders?filters=filled&force=true&accountId=U1234567"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/orders?filters=filled&force=true&accountId=U1234567 \
--request GET

 

Response Object

orders: Array of objects.
Contains all orders placed on the account for the day.
[{
acct: String.
Returns the accountID for the submitted order.

conidex: String.
Returns the contract identifier for the order.

conid: int.
Returns the contract identifier for the order.

orderId: int.
Returns the local order identifier of the order.

cashCcy: String.
Returns the currency used for the order.

sizeAndFills: String.
Returns the size of the order and how much of it has been filled.

orderDesc: String.
Returns the description of the order including the side, size, order type, price, and tif.

description1: String.
Returns the local symbol of the order.

ticker: String.
Returns the ticker symbol for the order.

secType: String.
Returns the security type for the order.

listingExchange: String.
Returns the primary listing exchange of the orer.

remainingQuantity: float.
Returns the remaining size for the order to fill.

filledQuantity: float.
Returns the size of the order already filled.

companyName: String.
Returns the company long name.

status: String.
Returns the current status of the order.

order_ccp_status: String.
Returns the current status of the order.

origOrderType: String.
Returns the original order type of the order, whether or not the type has been changed.

supportsTaxOpt: String.
Returns if the order is supported by the Tax Optimizer.

lastExecutionTime: String.
Returns the datetime of the order’s most recent execution.
Time returned is based on UTC timezone.
Value Format: YYMMDDHHmmss

orderType: String.
Returns the current order type, or the order at the time of execution.

bgColor: String.
Internal use only.

fgColor: String.
Internal use only.

timeInForce: String.
Returns the time in force (tif) of the order.

lastExecutionTime_r: int.
Returns the epoch time of the most recent execution on the order.

side: String.
Returns the side of the order.

avgPrice: String.
Returns the average price of execution for the order.
}]

snapshot: bool.
Returns if the data is a snapshot of the account’s orders.

{
  "orders": [
    {
      "acct": "U1234567",
      "conidex": "265598",
      "conid": 265598,
      "account": "U1234567",
      "orderId": 1234568790,
      "cashCcy": "USD",
      "sizeAndFills": "5",
      "orderDesc": "Sold 5 Market, GTC",
      "description1": "AAPL",
      "ticker": "AAPL",
      "secType": "STK",
      "listingExchange": "NASDAQ.NMS",
      "remainingQuantity": 0.0,
      "filledQuantity": 5.0,
      "totalSize": 5.0,
      "companyName": "APPLE INC",
      "status": "Filled",
      "order_ccp_status": "Filled",
      "avgPrice": "192.26",
      "origOrderType": "MARKET",
      "supportsTaxOpt": "1",
      "lastExecutionTime": "231211180049",
      "orderType": "Market",
      "bgColor": "#FFFFFF",
      "fgColor": "#000000",
      "order_ref": "Order123",
      "timeInForce": "GTC",
      "lastExecutionTime_r": 1702317649000,
      "side": "SELL"
    }
  ],
  "snapshot": true
}

 

Order Status

Retrieve 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.

GET /iserver/account/order/status/{{ orderId }}

 

Request Object

Query Params

orderId: String. Required
Order identifier for the placed order. Returned by the order placement response or the orderId available in the live order response.

request_url = f"{baseUrl}/iserver/account/order/status/1234567890"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/order/status/1234567890\
--request GET

 

Response Object

sub_type: null.
Internal use only.

request_id: String.
Returns the requestId of the order palced by the user.

order_id: int.
Returns the orderId of the requested order.

conidex: String.
Returns the contract identifier for the order.

conid: int.
Returns the contract identifier for the order.

symbol: String.
Returns the ticker symbol for the order.

side: String.
Returns the side of the order.

contract_description_1: String.
Returns the local symbol of the order.

listing_exchange: String.
Returns the primary listing exchange of the orer.

option_acct: String.
For Client Portal use (Internal use only).

company_name: String.
Returns the company long name.

size: String.
Returns the quantity of the order.

total_size: String.
Returns the maximum quantity of the order.

currency: String.
Returns the base currency of the order.

account: String.
Returns the account the order was placed for.

order_type: String.
Returns the order type for the given order.

cum_fill: String.
Returns the cumulative fill of the order.

order_status: String.
Returns the current status of the order.

order_ccp_status: String.
Returns the current status of the order as a code.

order_status_description: String.
Returns the human readable response of the order status.

tif: String.
Returns the time in force of the order.

fg_color: String.
For Client Portal use (Internal use only).

bg_color: String.
For Client Portal use (Internal use only).

order_not_editable: bool.
Returns whether or not the order can be modified.
This is relevant for orders that are currently or have already been executed.

editable_fields: null.
For Client Portal use (Internal use only).

cannot_cancel_order: bool.
Returns whether or not the order can be cancelled.
This is relevant for orders that are currently or have already been executed.

deactivate_order: bool.
Return whether or not the order has been marked inactive.

sec_type: String.
Returns the security type of the order’s contract.

available_chart_periods: String.
For Client Portal use (Internal use only).

order_description: String.
Returns the description of the order including the side, size, order type, price, and tif.

order_description_with_contract: String.
Returns the description of the order including the side, size, symbol, order type, price, and tif.

alert_active: int.
Returns wheteher or not there is an active alert available on the order.

child_order_type: String.
type of the child order
Value Format: A=attached, B=beta-hedge, 0=No Child

order_clearing_account: String.
Returns the accountID for the submitted order.

size_and_fills: String.
Returns the size of the order and how much of it has been filled.

exit_strategy_display_price: String.
Displays the price of the order as it resolved its execution.

exit_strategy_chart_description: String.
Returns the description of the order including the side, size, order type, price, and tif.

average_price: String.
Returns the average price of execution for the order.

exit_strategy_tool_availability: String.
Internal use only.

allowed_duplicate_opposite: bool.
Returns whether or not the opposing order can be placed on the market.

order_time: String.
Returns the datetime of the order placement.
Time returned is based on UTC timezone.
Value Format: YYMMDDHHmmss

{
  "sub_type": null,
  "request_id": "209",
  "server_id": "0",
  "order_id": 1799796559,
  "conidex": "265598",
  "conid": 265598,
  "symbol": "AAPL",
  "side": "S",
  "contract_description_1": "AAPL",
  "listing_exchange": "NASDAQ.NMS",
  "option_acct": "c",
  "company_name": "APPLE INC",
  "size": "0.0",
  "total_size": "5.0",
  "currency": "USD",
  "account": "U1234567",
  "order_type": "MARKET",
  "cum_fill": "5.0",
  "order_status": "Filled",
  "order_ccp_status": "2",
  "order_status_description": "Order Filled",
  "tif": "DAY",
  "fg_color": "#FFFFFF",
  "bg_color": "#000000",
  "order_not_editable": true,
  "editable_fields":"",
  "cannot_cancel_order": true,
  "deactivate_order": false,
  "sec_type": "STK",
  "available_chart_periods": "#R|1",
  "order_description": "Sold 5 Market, Day",
  "order_description_with_contract": "Sold 5 AAPL Market, Day",
  "alert_active": 1,
  "child_order_type": "0",
  "order_clearing_account": "U1234567",
  "size_and_fills": "5",
  "exit_strategy_display_price": "193.12",
  "exit_strategy_chart_description": "Sold 5 @ 192.26",
  "average_price": "192.26",
  "exit_strategy_tool_availability": "1",
  "allowed_duplicate_opposite": true,
  "order_time": "231211180049"
}

 

Order Status Value

For many orders, customers will see orders return an order status with an array of potential values. The table below elaborates on what the status means for the order and the potential behavior to expect from it.

Value Description
Inactive The order is inactive and is not yet transmitted.
PendingSubmit Order was received by the system but is no longer active because it was rejected or cancelled.
PreSubmitted Order has been transmitted but have not received confirmation yet that order accepted by destination exchange or venue.
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.

Trades

Returns 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.

GET /iserver/account/trades

 

Request Object

Query Params

days: String.
Specify the number of days to receive executions for, up to a maximum of 7 days.
If unspecified, only the current day is returned.

accountId: String.
Include a specific account identifier or allocation group to retrieve trades for.

request_url = f"{baseUrl}/iserver/account/trades?days=3&accountId=U1234567"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/account/trades?days=3&accountId=U1234567 \
--request GET

 

Response Object.

execution_id: String.
Returns the execution ID for the trade.

symbol: String.
Returns the underlying symbol.

supports_tax_opt: String.
Returns whether or not tax optimizer is supported for the order.

side: String.
Returns the side of the order, Buy or Sell.

order_description: String.
Returns the description of the order including the side, size, symbol, order type, price, and tif.

order_ref: String.
User defined string used to identify the order. Value is set using “cOID” field while placing an order.

trade_time: String.
Returns the UTC format of the trade time.

trade_time_r: int.
Returns the epoch time of the trade.

size: float.
Returns the quantity of the order.

price: String.
Returns the price of trade execution.

submitter: String.
Returns the username that submitted the order.

exchange: String.
Returns the exchange the order was executed on.

commission: String.
Returns the cost of commission for the trade.

net_amount: float.
Returns the total net cost of the order.

account: String.
Returns the account identifier.

accountCode: String.
Returns the account identifier.

company_name: String.
Returns the long name of the contract’s company.

contract_description_1: String.
Returns the local symbol of the order.

sec_type: String.
Returns the security type of the contract.

listing_exchange: String.
Returns the primary listing exchange of the contract.

conid: int.
Returns the contract identifier of the order.

conidEx: String.
Returns the contract identifier of the order.

clearing_id: String.
Returns the clearing firm identifier.

clearing_name: String.
Returns the clearing firm identifier.

liquidation_trade: String.
Returns whether the order was part of an account liquidation or note.

is_event_trading: String.
Returns whether the order was part of event trading or not.

[
  {
    "execution_id": "0000e0d5.6576fd38.01.01",
    "symbol": "AAPL",
    "supports_tax_opt": "1",
    "side": "S",
    "order_description": "Sold 5 @ 192.26 on ISLAND",
    "trade_time": "20231211-18:00:49",
    "trade_time_r": 1702317649000,
    "size": 5.0,
    "price": "192.26",
    "order_ref": "Order123",
    "submitter": "user1234",
    "exchange": "ISLAND",
    "commission": "1.01",
    "net_amount": 961.3,
    "account": "U1234567",
    "accountCode": "U1234567",
    "account_allocation_name": "U1234567",
    "company_name": "APPLE INC",
    "contract_description_1": "AAPL",
    "sec_type": "STK",
    "listing_exchange": "NASDAQ.NMS",
    "conid": 265598,
    "conidEx": "265598",
    "clearing_id": "IB",
    "clearing_name": "IB",
    "liquidation_trade": "0",
    "is_event_trading": "0"
  }
]

 

Orders

Place Order

When connected to an IServer Brokerage Session, this endpoint will allow you to submit orders.

CP WEB API supports various advanced orderTypes, for additional details and examples refer to the Order Types page.

Cash Quantity: Send orders using monetary value by specifying cashQty instead of quantity, e.g. cashQty: 200. The endpoint /iserver/contract/rules returns list of valid orderTypes in cqtTypes.

Currency Conversion: Convert cash from one currency to another by including isCcyConv = true. To specify the cash quantity use fxQTY instead of quantity, e.g. fxQTY: 100.

IB Algos: Attached user-defined settings to your trades by using any of IBKR’s Algo Orders. Use the endpoint /iserver/contract/{conid}/algos to identify the available strategies for a contract.

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.
POST /iserver/account/{accountID}/orders

 

Request Object

Path Params

accountId: String.
The account ID for which account should place the order.
Financial Advisors may specify

Body Params

orders: Array of Objects. Required
Used to the order content.
[{
acctId: String.
It should be one of the accounts returned by /iserver/accounts.
If not passed, the first one in the list is selected.

conid: int. Required*
conid is the identifier of the security you want to trade
You can find the conid with /iserver/secdef/search.
*Can use conidex instead of conid.

conidex: String. Optional*
A mix of the contract identifier and exchange
*Can be used instead of conid when specifying the contract identifier of a security.
Value format: “conid@exchange”

secType: String.
The contract-identifier (conid) and security type (type) specified as a concatenated value
Value Format: “conid:type”

cOID: String.
Customer Order ID.
An arbitrary string that can be used to identify the order
The value must be unique for a 24h span.
Do not set this value for child orders when placing a bracket order.

parentId: String.
Only specify for child orders when placing bracket orders.
The parentId for the child order(s) must be equal to the cOId (customer order id) of the parent.

orderType: String. Required
The order-type determines what type of order you want to send.
Available Order Types: LMT, MKT, STP, STOP_LIMIT, MIDPRICE, TRAIL, TRAILLMT

listingExchange: String.
Primary routing exchange for the order.
By default we use “SMART” routing.
Possible values are available via the endpoint: /iserver/contract/{conid}/info

isSingleGroup: bool.
Set to true if you want to place a single group orders(OCA)

outsideRTH: bool.
Set to true if the order can be executed outside regular trading hours.

price: float. Required for LMT or STOP_LIMIT
This is typically the limit price.
For STP|TRAIL this is the stop price.
For MIDPRICE this is the option price cap.

auxPrice: float. Required for STOP_LIMIT and TRAILLMT orders.
Stop price for STOP_LIMIT and TRAILLMT orders.
You must specify both price and auxPrice for STOP_LIMIT|TRAILLMT orders.

side: String. Required
Valid Values: SELL or BUY

ticker: String.
This is the underlying symbol for the contract.

tif: String. Required
The Time-In-Force determines how long the order remains active on the market.
Valid Values: GTC, OPG, DAY, IOC, PAX (CRYPTO ONLY).

trailingAmt: float. Required for TRAIL and TRAILLMT order
optional if order is TRAIL, or TRAILLMT.
When trailingType is amt, this is the trailing amount
When trailingType is %, it means percentage.

trailingType: String. Required for TRAIL and TRAILLMT order
This is the trailing type for trailing amount.
You must specify both trailingType and trailingAmt for TRAIL and TRAILLMT order
Valid Values: “amt” or “%”

referrer: String.
Custom order reference

quantity: float. Required*
Used to designate the total number of shares traded for the order.

cashQty: float.
Used to specify the monetary value of an order instead of the number of shares.
When using ‘cashQty’ don’t specify ‘quantity’
Cash quantity orders are provided on a non-guaranteed basis.
The system simulates the order by canceling it once the specified amount is spent (for buy orders) or collected (for sell orders).
In addition to the monetary value, the order uses a maximum size that is calculated using the Cash Quantity Estimated Factor, which can be modified in TWS Order Presets.

fxQty: float.
This is the cash quantity field which can only be used for Currency Conversion Orders.
When using ‘fxQty’ don’t specify ‘quantity’.

useAdaptive: boolean
If true, the system will use the Price Management Algo to submit the order.
Read more on our Price Management Algo page. https://www.interactivebrokers.com/en/index.php?f=43423

isCcyConv: boolean
set to true if the order is a FX conversion order

allocationMethod: String.
Set the allocation method when placing an order using an FA account for a group.
Based on value set in Trader Workstation.

manualOrderTime: int.
Only used for Brokers and Advisors. Mark the time to manually record initial order entry.
Must be sent as epoch time integer.

deactivated: bool.
Functions the same as Saving an Order in Trader Workstation.

strategy: String.
Specify which IB Algo algorithm to use for this order.

strategyParameters: Array.
The IB Algo parameters for the specified algorithm.
}]

request_url = f"{baseUrl}/iserver/account/U1234567/orders"
json_content = {
  "orders": [
    {
      "acctId": "U1234567",
      "conid": 265598,
      "conidex": "265598@SMART",
      "secType": "265598@STK",
      "cOID": "AAPL-BUY-100",
      "parentId": None,
      "orderType": "TRAILLMT",
      "listingExchange": "NASDAQ",
      "isSingleGroup": False,
      "outsideRTH": True,
      "price": 185.50,
      "auxPrice": 183,
      "side": "BUY",
      "ticker": "AAPL",
      "tif": "GTC",
      "trailingAmt": 1.00,
      "trailingType": "amt",
      "referrer": "QuickTrade",
      "quantity": 100,
      # Can not be used in tandem with quantity value.
      # "cashQty": {{ cashQty }},
      # "fxQty": {{ fxQty }},
      "useAdaptive": False,
      "isCcyConv": False,
      # May specify an allocation method such as Equal or NetLiq for Financial Advisors.
      # "allocationMethod": {{ allocationMethod }},
      "strategy": "Vwap",
        "strategyParameters": {
          "MaxPctVol":"0.1",
          "StartTime":"14:00:00 EST",
          "EndTime":"15:00:00 EST",
          "AllowPastEndTime":true
        }
    }
  ]
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/account/U1234567/orders \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "orders": [
    {
      "acctId": "U1234567",
      "conid": 265598,
      "conidex": "265598@SMART",
      "secType": "265598:STK",
      "cOID": "AAPL-BUY-100",
      "parentId": null,
      "orderType": "TRAILLMT",
      "listingExchange": "ISLAND",
      "isSingleGroup": false,
      "outsideRTH": true,
      "price": 185.50,
      "auxPrice": 183,
      "side": "BUY",
      "ticker": "AAPL",
      "tif": "GTC",
      "trailingAmt": 1.00,
      "trailingType": "amt",
      "referrer": "QuickTrade",
      "quantity": 100,
      # Can not be used in tandem with quantity value.
      # "cashQty": {{ cashQty }}, 
      # "fxQty": {{ fxQty }},
      "useAdaptive": false,
      "isCcyConv": false,
      # May specify an allocation method such as Equal or NetLiq for Financial Advisors.
      # "allocationMethod": {{ allocationMethod }},
      "strategy": "Vwap",
        "strategyParameters": {
          "MaxPctVol":"0.1",
          "StartTime":"14:00:00 EST",
          "EndTime":"15:00:00 EST",
          "AllowPastEndTime":true
        }
    }
  ]
}'

 

Response Object

orderId: String.
Returns the orders identifier which can be used for order tracking, modification, and cancellation.

order_status: String.
Returns the order status of the current market order.
See Order Status Value for more information.

encrypt_message: String.
Returns a “1” to display that the message sent was encrypted.

[
  {
    "order_id": "1234567890",
    "order_status": "Submitted",
    "encrypt_message": "1"
  }
]

 

Alternate Response Object

In some instances, you will receive an ID along with a message about your order.

See the Place Order Reply section for more details on resolving the confirmation.

Important: The reply must be confirmed before sending any further orders. Otherwise, the order will be invalidated and attempts to confirm invalid replies will result in a timeout (503).

id: String.
Returns a message ID relating to the particular order’s warning confirmation.

message: Array of Strings.
Returns the message warning about why the order wasn’t initially transmitted.

isSuppressed: bool.
Returns if a particular warning was suppressed before sending.
Always returns false.

messageIds: Array of Strings.
Returns an internal message identifier (Internal use only).

[
  {
    "id": "07a13a5a-4a48-44a5-bb25-5ab37b79186c",
    "message": [
      "The following order \"BUY 5 AAPL NASDAQ.NMS @ 150.0\" price exceeds \nthe Percentage constraint of 3%.\nAre you sure you want to submit this order?"
    ],
    "isSuppressed": false,
    "messageIds": [
      "o163"
    ]
  }
]

 

Order Reject Object

In the event an order is placed that can not be completed based on account details such as trading permissions or funds, customers will receive a 200 OK response along with an error message explaining the issue.

This is unique from the 200 response used in the Alternate Response Object, or a potential 500 error resulting from invalid request content.

{
  "error":"We cannot accept an order at the limit price you selected. Please submit your order using a limit price that is closer to the current market price of 197.79.  Alternatively, you can convert your order to an Algorithmic Order (IBALGO)."
}

 

Place Order Reply Confirmation

Many of the warning notifications within the Client Portal API can be disabled. To do this users MUST:

  1. Log in to the Trader Workstation
  2. Open the Global Configuration by selecting the Cog Wheel icon in the top right corner
  3. Navigate to the “Messages” section on the left.
  4. Carefully read each message before disabling it. You can then disable the warning by unchecking the box on the right of the message description.
  5. Navigate to the “Presets” section on the left
  6. Select the instrument(s) you are trading
  7. Carefully read each setting before making changes to it. You may modify the values inside the “Precautionary Settings” settings to be more or less restrictive.

Confirm order precautions and warnings presented from placing orders.

POST /iserver/reply/{{ replyId }}

 

Request Object

Path Params

replyId: String. Required
Include the id value from the prior order request relating to the particular order’s warning confirmation.

Body Params

confirmed: bool. Required
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.

request_url = f"{baseUrl}/iserver/reply/a12b34c5-d678-9e012f-3456-7a890b12cd3e"
json_content = {"confirmed":true}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/reply/a12b34c5-d678-9e012f-3456-7a890b12cd3e \
--request POST \
--header 'Content-Type:application/json' \
--data '{"confirmed":true}'

 

Response Object

orderId: String.
Returns the orders identifier which can be used for order tracking, modification, and cancellation.

order_status: String.
Returns the order status of the current market order.
See Order Status Value for more information.

encrypt_message: String.
Returns a “1” to display that the message sent was encrypted.

[
  {
    "order_id": "1234567890",
    "order_status": "Submitted",
    "encrypt_message": "1"
  }
]

 

NOTE: After sending your initial confirmation to the /iserver/reply/{replyId} endpoint, you may receive additional reply messages. These confirmation messages must also be responded to before the order will submit.

Respond to a Server Prompt

Respond to a server prompt received via ntf webscoket message.

POST /iserver/notification

Request Object

Body Params

orderId int. Required
IB-assigned order identifier obtained from the ntf websocket message that delivered the server prompt.

reqId string. Required
IB-assigned request identifier obtained from the ntf websocket message that delivered the server prompt.

text string. Required
The selected value from the “options” array delivered in the server prompt ntf websocket message.
 

request_url = f"{baseUrl}/iserver/notification"
json_content = {
  "orderId": 987654321,
  "reqId": "12345",
  "text": "Yes"
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {baseUrl}/iserver/notification \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "orderId": 987654321,
  "reqId": "12345",
  "text": "Yes"
}'

 

Response Object

{Status text}: string
Returns the status of the confirmation message.

Success

 

Preview Order / WhatIf Order

This 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.

 

POST /iserver/account/{accountId}/orders/whatif

 

Request Object

The body content of the /whatif endpoint will follow the same structure as the standard /iserver/account/{accountId}/orders endpoint.

See the Place Order section for more details.

request_url = f"{baseUrl}/iserver/account/U1234567/orders/whatif"
json_content = {
  "orders": [
    {
      "conid": 265598,
      "orderType": "LMT",
      "price": 200.25,
      "side": "BUY",
      "tif": "DAY",
      "quantity": 5
    }
  ]
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/account/U1234567/orders/whatif \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "orders": [
    {
      "conid": 265598,
      "orderType": "LMT",
      "price": 200.25,
      "side": "BUY",
      "tif": "DAY",
      "quantity": 5
    }
  ]
}'

 

Response Object

amount: Object.
Contains the details about the order cost.
{
amount: String.
Returns the cost of the base order.

commission: String.
Returns the commission cost of the base order.

total: String.
Returns the total cost of the order.
},

equity: Object.
Contains the details about the order’s impact on your equity.
{
current: String.
Returns the current equity of the account.

change: String.
Returns the equity impact from the order.

after: String.
Returns the equity after the order is traded.
},

initial: Object.
Contains the details about the order’s impact on your initial margin.
{
current: String.
Returns the current initial margin value.

change: String.
Returns the amount the initial margin will change by.

after: String.
Returns the initial margin value after the order.
},

maintenance: Object.
Contains the details about the order’s impact on your maintenance margin.
{
current: String.
Returns the current maintenance margin value.

change: String.
Returns the amount the maintenance margin will change by.

after: String.
Returns the maintenance margin value after the transaction.
},

position: Object.
Contains the details about the order’s impact on your current position.
{
current: String.
Returns the cost of the base order.

change: String.
Returns the cost of the base order.

after: String.
Returns the cost of the base order.
},

warn: String.
Returns any potential warning message from placing this order.
Returns null if no warning is possible.

error: String.
Returns any potential error message from placing this order.
Returns null if no error is possible.

{
  "amount": {
    "amount": "1,977.60 USD (10 Shares)",
    "commission": "1 USD",
    "total": "1,978.60 USD"
  },
  "equity": {
    "current": "215,415,594",
    "change": "-1",
    "after": "215,415,593"
  },
  "initial": {
    "current": "116,965",
    "change": "652",
    "after": "117,617"
  },
  "maintenance": {
    "current": "106,332",
    "change": "592",
    "after": "106,924"
  },
  "position": {
    "current": "0",
    "change": "10",
    "after": "10"
  },
  "warn": "21/You are trying to submit an order without having market data for this instrument. \nIB strongly recommends against this kind of blind trading which may result in \nerroneous or unexpected trades.",
  "error": null
}

 

Bracket Orders & OCA Groups

The available values and structures of Bracket or OCA orders follow the same general structure of individual orders. Bracket and OCA orders require a parent order be submitted, and then each leg, or child order, would include the parent’s order ID.

Bracket orders can be submitted sequentially using the default order_id created by Interactive Brokers.

OR

Bracket orders can be submitted using the cOID field for the parent order, and then use this same value in each of the child orders in the parentId field.

The body content on the right represents a standard bracket order which contains a parent order, a profit taker, and a stop loss. As you can see, the only addition to this order is the inclusion of cOID in the parent order, and the parentId field in the two children.

{
  "orders": [
    {
      "acctId": "U1234567",
      "conid": 265598,
      "cOID": "Parent",
      "orderType": "MKT",
      "listingExchange": "SMART",
      "outsideRTH": true,
      "side": "Buy",
      "referrer": "QuickTrade",
      "tif": "GTC",
      "quantity": 50
    },
    {
      "acctId": "U1234567",
      "conid": 265598,
      "orderType": "STP",
      "listingExchange": "SMART",
      "outsideRTH": false,
      "price": 157.30,
      "side": "Sell",
      "tif": "GTC",
      "quantity": 50,
      "parentId": "Parent"
    },
    {
      "acctId": "U1234567",
      "conid": 265598,
      "orderType": "LMT",
      "listingExchange": "SMART",
      "outsideRTH": false,
      "price": 157.00,
      "side": "Sell",
      "tif": "GTC",
      "quantity": 50,
      "parentId": "Parent"
    }
  ]
}

 

An OCA group will follow this same structure. However, in addition to the standard bracket, each order will include "isSingleGroup": true. Otherwise, no additional modifications need to be made.

 

{
  "orders": [
    {
      "acctId": "U1234567",
      "conid": 265598,
      "cOID": "Parent",
      "orderType": "MKT",
      "listingExchange": "SMART",
      "isSingleGroup": true,
      "outsideRTH": true,
      "side": "Buy",
      "referrer": "QuickTrade",
      "tif": "GTC",
      "quantity": 50
    },
    {
      "acctId": "U1234567",
      "conid": 265598,
      "orderType": "STP",
      "listingExchange": "SMART",
      "isSingleGroup": true,
      "outsideRTH": false,
      "price": 157.30,
      "side": "Sell",
      "tif": "GTC",
      "quantity": 50,
      "parentId": "Parent"
    },
    {
      "acctId": "U1234567",
      "conid": 265598,
      "orderType": "LMT",
      "listingExchange": "SMART",
      "outsideRTH": false,
      "isSingleGroup": true,
      "price": 157.00,
      "side": "Sell",
      "tif": "GTC",
      "quantity": 50,
      "parentId": "Parent"
    }
  ]
}

 

Combo / Spread Orders

Combination orders or spread orders may also be placed using the same orders endpoint. In the case of combo orders, we must use the ‘conidex’ instead of “conid”. The conidex field is a string representation of our combo order parameters.

Combo Orders follow the format of: ‘{spread_conid};;;{leg_conid1}/{ratio},{leg_conid2}/{ratio}‘

The spread_conid is a unique identified used to denote a spread order.  For US Stock Combos, only the spread_conid needs to be submitted.. For all other countries, you will need to use the format ‘spread_conid@exchange’.

Available currency spread conids:
Currency Spread ConID
AUD 61227077
CAD 61227082
CHF 61227087
CNH 136000441
GBP 58666491
HKD 61227072
INR 136000444
JPY 61227069
KRW 136000424
MXN 136000449
SEK 136000429
SGD 426116555
USD 28812380

Following our spread_conid, we will then follow with 3 semicolons, and then the first leg_coind. This will be the first contract to trade. After the conid, a forward slash, ‘/’, needs to be included followed by your spread ratio.

The ratio indicates two parts. The first is the sign of the ratio, whether it is positive or negative. Positive signs indicate a ‘Buy’ side, while a negative value represents a ‘Sell’ side. This could also be explained as a state of ‘Long’ and ‘Short’ respectively, depending on your current position and intention. After indicating the side, you would indicate the ratio value. This is the multiplier of your quantity value.

Now, you can continue to add legs to the order by separating them with a comma. The number of legs available is based on the exchange’s rules.

Combo Order Pricing

Combo orders can submit their price values based on the value of the individual leg, multiplied by the ratio. Each leg is then added together to create the final price of the order.

These prices can end as negative values if one of the legs is being sold and the total value of that leg multiplied by the ratio is greater than the value of the other order.

The price of a combo order = [({Cost of Leg 1} * {The ratio of Leg 1}) + ({Cost of Leg n} * {Ratio of Leg n}) + ({Cost of Leg n+1} * {Ratio of Leg n+1})]

Cancel Order

Cancels 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.

DELETE /iserver/account/{{ accountId }}/order/{{ orderId }}

 

Request Object

Path Param

accountId: String.
The account ID for which account should place the order.

orderId: String.
The orderID for that should be modified.
Can be retrieved from /iserver/account/orders
Submitting ‘-1’ will cancel all open orders

request_url = f”{baseUrl}/iserver/account/U1234567/order/123456789″
requests.delete(url=request_url)

curl \
--url {{baseUrl}}/iserver/account/U1234567/order/123456789 \
--request DELETE

 

Response Object

msg: String.
Returns the confirmation of the request being submitted.

order_id: int.
Returns the orderID of the cancelled order.

conid: int.
Returns the conid for the requested order to be cancelled.
Returns -1 for orders that were immediately cancelled on request.

account: String.
Returns the accountId for the requested order to be cancelled.
Returns null for orders that were immediately cancelled on request.

{
    "msg": "Request was submitted",
    "order_id": 123456789,
    "conid": 265598,
    "account": "U1234567"
}

 

Error Object

error: String.
Returns the error message.

{
    "error": "OrderID 1 doesn't exist"
}

 

Modify Order

Modifies an open order.

Must call /iserver/accounts endpoint prior to modifying an order.

Use /iservers/account/orders endpoint to review open-order(s).

POST /iserver/account/{accountId}/order/{orderId}

 

Request Object

Path Param

accountId: String.
The account ID for which account should place the order.

orderId: String.
The orderID for that should be modified.
Can be retrieved from /iserver/account/orders

Body Params

The body content of the modify order endpoint will follow the same structure as the standard /iserver/account/{accountId}/orders endpoint.

The content should mirror the content of the original order.

See the Place Order section for more details.

request_url = f"{baseUrl}/iserver/account/U1234567/order/123456789
json_content = {
  "conid": 265598,
  "orderType": "STP",
  "price": 180,
  "side": "BUY",
  "tif": "DAY",
  "quantity": 10
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/account/U1234567/order/123456789 \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "conid": 265598,
  "orderType": "STP",
  "price": 180,
  "side": "BUY",
  "tif": "DAY",
  "quantity": 10
}'

 

Response Object

orderId: String.
Returns the orders identifier which can be used for order tracking, modification, and cancellation.

order_status: String.
Returns the order status of the current market order.
See Order Status Value for more information.

encrypt_message: String.
Returns a “1” to display that the message sent was encrypted.

[
    {
        "order_id": "1234567890",
        "order_status": "Submitted",
        "encrypt_message": "1"
    }
]

 

Alternate Response Object

In some instances, you will receive an ID along with a message about your order.

See the Place Order Reply section for more details on resolving the confirmation.

id: String.
Returns a message ID relating to the particular order’s warning confirmation.

message: Array of Strings.
Returns the message warning about why the order wasn’t initially transmitted.

isSuppressed: bool.
Returns if a particular warning was suppressed before sending.
Always returns false.

messageIds: Array of Strings.
Returns an internal message identifier (Internal use only).

[
  {
    "id": "a12b34c5-d678-9e012f-3456-7a890b12cd3e",
    "message": [
      "You are about to submit a stop order. Please be aware of the various stop order types available and the risks associated with each one.\nAre you sure you want to submit this order?"
    ],
    "isSuppressed": false,
    "messageIds": [
      "o0"
    ]
  }
]

 

Suppress Messages

Disables a messageId, or series of messageIds, that will no longer prompt the user.

POST /iserver/questions/suppress

 

Request Object

Body Param

messageIds: Array of Strings.
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. However, users should look to suppress messages on an as-needed basis to avoid unexpected order submissions.

request_url = f"{baseUrl}/iserver/questions/suppress"
json_content = {
  "messageIds": ["o102"]
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/questions/suppress \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "messageIds": ["o102"]
}'

 

Response Object

status: String.
Verifies that the request has been sent.

{
  "status": "submitted"
}

 

Reset Suppressed Messages

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/iserver/questions/suppress/reset"
json_content = {}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/questions/suppress/reset \
--request POST \
--header 'Content-Type:application/json' \
--data ''

 

Response Object

status: String.
Verifies that the request has been sent.

{
  "status": "submitted"
}

 

Portfolio

Portfolio Accounts

In 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. For querying a list of accounts which the user can trade, see /iserver/accounts. For a list of subaccounts in tiered account structures (e.g. financial advisor or ibroker accounts) see /portfolio/subaccounts.

GET /portfolio/accounts

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/portfolio/accounts"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/portfolio/accounts \
--request GET

 

Response Object

id: String
The account ID for which account should place the order.

accountId: String
The account ID for which account should place the order.

accountVan: String
The account alias for which account should place the order.

accountTitle: String
Title of the account

displayName: String
The account ID for which account should place the order.

accountAlias: String
User customizable account alias. Refer to Configure Account Alias for details.

accountStatus: int.
When the account was opened in unix time.

currency: String
Base currency of the account.

type: String
Account Type

tradingType: String
Account trading structure.

businessType: String.
Returns the organizational strcuture of the account.

ibEntity: String.
Returns the entity of Interactive Brokers the account is tied to.

faClient: bool.
If an account is a sub-account to a Financial Advisor.

clearingStatus: String
Status of the Account
Potential Values: O: Open; P or N: Pending; A: Abandoned; R: Rejected; C: Closed.

covestor: bool.
Is a Covestor Account

noClientTrading: bool.
Returns if the client account may trade.

trackVirtualFXPortfolio: bool.
Returns if the account is tracking Virtual FX or not.

parent: {

mmc: Array of Strings.
Returns the Money Manager Client Account.

accountId: String
Account Number for Money Manager Client

isMParent: bool.
Returns if this is a Multiplex Parent Account

isMChild: bool.
Returns if this is a Multiplex Child Account

isMultiplex: bool.
Is a Multiplex Account. These are account models with individual account being parent and managed account being child.

}
desc: String
Returns an account description.
Value Format: “accountId – accountAlias”
}]

[
  {
    "id": "U1234567",
    "PrepaidCrypto-Z": false,
    "PrepaidCrypto-P": false,
    "brokerageAccess": true,
    "accountId": "U1234567",
    "accountVan": "U1234567",
    "accountTitle": "",
    "displayName": "U1234567",
    "accountAlias": null,
    "accountStatus": 1644814800000,
    "currency": "USD",
    "type": "DEMO",
    "tradingType": "PMRGN",
    "businessType": "IB_PROSERVE",
    "ibEntity": "IBLLC-US",
    "faclient": false,
    "clearingStatus": "O",
    "covestor": false,
    "noClientTrading": false,
    "trackVirtualFXPortfolio": true,
    "parent": {
      "mmc": [],
      "accountId": "",
      "isMParent": false,
      "isMChild": false,
      "isMultiplex": false
    },
    "desc": "U1234567"
  }
]

 

Portfolio Subaccounts

Used 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. If you have more than 100 sub-accounts use /portfolio/subaccounts2. To query a list of accounts the user can trade, see /iserver/accounts.

GET /portfolio/subaccounts

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/portfolio/subaccounts"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/portfolio/subaccounts \
--request GET

 

Response Object

id: String
The account ID for which account should place the order.

accountId: String
The account ID for which account should place the order.

accountVan: String
The account alias for which account should place the order.

accountTitle: String
Title of the account

displayName: String
The account ID for which account should place the order.

accountAlias: String
User customizable account alias. Refer to Configure Account Alias for details.

accountStatus: int.
When the account was opened in unix time.

currency: String
Base currency of the account.

type: String
Account Type

tradingType: String
Account trading structure.

businessType: String.
Returns the organizational strcuture of the account.

ibEntity: String.
Returns the entity of Interactive Brokers the account is tied to.

faClient: bool.
If an account is a sub-account to a Financial Advisor.

clearingStatus: String
Status of the Account
Potential Values: O: Open; P or N: Pending; A: Abandoned; R: Rejected; C: Closed.

covestor: bool.
Is a Covestor Account

noClientTrading: bool.
Returns if the client account may trade.

trackVirtualFXPortfolio: bool.
Returns if the account is tracking Virtual FX or not.

parent: {

mmc: Array of Strings.
Returns the Money Manager Client Account.

accountId: String
Account Number for Money Manager Client

isMParent: bool.
Returns if this is a Multiplex Parent Account

isMChild: bool.
Returns if this is a Multiplex Child Account

isMultiplex: bool.
Is a Multiplex Account. These are account models with individual account being parent and managed account being child.

}
desc: String
Returns an account description.
Value Format: “accountId – accountAlias”
}]

[
  {
    "id": "U1234567",
    "PrepaidCrypto-Z": false,
    "PrepaidCrypto-P": false,
    "brokerageAccess": false,
    "accountId": "U1234567",
    "accountVan": "U1234567",
    "accountTitle": "",
    "displayName": "U1234567",
    "accountAlias": null,
    "accountStatus": 1644814800000,
    "currency": "USD",
    "type": "DEMO",
    "tradingType": "PMRGN",
    "businessType": "IB_PROSERVE",
    "ibEntity": "IBLLC-US",
    "faclient": false,
    "clearingStatus": "O",
    "covestor": false,
    "noClientTrading": false,
    "trackVirtualFXPortfolio": true,
    "parent": {
      "mmc": [],
      "accountId": "",
      "isMParent": false,
      "isMChild": false,
      "isMultiplex": false
    },
    "desc": "U1234567"
  }
]

 

Portfolio Subaccounts (Large Account Structures)

Used 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. If you have less than 100 sub-accounts use /portfolio/subaccounts. To query a list of accounts the user can trade, see /iserver/accounts.

GET /portfolio/subaccounts2

 

Request Object

page: String. Required
Indicate the page identifier that should be retrieved.
Pagination begins at page 0.
20 accounts returned per page.

request_url = f"{baseUrl}/portfolio/subaccounts2?page=0"
requests.get(url=request_url) 

 

curl \
--url {{baseUrl}}/portfolio/subaccounts2?page=0 \
--request GET

 

Response Object

metadata: Object.
Contains metadata about the response data.
{
total: int.
Displays the total number of accounts returned.

pageSize: int.
Returns the page size.

pageNum: int.
Returns the page number or identifier of the request.

subaccounts: Array of Objects.
Contains all of the accounts and their respective data.
[{
id: String
The account ID for which account should place the order.

accountId: String
The account ID for which account should place the order.

accountVan: String
The account alias for which account should place the order.

accountTitle: String
Title of the account

displayName: String
The account ID for which account should place the order.

accountAlias: String
User customizable account alias. Refer to Configure Account Alias for details.

accountStatus: int.
When the account was opened in unix time.

currency: String
Base currency of the account.

type: String
Account Type

tradingType: String
Account trading structure.

businessType: String.
Returns the organizational strcuture of the account.

ibEntity: String.
Returns the entity of Interactive Brokers the account is tied to.

faClient: bool.
If an account is a sub-account to a Financial Advisor.

clearingStatus: String
Status of the Account
Potential Values: O: Open; P or N: Pending; A: Abandoned; R: Rejected; C: Closed.

covestor: bool.
Is a Covestor Account

noClientTrading: bool.
Returns if the client account may trade.

trackVirtualFXPortfolio: bool.
Returns if the account is tracking Virtual FX or not.

parent: {

mmc: Array of Strings.
Returns the Money Manager Client Account.

accountId: String
Account Number for Money Manager Client

isMParent: bool.
Returns if this is a Multiplex Parent Account

isMChild: bool.
Returns if this is a Multiplex Child Account

isMultiplex: bool.
Is a Multiplex Account. These are account models with individual account being parent and managed account being child.

}
desc: String
Returns an account description.
Value Format: “accountId – accountAlias”
}]

[
  {
    "id": "U1234567",
    "PrepaidCrypto-Z": false,
    "PrepaidCrypto-P": false,
    "brokerageAccess": false,
    "accountId": "U1234567",
    "accountVan": "U1234567",
    "accountTitle": "",
    "displayName": "U1234567",
    "accountAlias": null,
    "accountStatus": 1644814800000,
    "currency": "USD",
    "type": "DEMO",
    "tradingType": "PMRGN",
    "businessType": "IB_PROSERVE",
    "ibEntity": "IBLLC-US",
    "faclient": false,
    "clearingStatus": "O",
    "covestor": false,
    "noClientTrading": false,
    "trackVirtualFXPortfolio": true,
    "parent": {
      "mmc": [],
      "accountId": "",
      "isMParent": false,
      "isMChild": false,
      "isMultiplex": false
    },
    "desc": "U1234567"
  }
]

 

Specific Account's Portfolio Information

Account information related to account Id /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint.

GET /portfolio/{accountId}/meta

 

Request Object

Path Params

accountId: String. Required
Specify the AccountID to receive portfolio information for.

request_url = f"{baseUrl}/portfolio/U1234567/meta"
requests.get(url=request_url) 

 

curl \
--url {{baseUrl}}/portfolio/U1234567/meta \
--request GET

 

Response Object

id: String
The account ID for which account should place the order.

accountId: String
The account ID for which account should place the order.

accountVan: String
The account alias for which account should place the order.

accountTitle: String
Title of the account

displayName: String
The account ID for which account should place the order.

accountAlias: String
User customizable account alias. Refer to Configure Account Alias for details.

accountStatus: int.
When the account was opened in unix time.

currency: String
Base currency of the account.

type: String
Account Type

tradingType: String
Account trading structure.

businessType: String.
Returns the organizational strcuture of the account.

ibEntity: String.
Returns the entity of Interactive Brokers the account is tied to.

faClient: bool.
If an account is a sub-account to a Financial Advisor.

clearingStatus: String
Status of the Account
Potential Values: O: Open; P or N: Pending; A: Abandoned; R: Rejected; C: Closed.

covestor: bool.
Is a Covestor Account

noClientTrading: bool.
Returns if the client account may trade.

trackVirtualFXPortfolio: bool.
Returns if the account is tracking Virtual FX or not.

parent: {

mmc: Array of Strings.
Returns the Money Manager Client Account.

accountId: String
Account Number for Money Manager Client

isMParent: bool.
Returns if this is a Multiplex Parent Account

isMChild: bool.
Returns if this is a Multiplex Child Account

isMultiplex: bool.
Is a Multiplex Account. These are account models with individual account being parent and managed account being child.

}
desc: String
Returns an account description.
Value Format: “accountId – accountAlias”
}]

{
  "id": "U1234567",
  "PrepaidCrypto-Z": false,
  "PrepaidCrypto-P": false,
  "brokerageAccess": false,
  "accountId": "U1234567",
  "accountVan": "U1234567",
  "accountTitle": "",
  "displayName": "U1234567",
  "accountAlias": null,
  "accountStatus": 1644814800000,
  "currency": "USD",
  "type": "DEMO",
  "tradingType": "PMRGN",
  "businessType": "IB_PROSERVE",
  "ibEntity": "IBLLC-US",
  "faclient": false,
  "clearingStatus": "O",
  "covestor": false,
  "noClientTrading": false,
  "trackVirtualFXPortfolio": true,
  "parent": {
    "mmc": [],
    "accountId": "",
    "isMParent": false,
    "isMChild": false,
    "isMultiplex": false
  },
  "desc": "U1234567"
}

 

Portfolio Allocation (Single)

Information about the account’s portfolio allocation by Asset Class, Industry and Category. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint.

GET /portfolio/{accountId}/allocation

 

Request Object

Path Params

accountId: String. Required
Specify the account ID for the request.

request_url = f"{baseUrl}/portfolio/U1234567/allocation"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/portfolio/U1234567/allocation \
--request GET

 

assetClass: Object.
Contains details pertaining to specific security types.
{
long: Object.
Returns the value of the asset class currently traded long.

short: Object.
Returns the value of the asset class currently traded short.
},

sector: Object.
Contains details pertaining to specific trade sectors.
{
long: Object.
Returns the value of the trade sector currently traded long.

short: Object.
Returns the value of the trade sector currently traded short.
},

group: Object.
Contains details pertaining to specific industry groups.
{
long: Object.
Returns the value of the industry group currently traded long.

short: Object.
Returns the value of the industry group currently traded short.
}

{
  "assetClass": {
    "long": {
      "OPT": 27.12,
      "STK": 317071.39468663215,
      "CASH": 2.1510110008312488E8
    },
    "short": {
      "OPT": -30.0,
      "CASH": -25.917167515158653
    }
  },
  "sector": {
    "long": {
      "Others": 5628.650040692091,
      "Technology": 237511.16,
      "Industrial": 43134.63,
      "Consumer, Cyclical": 22537.62620745659,
      "Financial": 2504.35,
      "Communications": 5116.61,
      "Consumer, Non-cyclical": 665.4884384834767
    },
    "short": {
      "Others": -30.0
    }
  },
  "group": {
    "long": {
      "Computers": 121517.38,
      "Others": 5628.650040692091,
      "Semiconductors": 115993.78,
      "Auto Manufacturers": 22537.62620745659,
      "Banks": 2504.35,
      "Miscellaneous Manufactur": 43134.63,
      "Internet": 5116.61,
      "Beverages": 649.07,
      "Pharmaceuticals": 16.41843848347664
    },
    "short": {
      "Others": -30.0
    }
  }
}

 

Portfolio Allocation (All)

Similar to /portfolio/{accountId}/allocation but returns a consolidated view of of all the accounts returned by /portfolio/accounts. /portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint.

POST /portfolio/allocation

 

Request Object

Body Params

acctIds: Array of Strings. Required
Contains all account IDs as strings the user should receive data for.

request_url = f"{baseUrl}/portfolio/allocation"
json_content = {
  "acctIds": [
    "U1234567",
    "U4567890"
  ]
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/portfolio/allocation \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "acctIds": [
    "U1234567",
    "U4567890"
  ]
}'

 

assetClass: Object.
Contains details pertaining to specific security types.
{
long: Object.
Returns the value of the asset class currently traded long.

short: Object.
Returns the value of the asset class currently traded short.
},

sector: Object.
Contains details pertaining to specific trade sectors.
{
long: Object.
Returns the value of the trade sector currently traded long.

short: Object.
Returns the value of the trade sector currently traded short.
},

group: Object.
Contains details pertaining to specific industry groups.
{
long: Object.
Returns the value of the industry group currently traded long.

short: Object.
Returns the value of the industry group currently traded short.
}

{
  "assetClass": {
    "long": {
      "OPT": 27.12,
      "STK": 316441.2320366,
      "CASH": 2.1510102008312488E8
    },
    "short": {
      "OPT": -30.0,
      "CASH": -25.923946709036827
    }
  },
  "sector": {
    "long": {
      "Others": 5624.600040692091,
      "Technology": 237014.72999999998,
      "Industrial": 43077.12,
      "Consumer, Cyclical": 22453.78620745659,
      "Financial": 2503.3599999999997,
      "Communications": 5126.98,
      "Consumer, Non-cyclical": 667.7757884514332
    },
    "short": {
      "Others": -30.0
    }
  },
  "group": {
    "long": {
      "Computers": 121222.53,
      "Others": 5624.600040692091,
      "Semiconductors": 115792.2,
      "Auto Manufacturers": 22453.78620745659,
      "Banks": 2503.3599999999997,
      "Miscellaneous Manufactur": 43077.12,
      "Internet": 5126.98,
      "Beverages": 651.35,
      "Pharmaceuticals": 16.42578845143318
    },
    "short": {
      "Others": -30.0
    }
  }
}

 

Positions

Returns a list of positions for the given account.
The endpoint supports paging, each page will return up to 100 positions.
/portfolio/accounts or /portfolio/subaccounts must be called prior to this endpoint.

GET /portfolio/{accountId}/positions/{pageId}

 

Request Object

Path Params

accountId: String. Required
The account ID for which account should place the order.

pageId: String. Required
The “page” of positions that should be returned.
One page contains a maximum of 100 positions.
Pagination starts at 0.

Query Params

model: String.
Code for the model portfolio to compare against.

sort: String.
Declare the table to be sorted by which column

direction: String.
The order to sort by.
‘a’ means ascending
‘d’ means descending

period: String.
period for pnl column
Value Format: 1D, 7D, 1M

request_url = f"{baseUrl}/portfolio/U1234567/positions/0?direction=a&period=1W&sort=position&model=MyModel"
requests.get(url=request_url) 

 

curl \
--url {{baseUrl}}/portfolio/U1234567/positions/0?direction=a&period=1W&sort=position&model=MyModel \
--request GET

 

Response Object

acctId: String.

conid: int.
Returns the contract ID of the position.

contractDesc: String.
Returns the local symbol of the order.

position: float.
Returns the total size of the position.

mktPrice:  float.
Returns the current market price of each share.

mktValue:  float.
Returns the total value of the order.

avgCost: float.
Returns the average cost of each share in the position times the multiplier.

avgPrice: float.
Returns the average cost of each share in the position when purchased.

realizedPnl: float.
Returns the total profit made today through trades.

unrealizedPnl: float.
Returns the total potential profit if you were to trade.

exchs: null.
Deprecated value.
Always returns null.

currency: String.
Returns the traded currency for the contract.

time: int.
Returns amount of time in ms to generate the data.

chineseName: String.
Returns the Chinese characters for the symbol.

allExchanges: String*.
Returns a series of exchanges the given symbol can trade on.

listingExchange: String.
Returns the primary or listing exchange the contract is hosted on.

countryCode: String.
Returns the country code the contract is traded on.

name: String.
Returns the comapny name.

assetClass: String.
Returns the asset class or security type of the contract.

expiry: String.
Returns the expiry of the contract. Returns null for non-expiry instruments.

lastTradingDay: String.
Returns the last trading day of the contract.

group: String.
Returns the group or industry the contract is affilated with.

putOrCall: String.
Returns if the contract is a Put or Call option.

sector: String.
Returns the contract’s sector.

sectorGroup: String.
Returns the sector’s group.

strike: int.
Returns the strike of the contract.

ticker: String.
Returns the ticker symbol of the traded contract.

undConid: int.
Returns the contract’s underlyer.

multiplier: float,
Returns the contract multiplier.

type: String.
Returns stock type.

hasOptions: bool.
Returns if contract has tradable options contracts.

fullName: String.
Returns symbol name for requested contract.

isUS: bool.
Returns if the contract is US based or not.

incrementRules: Array.
Returns rules regarding incrementation for market data and order placemnet.

lowerEdge: float,
Returns lower edge value used to calculate increment.

increment: float.
Allowed incrementable value.

displayRule: object.
Returns an object containing display content for market data.

magnification: int.
Returns maginification or multiplier of contract

displayRuleStep: Array.
Contains various rules in the display object.

decimalDigits: int.
Returns average decimal digit for data display.

lowerEdge: float.
Returns lower edge value used to calculate increment.

wholeDigits: int.
Returns allowed display size.

isEventContract: bool.
Returns if the contract is an event contract or not.

pageSize: int.
Returns the content size of the request.
}]

[
  {
    "acctId": "U1234567",
    "conid": 756733,
    "contractDesc": "SPY",
    "position": 5.0,
    "mktPrice": 471.16000365,
    "mktValue": 2355.8,
    "currency": "USD",
    "avgCost": 434.93,
    "avgPrice": 434.93,
    "realizedPnl": 0.0,
    "unrealizedPnl": 181.15,
    "exchs": null,
    "expiry": null,
    "putOrCall": null,
    "multiplier": null,
    "strike": 0.0,
    "exerciseStyle": null,
    "conExchMap": [],
    "assetClass": "STK",
    "undConid": 0,
    "model": ""
  },
  {
    "acctId": "U1234567",
    "conid": 76792991,
    "contractDesc": "TSLA",
    "position": 7.0,
    "mktPrice": 250.73399355,
    "mktValue": 1755.14,
    "currency": "USD",
    "avgCost": 221.67142855,
    "avgPrice": 221.67142855,
    "realizedPnl": 0.0,
    "unrealizedPnl": 203.44,
    "exchs": null,
    "expiry": null,
    "putOrCall": null,
    "multiplier": null,
    "strike": 0.0,
    "exerciseStyle": null,
    "conExchMap": [],
    "assetClass": "STK",
    "undConid": 0,
    "model": ""
  },
  {
    "acctId": "U1234567",
    "conid": 107113386,
    "contractDesc": "META",
    "position": 11.0,
    "mktPrice": 333.1199951,
    "mktValue": 3664.32,
    "currency": "USD",
    "avgCost": 306.6909091,
    "avgPrice": 306.6909091,
    "realizedPnl": 0.0,
    "unrealizedPnl": 290.72,
    "exchs": null,
    "expiry": null,
    "putOrCall": null,
    "multiplier": null,
    "strike": 0.0,
    "exerciseStyle": null,
    "conExchMap": [],
    "assetClass": "STK",
    "undConid": 0,
    "model": ""
  }
]

 

Positions by Conid

Returns a list containing position details only for the specified conid

GET /portfolio/{acctId}/position/{conid}

 

Request Object

Path Params

accountId: String. Required
The account ID for which account should place the order.

conId: String. Required
The contract ID to receive position information on.

request_url = f"{baseUrl}/portfolio/U1234567/position/265598"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/portfolio/U1234567/position/265598 \
--request GET

 

Response Object

acctId: String.

conid: int.
Returns the contract ID of the position.

contractDesc: String.
Returns the local symbol of the order.

position: float.
Returns the total size of the position.

mktPrice:  float.
Returns the current market price of each share.

mktValue:  float.
Returns the total value of the order.

avgCost: float.
Returns the average cost of each share in the position times the multiplier.

avgPrice: float.
Returns the average cost of each share in the position when purchased.

realizedPnl: float.
Returns the total profit made today through trades.

unrealizedPnl: float.
Returns the total potential profit if you were to trade.

exchs: null.
Deprecated value.
Always returns null.

currency: String.
Returns the traded currency for the contract.

time: int.
Returns amount of time in ms to generate the data.

chineseName: String.
Returns the Chinese characters for the symbol.

allExchanges: String*.
Returns a series of exchanges the given symbol can trade on.

listingExchange: String.
Returns the primary or listing exchange the contract is hosted on.

countryCode: String.
Returns the country code the contract is traded on.

name: String.
Returns the comapny name.

assetClass: String.
Returns the asset class or security type of the contract.

expiry: String.
Returns the expiry of the contract. Returns null for non-expiry instruments.

lastTradingDay: String.
Returns the last trading day of the contract.

group: String.
Returns the group or industry the contract is affilated with.

putOrCall: String.
Returns if the contract is a Put or Call option.

sector: String.
Returns the contract’s sector.

sectorGroup: String.
Returns the sector’s group.

strike: int.
Returns the strike of the contract.

ticker: String.
Returns the ticker symbol of the traded contract.

undConid: int.
Returns the contract’s underlyer.

multiplier: float,
Returns the contract multiplier.

type: String.
Returns stock type.

hasOptions: bool.
Returns if contract has tradable options contracts.

fullName: String.
Returns symbol name for requested contract.

isUS: bool.
Returns if the contract is US based or not.

incrementRules: Array.
Returns rules regarding incrementation for market data and order placemnet.

lowerEdge: float,
Returns lower edge value used to calculate increment.

increment: float.
Allowed incrementable value.

displayRule: object.
Returns an object containing display content for market data.

magnification: int.
Returns maginification or multiplier of contract

displayRuleStep: Array.
Contains various rules in the display object.

decimalDigits: int.
Retrns average decimal digit for data display.

lowerEdge: float.
Returns lower edge value used to calculate increment.

wholeDigits: int.
Returns allowed display size.

isEventContract: bool.
Returns if the contract is an event contract or not.

pageSize: int.
Returns the content size of the request.
}]

[
  {
    "acctId": "U1234567",
    "conid": 265598,
    "contractDesc": "AAPL",
    "position": 614.2639,
    "mktPrice": 197.3840027,
    "mktValue": 121245.87,
    "currency": "USD",
    "avgCost": 192.7477563,
    "avgPrice": 192.7477563,
    "realizedPnl": 0.0,
    "unrealizedPnl": 2847.88,
    "exchs": null,
    "expiry": null,
    "putOrCall": null,
    "multiplier": 0.0,
    "strike": "0",
    "exerciseStyle": null,
    "conExchMap": [],
    "assetClass": "STK",
    "undConid": 0,
    "model": "",
    "time": 43,
    "chineseName": "苹果公司",
    "allExchanges": "AMEX,NYSE,CBOE,PHLX,CHX,ARCA,ISLAND,ISE,IDEAL,NASDAQQ,NASDAQ,DRCTEDGE,BEX,BATS,NITEECN,EDGEA,CSFBALGO,JEFFALGO,NYSENASD,PSX,BYX,ITG,PDQ,IBKRATS,CITADEL,NYSEDARK,MIAX,IBDARK,CITADELDP,NASDDARK,IEX,WEDBUSH,SUMMER,WINSLOW,FINRA,LIQITG,UBSDARK,BTIG,VIRTU,JEFF,OPCO,COWEN,DBK,JPMC,EDGX,JANE,NEEDHAM,FRACSHARE,RBCALGO,VIRTUDP,BAYCREST,FOXRIVER,MND,NITEEXST,PEARL,GSDARK,NITERTL,NYSENAT,IEXMID,HRT,FLOWTRADE,HRTDP,JANELP,PEAK6,IMCDP,CTDLZERO,HRTMID,JANEZERO,HRTEXST,IMCLP,LTSE,SOCGENDP,MEMX,INTELCROS,VIRTUBYIN,JUMPTRADE,NITEZERO,TPLUS1,XTXEXST,XTXDP,XTXMID,COWENLP,BARCDP,JUMPLP,OLDMCLP,RBCCMALP,WALLBETH,IBEOS,JONES,GSLP,BLUEOCEAN,USIBSILP,OVERNIGHT,JANEMID,IBATSEOS,HRTZERO,VIRTUALGO",
    "listingExchange": "NASDAQ",
    "countryCode": "US",
    "name": "APPLE INC",
    "lastTradingDay": null,
    "group": "Computers",
    "sector": "Technology",
    "sectorGroup": "Computers",
    "ticker": "AAPL",
    "type": "COMMON",
    "hasOptions": true,
    "fullName": "AAPL",
    "isUS": true,
    "incrementRules": [
      {
        "lowerEdge": 0.0,
        "increment": 0.01
      }
    ],
    "displayRule": {
      "magnification": 0,
      "displayRuleStep": [
        {
          "decimalDigits": 2,
          "lowerEdge": 0.0,
          "wholeDigits": 4
        }
      ]
    },
    "isEventContract": false,
    "pageSize": 100
  }
]

 

Invalidate Backend Portfolio Cache

Invalidates the cached value for your portfolio’s positions and calls the /portfolio/{accountId}/positions/0 endpoint automatically.

POST /portfolio/{accountId}/positions/invalidate

 

Request Object

Path Params

accountId: String. Required
The account ID for which cache to invalidate.

request_url = f"{baseUrl}/portfolio/U1234567/positions/invalidate"
json_content = {}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/portfolio/U1234567/positions/invalidate \
--request POST \
--header 'Content-Type:application/json' \
--data '{}'

 

Response Object

acctId: String.

conid: int.
Returns the contract ID of the position.

contractDesc: String.
Returns the local symbol of the order.

position: float.
Returns the total size of the position.

mktPrice:  float.
Returns the current market price of each share.

mktValue:  float.
Returns the total value of the order.

avgCost: float.
Returns the average cost of each share in the position times the multiplier.

avgPrice: float.
Returns the average cost of each share in the position when purchased.

realizedPnl: float.
Returns the total profit made today through trades.

unrealizedPnl: float.
Returns the total potential profit if you were to trade.

exchs: null.
Deprecated value.
Always returns null.

currency: String.
Returns the traded currency for the contract.

time: int.
Returns amount of time in ms to generate the data.

chineseName: String.
Returns the Chinese characters for the symbol.

allExchanges: String*.
Returns a series of exchanges the given symbol can trade on.

listingExchange: String.
Returns the primary or listing exchange the contract is hosted on.

countryCode: String.
Returns the country code the contract is traded on.

name: String.
Returns the comapny name.

assetClass: String.
Returns the asset class or security type of the contract.

expiry: String.
Returns the expiry of the contract. Returns null for non-expiry instruments.

lastTradingDay: String.
Returns the last trading day of the contract.

group: String.
Returns the group or industry the contract is affilated with.

putOrCall: String.
Returns if the contract is a Put or Call option.

sector: String.
Returns the contract’s sector.

sectorGroup: String.
Returns the sector’s group.

strike: int.
Returns the strike of the contract.

ticker: String.
Returns the ticker symbol of the traded contract.

undConid: int.
Returns the contract’s underlyer.

multiplier: float,
Returns the contract multiplier.

type: String.
Returns stock type.

hasOptions: bool.
Returns if contract has tradable options contracts.

fullName: String.
Returns symbol name for requested contract.

isUS: bool.
Returns if the contract is US based or not.

incrementRules: Array.
Returns rules regarding incrementation for market data and order placemnet.

lowerEdge: float,
Returns lower edge value used to calculate increment.

increment: float.
Allowed incrementable value.

displayRule: object.
Returns an object containing display content for market data.

magnification: int.
Returns maginification or multiplier of contract

displayRuleStep: Array.
Contains various rules in the display object.

decimalDigits: int.
Retrns average decimal digit for data display.

lowerEdge: float.
Returns lower edge value used to calculate increment.

wholeDigits: int.
Returns allowed display size.

isEventContract: bool.
Returns if the contract is an event contract or not.

pageSize: int.
Returns the content size of the request.
}]

[
  {
    "acctId": "U1234567",
    "conid": 265598,
    "contractDesc": "AAPL",
    "position": 614.2639,
    "mktPrice": 197.3840027,
    "mktValue": 121245.87,
    "currency": "USD",
    "avgCost": 192.7477563,
    "avgPrice": 192.7477563,
    "realizedPnl": 0.0,
    "unrealizedPnl": 2847.88,
    "exchs": null,
    "expiry": null,
    "putOrCall": null,
    "multiplier": null,
    "strike": 0.0,
    "exerciseStyle": null,
    "conExchMap": [],
    "assetClass": "STK",
    "undConid": 0,
    "model": ""
  },
  {...},
  {
    "acctId": "U1234567",
    "conid": 8894,
    "contractDesc": "KO",
    "position": 11.0,
    "mktPrice": 59.2400017,
    "mktValue": 651.64,
    "currency": "USD",
    "avgCost": 61.9409091,
    "avgPrice": 61.9409091,
    "realizedPnl": 0.0,
    "unrealizedPnl": -29.71,
    "exchs": null,
    "expiry": null,
    "putOrCall": null,
    "multiplier": null,
    "strike": 0.0,
    "exerciseStyle": null,
    "conExchMap": [],
    "assetClass": "STK",
    "undConid": 0,
    "model": ""
  }
]

 

Portfolio Summary

Information 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.

GET /portfolio/{accountId}/summary

 

Request Object

Path Params

accountId: String. Required
Specify the account ID for which account you require ledger information on.

request_url = f"{baseUrl}/portfolio/U1234567/summary"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/portfolio/U1234567/summary \
--request GET

 

Response Object

The /summary endpoint returns a Key: Value Object structure. This returns a total of 45-135 unique values used to summarize the account.

Responses will come as the base value, containing a summary of all returned details, followed by an identical response name with a trailing “-c” or “-s”. “-c” represents commodity values held under the account. Meanwhile, “-s” represents all security values held on the account.

{object key}: Object.
This key indicates what data is being returned. This may include account information, balance information, or other relevant portfolio details as specified.

amount: float.
Returns the price value regarding the key.
May return null if price value not required.

currency: String.
Returns the base currency the response is built with.

isNull: bool.
Returns if the value is unavailable.

timestamp: int.
Returns the time the data was retrieved in epoch time.

value: String.
Returns a string details about the given key.
May return null if no string value required.

severity: int.
Internal use only.

{
  "accountcode": {
    "amount": 0.0,
    "currency": null,
    "isNull": false,
    "timestamp": 1702582422000,
    "value": "U1234567",
    "severity": 0
  },
  {...},
  "indianstockhaircut": {
    "amount": 0.0,
    "currency": "USD",
    "isNone": false,
    "timestamp": 1702582422000,
    "value": null,
    "severity": 0
  }
}

 

Portfolio Ledger

Information 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.

GET /portfolio/{accountId}/ledger

 

Request Object

Path Params

accountId: String. Required
Specify the account ID for which account you require ledger information on.

request_url = f"{baseUrl}/portfolio/U1234567/ledger"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/portfolio/U1234567/ledger \
--request GET

 

Response Object

{currency}: Object.
Returns the ledger values for the specified currency.
May return “BASE” to show your base currency.
{
commoditymarketvalue: float.
Returns the total market value of commodity positions in the given currency.

futuremarketvalue: float.
Returns the total market value of futures positions in the given currency.

settledcash: float.
Returns the total settled cash for the given currency.

exchangerate: int.
Returns the exchange rate from the base currency to the specified currency.

sessionid: int.
Internal use only.

cashbalance: float.
Returns the total cash available for trading in the given currency.

corporatebondsmarketvalue: float.
Returns the total market value of corporate bond positions in the given currency.

warrantsmarketvalue: float.
Returns the total market value of warrant positions in the given currency.

netliquidationvalue: float.
Returns the current net liquidation value of the positions held in the given currency.

interest: float.
Returns the margin interest rate on the given currency.

unrealizedpnl: float.
Returns the unrealized profit and loss for positions in the given currency.

stockmarketvalue: float.
Returns the total market value of stock positions in the given currency.

moneyfunds: float.
Returns the total market value of money funds positions in the given currency.

currency: String.
Returns the currency’s symbol.

realizedpnl: float.
Returns the realized profit and loss for positions in the given currency.

funds: float.
Returns the total market value of all funds positions in the given currency.

acctcode: String.
Returns the account ID for the account owner specified.

issueroptionsmarketvalue: float.
Returns the total market value of all issuer option positions in the given currency.

key: String.
Returns “LedgerList”. Internal use only.

timestamp: int.
Returns the timestamp for the value retrieved in epoch time.

severity: int.
Internal use only.

stockoptionmarketvalue: float.
Returns the total market value of all stock option positions in the given currency.

futuresonlypnl: float.

tbondsmarketvalue: float.
Returns the total market value of all treasury bond positions in the given currency.

futureoptionmarketvalue: float.
Returns the total market value of all futures option positions in the given currency.

cashbalancefxsegment: float.
Internal use only.

secondkey: String.
Returns the currency’s symbol.

tbillsmarketvalue: float.
Returns the total market value of all treasury bill positions in the given currency.

dividends: float.
Returns the value of dividends held from the given currency.
}

{
  "USD": {
    "commoditymarketvalue": 0.0,
    "futuremarketvalue": -1051.0,
    "settledcash": 214716688.0,
    "exchangerate": 1,
    "sessionid": 1,
    "cashbalance": 214716688.0,
    "corporatebondsmarketvalue": 0.0,
    "warrantsmarketvalue": 0.0,
    "netliquidationvalue": 215335840.0,
    "interest": 305569.94,
    "unrealizedpnl": 39695.82,
    "stockmarketvalue": 314123.88,
    "moneyfunds": 0.0,
    "currency": "USD",
    "realizedpnl": 0.0,
    "funds": 0.0,
    "acctcode": "U1234567",
    "issueroptionsmarketvalue": 0.0,
    "key": "LedgerList",
    "timestamp": 1702582321,
    "severity": 0,
    "stockoptionmarketvalue": -2.88,
    "futuresonlypnl": -1051.0,
    "tbondsmarketvalue": 0.0,
    "futureoptionmarketvalue": 0.0,
    "cashbalancefxsegment": 0.0,
    "secondkey": "USD",
    "tbillsmarketvalue": 0.0,
    "endofbundle": 1,
    "dividends": 0.0
  },
  "BASE": {
    "commoditymarketvalue": 0.0,
    "futuremarketvalue": -1051.0,
    "settledcash": 215100080.0,
    "exchangerate": 1,
    "sessionid": 1,
    "cashbalance": 215100080.0,
    "corporatebondsmarketvalue": 0.0,
    "warrantsmarketvalue": 0.0,
    "netliquidationvalue": 215721776.0,
    "interest": 305866.88,
    "unrealizedpnl": 39907.37,
    "stockmarketvalue": 316365.38,
    "moneyfunds": 0.0,
    "currency": "BASE",
    "realizedpnl": 0.0,
    "funds": 0.0,
    "acctcode": "U1234567",
    "issueroptionsmarketvalue": 0.0,
    "key": "LedgerList",
    "timestamp": 1702582321,
    "severity": 0,
    "stockoptionmarketvalue": -2.88,
    "futuresonlypnl": -1051.0,
    "tbondsmarketvalue": 0.0,
    "futureoptionmarketvalue": 0.0,
    "cashbalancefxsegment": 0.0,
    "secondkey": "BASE",
    "tbillsmarketvalue": 0.0,
    "dividends": 0.0
  }
}

 

Position & Contract Info

Returns an object containing information about a given position along with its contract details.

GET /portfolio/positions/{conid}

 

Request Object

Path Params

conId: String. Required
The contract ID to receive position information on.

request_url = f"{baseUrl}/portfolio/positions/265598"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/portfolio/positions/265598 \
--request GET

 

Response Object

accountId: String.
Displays the accountId returning data for.

acctId: String.
Displays the accountId to return data for.

conid: int.
Returns the contract ID of the position.

contractDesc: String.
Returns the local symbol of the order.

position: float.
Returns the total size of the position.

mktPrice:  float.
Returns the current market price of each share.

mktValue:  float.
Returns the total value of the order.

avgCost: float.
Returns the average cost of each share in the position times the multiplier.

avgPrice: float.
Returns the average cost of each share in the position when purchased.

realizedPnl: float.
Returns the total profit made today through trades.

unrealizedPnl: float.
Returns the total potential profit if you were to trade.

exchs: null.
Deprecated value.
Always returns null.

currency: String.
Returns the traded currency for the contract.

time: int.
Returns amount of time in ms to generate the data.

chineseName: String.
Returns the Chinese characters for the symbol.

allExchanges: String*.
Returns a series of exchanges the given symbol can trade on.

listingExchange: String.
Returns the primary or listing exchange the contract is hosted on.

countryCode: String.
Returns the country code the contract is traded on.

name: String.
Returns the comapny name.

assetClass: String.
Returns the asset class or security type of the contract.

expiry: String.
Returns the expiry of the contract. Returns null for non-expiry instruments.

lastTradingDay: String.
Returns the last trading day of the contract.

group: String.
Returns the group or industry the contract is affilated with.

putOrCall: String.
Returns if the contract is a Put or Call option.

sector: String.
Returns the contract’s sector.

sectorGroup: String.
Returns the sector’s group.

strike: int.
Returns the strike of the contract.

ticker: String.
Returns the ticker symbol of the traded contract.

undConid: int.
Returns the contract’s underlyer.

multiplier: float,
Returns the contract multiplier.

type: String.
Returns stock type.

hasOptions: bool.
Returns if contract has tradable options contracts.

fullName: String.
Returns symbol name for requested contract.

isUS: bool.
Returns if the contract is US based or not.

incrementRules: Array.
Returns rules regarding incrementation for market data and order placemnet.

lowerEdge: float,
Returns lower edge value used to calculate increment.

increment: float.
Allowed incrementable value.

displayRule: object.
Returns an object containing display content for market data.

magnification: int.
Returns maginification or multiplier of contract

displayRuleStep: Array.
Contains various rules in the display object.

decimalDigits: int.
Retrns average decimal digit for data display.

lowerEdge: float.
Returns lower edge value used to calculate increment.

wholeDigits: int.
Returns allowed display size.

isEventContract: bool.
Returns if the contract is an event contract or not.

pageSize: int.
Returns the content size of the request.
}]

[
  {
    "acctId": "U1234567",
    "conid": 265598,
    "contractDesc": "AAPL",
    "position": 614.2639,
    "mktPrice": 197.7639923,
    "mktValue": 121479.28,
    "currency": "USD",
    "avgCost": 192.7477563,
    "avgPrice": 192.7477563,
    "realizedPnl": 0.0,
    "unrealizedPnl": 3081.29,
    "exchs": null,
    "expiry": null,
    "putOrCall": null,
    "multiplier": null,
    "strike": 0.0,
    "exerciseStyle": null,
    "conExchMap": [],
    "assetClass": "STK",
    "undConid": 0,
    "model": ""
  }
]

 

PortfolioAnalyst

Account Performance

Returns the performance (MTM) for the given accounts, if more than one account is passed, the result is consolidated.

POST /pa/performance

 

Request Object

Body Parameters

acctIds: Array of Strings. Required
Include each account ID to receive data for.

period: String. Required
Specify the period for which the account should be analyzed.
Available Values: “1D”,”7D”,”MTD”,”1M”,”YTD”,”1Y”

request_url = f"{baseUrl}/pa/performance"
json_content = {
  "acctIds": ["U1234567"]
  "period": "1D"
}
requests.post(url=request_url, json=json_content)

 

curl \
{{baseUrl}}/pa/performance \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "acctIds": ["U1234567", "U4567890"]
  "period": "1D"
}'

 

Response Object

currencyType: String.
Confirms if the currency type.
If trading primarily in your base currency, “base” will be returned.

rc: int.
Returns the data identifier (Client Portal Only).

nav: Object.
Net asset value data for the account or consolidated accounts. NAV data is not applicable to benchmarks.

data: Array of Object.
Contains the affiliated ‘nav’ data.

idType: String.
Returns how identifiers are determined.

navs: int.
Returns the series of data points corresponding to the listed days.

start: String.
Returns the first available date for data.

end: String.
Returns the end of the available frequency.

id: String.
Returns the account identifier.

startNAV: Object.
Returns the intiial NAV available.

date: String.
Returns the starting date for the request.

val: int.
Returns the Net Asset Value of the account.

baseCurrency: String.
Returns the base currency used in the account.

freq: String.
Displays the values corresponding to a given frequency.

dates: Array of Strings.
Returns the array of dates corresponding to your frequency, the length should be same as the length of returns inside data.

nd: int.
Returns the total data points.

cps: object.
Returns the object containing the Cumulative performance data.

data: Array of Objects.
Returns the array of cps data available.

idType: String.
Returns the key value of the request.

start: String.
Returns the starting value of the value range.

end: String.
Returns the ending value of the value range.

returns: Array of ints.
Returns all cps values in order between the start and end times.

id: String.
Returns the account identifier.

baseCurrency: String.
Returns the base curency for the account.

freq: String.
Returns the determining frequency of the data range.

dates: Array of Strings.
Returns the dates corresponding to the frequency of data.

tpps: Object.
Returns the Time period performance data.

data: Array.
Object containing all data about tpps.

idType: String.
Returns the key value of the request.

start: String.
Returns the starting value of the value range.

end: String.
Returns the ending value of the value range.

returns: Array of ints.
Returns all cps values in order between the start and end times.

id: String.
Returns the account identifier.

baseCurrency: String.
Returns the base curency for the account.

freq: String.
Returns the determining frequency of the data range.

dates: Array of Strings.
Returns the dates corresponding to the frequency of data.

id: String.
Returns the request identifier, getPerformanceData.

included: Array.
Returns an array contianing accounts reviewed.

pm: String.
Portfolio Measure. Used to indicate TWR or MWR values returned.

{
  "currencyType": "base",
  "rc": 0,
  "nav": {
    "data": [
      {
        "idType": "acctid",
        "navs": [
          2.027673321223E8,
          {...},
          2.157185988239E8
        ],
        "start": "20230102",
        "end": "20231213",
        "id": "U1234567",
        "startNAV": {
          "date": "20221230",
          "val": 2.027677613449E8
        },
        "baseCurrency": "USD"
      }
    ],
    "freq": "D",
    "dates": [
      "20230102",
          {...},
      "20231213"
    ]
  },
  "nd": 346,
  "cps": {
    "data": [
      {
        "idType": "acctid",
        "start": "20230102",
        "end": "20231213",
        "returns": [
          0,
          {...},
          0.0639
        ],
        "id": "U1234567",
        "baseCurrency": "USD"
      }
    ],
    "freq": "D",
    "dates": [
      "20230102",
          {...},
      "20231213"
    ]
  },
  "tpps": {
    "data": [
      {
        "idType": "acctid",
        "start": "20230102",
        "end": "20231213",
        "returns": [
          0.0037,
          0.0031,
          0.0033,
          0.0034,
          0.02,
          0.0127,
          0.0036,
          0.0036,
          0.0034,
          0.0012,
          0.0026,
          0.0017
        ],
        "id": "U1234567",
        "baseCurrency": "USD"
      }
    ],
    "freq": "M",
    "dates": [
      "202301",
      "202302",
      "202303",
      "202304",
      "202305",
      "202306",
      "202307",
      "202308",
      "202309",
      "202310",
      "202311",
      "202312"
    ]
  },
  "id": "getPerformanceData",
  "included": [
    "U1234567"
  ],
  "pm": "TWR"
}

 

Transaction History

Transaction history for a given number of conids and accounts.
Types of transactions include dividend payments, buy and sell transactions, transfers.

POST /pa/transactions

 

Request Object

Body Parameters

acctIds: Array of Strings. Required
Include each account ID to receive data for.

conids: Array of integers. Required
Include contract ID to receive data for.
Only supports one contract id at a time.

currency: String. Required
Define the currency to display price amounts with.
Defaults to USD.

days: String. Optional
Specify the number of days to receive transaction data for.
Defaults to 90 days of transaction history if unspecified.

request_url = f"{baseUrl}/pa/transactions"
json_content = {
  "acctIds": [
    "U1234567"
  ],
  "conids": [
    265598
  ],
  "currency": "USD",
  "days": 3
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/pa/transactions\
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "acctIds": [
    "U1234567"
  ],
  "conids": [
    265598
  ],
  "currency": "USD",
  "days": 3
}'

 

Response Object

rc: int.
(Client portal use only)

nd: int.
(Client portal use only)

rpnl: Object.
Rturns the object containing the realized pnl for the contract on the date.

data: Array of objects.
Returns an array of realized pnl objects.

date: String.
Specifies the date for the transaction.

cur: String.
Specifies the currency of the realized value.

fxRate: int.
Returns the foreign exchnage rate.

side: String.
Determines if the day was a loss or gain
Value format: “L”, “G”

acctid: String.
Returns the account ID the trade transacted on.

amt: String.
Returns the amount gained or lost on the day.

conid: String.
Returns the contract ID of the transaction.

amt: String.
Provides the total amount gained or lost from all days returned

currency: String.
Returns the currency the account is traded in.

from: int.
Returns the epoch time for the start of requests.

id: String.
Returns the request identifier, getTransactions.

to: int.
Returns the epoch time for the end of requests.

includesRealTime: bool.
Returns if the trades are up to date or not.

transactions: Array of objects.
Lists all supported transaction values.

date: String.
Reutrns the human-readable datetime of the transaction.
Value Format: “{Day of the week} {3-digit month} {day of the month} 00:00:00 {timezone} {year}”

cur: String.
Returns the currency of the traded insturment.

fxRate: int.
Returns the forex conversion rate.

pr: float.
Returns the price per share of the transaction.

qty: int.
Returns the total quantity traded.
Will display a negative value for sell orders, and a positive value for buy orders.

acctid: String.
Returns the account which made the transaction.

amt: float.
Returns the total value of the trade.

conid: int.
Returns the contract identifier.

type: String.
Returns the order side.

desc: String.
Returns the long name for the company.

{
  "rc": 0,
  "nd": 4,
  "rpnl": {
    "data": [
      {
        "date": "20231211",
        "cur": "USD",
        "fxRate": 1,
        "side": "L",
        "acctid": "U1234567",
        "amt": "12.2516",
        "conid": "265598"
      }
    ],
    "amt": "12.2516"
  },
  "currency": "USD",
  "from": 1702270800000,
  "id": "getTransactions",
  "to": 1702530000000,
  "includesRealTime": true,
  "transactions": [
    {
      "date": "Mon Dec 11 00:00:00 EST 2023",
      "cur": "USD",
      "fxRate": 1,
      "pr": 192.26,
      "qty": -5,
      "acctid": "U1234567",
      "amt": 961.3,
      "conid": 265598,
      "type": "Sell",
      "desc": "Apple Inc"
    }
  ]
}

 

Scanner

Iserver Scanner Parameters

Returns an xml file containing all available parameters to be sent for the Iserver scanner request.

GET /iserver/scanner/params

 

Request Object

No parameters or body content should be sent.

request_url = f"{baseUrl}/iserver/scanner/params"
requests.get(url=request_url) 

 

curl \
--url {{baseUrl}}/iserver/scanner/params \
--request GET

 

Response Object

scan_type_list: List Array of objects.
Contains all values used as the scanner “type” in the request.
[{
display_name: String.
Human readable name for the scanner “type”

code: String.
Value used for the market scanner request.

instruments: Array of Strings.
Returns all instruments the scanner type can be used with.
}]

instrument_list: Array of Objects.
Contains all values relevant to the scanner “instrument” request field.
[{
display_name: String.
Human readable representation of the instrument type.

type: String.
Value used for the market scanner request.

filters: Array of Strings.
Returns an array of all filters uniquely avaliable to that instrument type.
}]

filter_list: Array of Objects.
[{
group: String.
Returns the group of filters the request is affiliated with.

display_name: String.
Returns the human-readable identifier for the filter.

code: String.
Value used for the market scanner request.

type: String.
Returns the type of value to be used in the request.
This can indicate a range based value, or if it should be a single value.
}]

location_tree: Array of objects.
Contains all values relevant to the location field of the market scanner request.

display_name: String.
Returns the overarching instrument type to designate the location.

type: String.
Returns the code value of the market scanner instrument type value.

locations: Array of objects.
[{
display_name: String.
Returns the human-readable value of the market scanner’s location value.

type: String.
Returns the code value of the market scanner location value.

locations: Array.
Always returns an empty array at this depth.
}]

]

{
  "scan_type_list":[
    {
      "display_name": "display_name",
      "code": "code",
      "instruments": []
    }
  ],
  "instrument_list":[ 
    {
      "display_name": "display_name",
      "type": "type",
      "filters": []
    }
  ],
  "filter_list":[
    {
      "group": "group",
      "display_name": "display_name",
      "code": "code",
      "type": "type"
    }
  ],
  "location_tree":[
    {
      "display_name": "display_name",
      "type": "type",
      "locations": [
        {
          "display_name": "display_name",
          "type": "type",
          "locations": []
        }
      ]
    }
  ]
}

 

Iserver Market Scanner

Searches for contracts according to the filters specified in /iserver/scanner/params endpoint

Users can receive a maximum of 50 contracts from 1 request.

POST /iserver/scanner/run

 

Request Object

Body Parameters

instrument: String. Required
Instrument type as the target of the market scanner request.
Found in the “instrument_list” section of the /iserver/scanner/params response.

type: String. Required
Scanner value the market scanner is sorted by.
Based on the “scan_type_list” section of the /iserver/scanner/params response.

location: String. Required
Location value the market scanner is searching through.
Based on the “location_tree” section of the /iserver/scanner/params response.

filter: Array of objects.
Contains any additional filters that should apply to response.
[{
code: String.
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”.
}]

request_url = f"{baseUrl}/iserver/scanner/run"
json_content = {
  "instrument": "STK",
  "location": "STK.US.MAJOR",
  "type": "TOP_TRADE_COUNT",
  "filter": [
    {
      "code":"priceAbove",
      "value":5
    }
  ]
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl/iserver/scanner/run \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "instrument": "STK",
  "location": "STK.US.MAJOR",
  "type": "TOP_PERC_GAIN",
  "filter": [
    {
      "code":"priceAbove",
      "value":5
    }
  ]
}'

 

Response Object

contracts: Array of objects.
Contains contracts related to the market scanner request.
[{
server_id: String.
Contract’s index in relation to the market scanner type’s sorting priority.

column_name: String.
Always returned for the first contract.
Used for Client Portal (Internal use only)

symbol: String.
Returns the contract’s ticker symbol.

conidex: String.
Returns the contract ID of the contract.

con_id: int.
Returns the contract ID of the contract.

available_chart_periods: String.
Used for Client Portal (Internal use only)

company_name: String.
Returns the company long name.

contract_description_1: String.
For derivatives like Futures, the local symbol of the contract will be returned.

listing_exchange: String.
Returns the primary listing exchange of the contract.

sec_type: String.
Returns the security type of the contract.
}],

scan_data_column_name: String.
Used for Client Portal (Internal use only)

{
  "contracts": [
    {
      "server_id": "0",
      "symbol": "AMD",
      "conidex": "4391",
      "con_id": 4391,
      "available_chart_periods": "#R|1",
      "company_name": "ADVANCED MICRO DEVICES",
      "scan_data": "163.773K",
      "contract_description_1": "AMD",
      "listing_exchange": "NASDAQ.NMS",
      "sec_type": "STK"
    }
  ],
  "scan_data_column_name": "Trades"
}

 

HMDS Scanner Parameters

Query the parameter list for the HMDS market scanner

GET /hmds/scanner/params

 

Request Object

No parameters or body content should be sent.

request_url = f"{baseUrl}/hmds/scanner/params"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/hmds/scanner/params \
--request GET

 

Response Object

instrument_list: Array of objects.
Contains all instruments to be queried by the market scanner.
[{
display_name: String.
Returns the human readable string for the instrument.

type: String.
Returns the value to input in the instrument field of the market scanner request.

filters: Array of Strings.
Returns the available filters for the given instrument.
}]

scan_type_list: Array of objects.
Contains all scanner types to be queried by the market scanner.
[{
display_name: String.
Returns the human readable string for the scanCode.

code: String.
Returns the value to input in the scanCode field of the market scanner request.

instruments: Array of Strings.
Returns the compatible instruments for the given scanCode.
}]

location_tree: Array of objects.
Contains all locations to be queried by the market scanner.
[{
display_name: String.
Returns the human readable string for the location.

type: String.
Returns the value to input in the secType field of the market scanner request.

locations: Array of Strings.
Returns the compatible instruments for the given scanCode.
[{
display_name: String.
Returns the human readable string for the location.

locationCode: String.
Returns the value to be input to the locations field.

locations: Array of objects.
Returns an identical response, though for the sub-locations of the primary.
}]}]

{
  "instrument_list": [
    {
      "display_name": "display_name",
      "type": "type",
      "filters": []
    }
  ],
  "scan_type_list": [
    {
      "display_name": "display_name",
      "code": "code",
      "instruments": []
    }
  ],
  "location_tree": [
    {
      "display_name": "display_name",
      "type": "type",
      "locations": [
        {
          "display_name": "display_name",
          "locationCode": "locationCode",
          "locations": []
        }
      ]
    }
  ]
}

 

HMDS Market Scanner

Request a market scanner from our HMDS service.

Can return a maximum of 250 contracts.

POST /hmds/scanner/run

 

Request Object

Body Parameters

instrument: String. Required
Specify the type of instrument for the request.
Found under the “instrument_list” value of the /hmds/scanner/params request.

locations: String. Required
Specify the type of location for the request.
Found under the “location_tree” value of the /hmds/scanner/params request.

scanCode: String. Required
Specify the scanner type for the request.
Found under the “scan_type_list” value of the /hmds/scanner/params request.

secType: String. Required
Specify the type of security type for the request.
Found under the “location_tree” value of the /hmds/scanner/params request.

delayedLocations: null.
Internal use only.

maxItems: int.
Specify how many items should be returned.
Default and maximum set to 250.

filters: Array of object. Required*
Array of objects containing all filters upon the scanner request.
Content contains a series of key:value pairs.
While “filters” must be specified in the body, no content in the array needs to be passed.

request_url = f"{baseUrl}/hmds/scanner/run"
json_content= {
  "instrument":"BOND",
  "locations": "BOND.US",
  "scanCode": "HIGH_BOND_ASK_YIELD_ALL",
  "secType": "BOND",
  "delayedLocations":"SMART",
  "maxItems":25,
  "filters":[{
    "bondAskYieldBelow": 15.819
  }]
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/hmds/scanner/run \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "instrument":"BOND",
  "locations": "BOND.US",
  "scanCode": "HIGH_BOND_ASK_YIELD_ALL",
  "secType": "BOND",
  "delayedLocations":"SMART",
  "maxItems":25,
  "filters":[{
    "bondAskYieldBelow": 15.819
  }]
}'

 

Response Object

contracts: Array of objects.
Contains all contracts in order from the scanner response.
[{
inScanTime: String.
Returns the time at which the contract was scanned.
Always returned in UTC time as a string.

contractID: String.
Returns the contract identifier of the scanned contract.

con_id: String.
Returns the contract identifier of the scanned contract.
}]

{
  "total": "17262",
  "size": "250",
  "offset": "0",
  "scanTime": "20231214-18:55:25",
  "id": "scanner1",
  "position": "v1:AAAAAQABG3gAAAAAAAAA+g==",
  "Contracts": {
    "Contract": [
      {
        "inScanTime": "20231214-18:55:25",
        "contractID": "431424315"
      },
  ]
}

 

Session

Requests used to designate changes to the web session itself rather than endpoints relating to trades or account data directly.

Authentication Status

Current Authentication status to the Brokerage system. Market Data and Trading is not possible if not authenticated, e.g. authenticated shows false

POST /iserver/auth/status

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/iserver/auth/status"
json_content = {}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/auth/status \
--request POST \
--header 'Content-Type:application/json' \
--data '{}'

 

Response Object

authenticated: bool.
Returns whether your brokerage session is authenticated or not.

competing: bool.
Returns whether you have a competing brokerage session in another connection.

connected: bool.
Returns whether you are connected to the gateway, authenticated or not.

message: String.
If there is a message about your authenticate status, it will be returned here.
Authenticated sessions return an empty string.

MAC: String.
IBKR MAC information. Internal use only.

serverInfo: Object.

serverName: String.
IBKR server information. Internal use only.

serverVersion: String.
IBKR version information. Internal use only.

fail: String.
Returns the reason for failing to retrieve authentication status.

{
  "authenticated": true,
  "competing": false,
  "connected": true,
  "message": "",
  "MAC": "12:B:B3:23:BF:A0",
  "serverInfo": {
    "serverName": "JifN19053",
    "serverVersion": "Build 10.25.0p, Dec 5, 2023 5:48:12 PM"
  },
  "fail": ""
}

 

Alternate Response Object

Users that have been timed out or logged out of their session will result in a “false” authentication status, indicating the user is not maintaining a brokerage session.

{
  "authenticated": false,
  "competing": false,
  "connected": false,
  "MAC": "98:B2:C3:45:DE:F6"
}

 

Initialize Brokerage Session

After 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,

POST /iserver/auth/ssodh/init

 

Request Object

Body Params

publish: Boolean. Required
Determines if the request should be sent immediately.
Users should always pass true. Otherwise, a ‘500’ response will be returned.

compete: Boolean. Required
Determines if other brokerage sessions should be disconnected to prioritize this connection.

request_url = "{baseUrl}/iserver/auth/ssodh/init"
json_content= {"publish":True,"compete":True}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/auth/ssodh/init \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "publish":true,
  "compete":true
}'

 

Response Object

authenticated: bool.
Returns whether your brokerage session is authenticated or not.

competing: bool.
Returns whether you have a competing brokerage session in another connection.

connected: bool.
Returns whether you are connected to the gateway, authenticated or not.

message: String.
If there is a message about your authenticate status, it will be returned here.
Authenticated sessions return an empty string.

MAC: String.
IBKR MAC information. Internal use only.

serverInfo: Object.

serverName: String.
IBKR server information. Internal use only.

serverVersion: String.
IBKR version information. Internal use only.

{
  "authenticated": true,
  "competing": false,
  "connected": true,
  "message": "",
  "MAC": "98:F2:B3:23:BF:A0",
  "serverInfo": {
    "serverName": "JifN19053",
    "serverVersion": "Build 10.25.0p, Dec 5, 2023 5:48:12 PM"
  }
}

 

Logout of the current session

Logs the user out of the gateway session. Any further activity requires re-authentication.

 

POST /logout

 

Request Object

No params or body content should be sent.

request_url = "{baseUrl}/logout"
json_content= {}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/logout \
--request POST \
--header 'Content-Type:application/json' \
--data '{}'

 

Response Object

status: bool.
Returns true if the session was ended.

{
  "status":true
}

 

Ping the server

If 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.

POST /tickle

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/tickle"
json_content = {}
requests.post(url=request_url, json=json_content)

 

curl \ 
--url {{baseUrl}}/tickle \
--request POST \
--header 'Content-Type:application/json' \
--data '{}'

 

Response Object

session: String.
Returns the session identifier of your connection.
Can be used for the cookie parameter of your request.

ssoExpires: int.
Displays the time until session expiry in milliseconds.

collission: bool.
Internal use only.

userId: int.
Internal use only.

hmds: object.
Returns any potential historical data-specific information.
“No bridge” indicates historical data is not being currently requested.

iserver: object.
Returns the content of the
/iserver/auth/status endpoint.

{
  "session": "bb665d0f55b6289d70bc7380089fc96f",
  "ssoExpires": 460311,
  "collission": false,
  "userId": 123456789,
  "hmds": {
    "error": "no bridge"
  },
  "iserver": {
    "authStatus": {
      "authenticated": true,
      "competing": false,
      "connected": true,
      "message": "",
      "MAC": "98:F2:B3:23:BF:A0",
      "serverInfo": {
        "serverName": "JifN19053",
        "serverVersion": "Build 10.25.0p, Dec 5, 2023 5:48:12 PM"
      }
    }
  }
}

 

Re-authenticate the Brokerage Session (Deprecated)

When 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.

POST /iserver/reauthenticate

 

Request Object

No params or body content should be sent.

request_url = f"{baseUrl}/iserver/reauthenticate"
json_content = {}
requests.post(url=request_url, json=json_content )

 

curl \
--url {{baseUrl}}/iserver/reauthenticate \ 
--request POST \ 
--header 'Content-Type:application/json' \ 
--data '{}'

 

Response Object

message: String.
Returns “triggered” to indicate the response was sent.

{
  "message": "triggered"
}

 

Validate SSO

Validates the current session for the SSO user

GET /sso/validate

 

Request Object:

No additional parameters necessary.

request_url = f"{baseUrl}/sso/validate"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/sso/validate \
--request GET

 

Response Object:

USER_ID: int.
Internal user identifier.

USER_NAME: String.
current username logged in for the session.

RESULT: bool.
Confirms if validation was successful.
true if session was validated; false if not.

AUTH_TIME: int.
Returns the time of authentication in epoch time.

SF_ENABLED: bool.
Internal use only.

IS_FREE_TRIAL: bool.
Returns if the account is a trial account or a funded account.

CREDENTIAL: String.
Returns the underlying username of the account.

IP: String.
Internal use only.
Does not reflect the IP address of the user.

EXPIRES: int.
Returns the time until expiration in milliseconds.

QUALIFIED_FOR_MOBILE_AUTH: bool.
Returns if the customer requires two factor authentication.

LANDING_APP: String.
Used for Client Portal (Internal use only)

IS_MASTER: bool.
Returns whether the account is a master account (true) or subaccount (false).

lastAccessed: int.
Returns the last time the user was accessed in epoch time.

loginType: int.
Returns the login type.
1 for Live, 2 for Paper

PAPER_USER_NAME: Returns the paper username for the account.

features: object.
Returns supported features such as bonds and option trading.

{
  "USER_ID": 123456789,
  "USER_NAME": "user1234",
  "RESULT": true,
  "AUTH_TIME": 1702580846836,
  "SF_ENABLED": false,
  "IS_FREE_TRIAL": false,
  "CREDENTIAL": "user1234",
  "IP": "12.345.678.901",
  "EXPIRES": 415890,
  "QUALIFIED_FOR_MOBILE_AUTH": null,
  "LANDING_APP": "UNIVERSAL",
  "IS_MASTER": false,
  "lastAccessed": 1702581069652,
  "LOGIN_TYPE": 2,
  "PAPER_USER_NAME": "user1234",
  "features": {
    "env": "PROD",
    "wlms": true,
    "realtime": true,
    "bond": true,
    "optionChains": true,
    "calendar": true,
    "newMf": true
  },
  "region": "NJ"
}

Watchlists

Manage watchlists that are used in both Trader Workstation and Client Portal.

Can also be used to maintain lists within the Client Portal API.

Create a Watchlist

Create a watchlist to monitor a series of contracts.

POST /iserver/watchlist

 

Request Object

Body Params

id: String. Required
Supply a unique identifier to track a given watchlist. Must supply a number.

name: String. Required
Supply the human readable name of a given watchlist. Displayed in TWS and Client Portal.

rows: Array of Objects. Required
[{
C: int.
Provide the conid, or contract identifier, of the conid to add.

H: Empty String.
Can be used to add a blank row between contracts in the watchlist.
}]

request_url = f"{baseUrl}/iserver/watchlist"
json_content = {
  "id":"1234",
  "name":"Test Watchlist",
  "rows":[
    {"C":8314},
    {"C":8894}
  ]
}
requests.post(url=request_url, json=json_content)

 

curl \
--url {{baseUrl}}/iserver/watchlist \
--request POST \
--header 'Content-Type:application/json' \
--data '{
  "id":"1234",
  "name":"Test Watchlist",
  "rows":[
    {"C":8314},
    {"C":8894}
  ]
}'

 

Response Object

id: String.
Returns the id value used to create the watchlist.

hash: String.
Returns the internal IB hash value of the order.

name: String.
Returns the human-readable name of the watchlist.

readOnly: bool.
Determines if the watchlist is marked as write-restricted.

instruments: Empty Array.
Always returns an empty array.
Conids supplied will still be in the final watchlist.
See the /iserver/watchlist?id endpoint for more details.

{
  "id": "1234",
  "hash": "1702581306241",
  "name": "Test Watchlist",
  "readOnly": false,
  "instruments": []
}

 

Get All Watchlists

Retrieve a list of all available watchlists for the account.

GET /iserver/watchlists

 

Request Object:

Body Params

SC: String.
Specify the scope of the request.
Valid Values: USER_WATCHLIST

request_url = f"{baseUrl}/iserver/watchlist?SC=USER_WATCHLIST"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/watchlists?SC=USER_WATCHLIST \
--request GET

 

Response Object

data: Object.
Contains all of the data about the watchlist.
{
scanners_only: bool.
Shows if the system is only displaying scanners.

system_lists: Array of Objects.
Returns all IB-created watchlists.
[{
is_open: bool.
Internal use only.

read_only: bool.
Returns if the watchlist can be edited or not.

name: String.
Returns the human-readable name of the watchlist.

id: String.
Returns the code identifier of the watchlist.

type: String.
Returns the watchlist type.
Always returns “watchlist”.
}],

show_scanners: bool.
Returns if scanners are shown.

bulk_delete: bool.
Displays if the watchlists should be deleted.

user_lists: Array of Objects.
Returns all of the available user-created lists.
[{
is_open: bool.
Internal use only.

read_only: bool.
Returns if the watchlist can be edited or not.

name: String.
Returns the human-readable name of the watchlist.

id: String.
Returns the code identifier of the watchlist.

type: String.
Returns the watchlist type.
Always returns “watchlist”.
}]
},

action: String.
Internal use only.
Returns “content”.

MID: String.
Returns the number of times the endpoint was requested this session.
}

{
  "data": {
    "scanners_only": false,
    "show_scanners": false,
    "bulk_delete": false,
    "user_lists": [
      {
        "is_open": false,
        "read_only": false,
        "name": "Test Watchlist",
        "modified": 1702581306241,
        "id": "1234",
        "type": "watchlist"
      }
    ]
  },
  "action": "content",
  "MID": "1"
}

 

Get Watchlist Information

Request the contracts listed in a particular watchlist.

GET /iserver/watchlist

 

Request Object

Query Params

id: String. Required
Set equal to the watchlist ID you would like data for.

request_url = f"{baseUrl}/iserver/watchlist?id=1234"
requests.get(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/watchlist?id=1234 \
--request GET

 

Response Object

The first request may only return the values C, conid, and name values. Subsequent requests will add additional contract information.

id: String.

hash: String.

name: String.

readOnly: bool.

instruments: Array of Objects.
[{
C: String.
Returns the contract ID.

conid: int.
Returns the contract ID.

name: String.
Returns the long name of the company.

fullName: String.
Returns the local symbol of the contract.

assetClass: String.
Returns the security type of the contract.

ticker: String.
Returns the ticker symbol for the contract.

chineseName: String.
Returns the Chinese character name for the contract.
}]

{
  "id": "1234",
  "hash": "1702581306241",
  "name": "Test Watchlist",
  "readOnly": false,
  "instruments": [
    {
      "ST": "STK",
      "C": "8314",
      "conid": 8314,
      "name": "INTL BUSINESS MACHINES CORP",
      "fullName": "IBM",
      "assetClass": "STK",
      "ticker": "IBM",
      "chineseName": "国际商业机器"
    },
    {
      "ST": "STK",
      "C": "8894",
      "conid": 8894,
      "name": "COCA-COLA CO/THE",
      "fullName": "KO",
      "assetClass": "STK",
      "ticker": "KO",
      "chineseName": "可口可乐"
    }
  ]
}

 

Delete a Watchlist

Permanently delete a specific watchlist for all platforms.

DELETE /iserver/watchlist

 

Request Object

id: String. Required
Include the watchlist ID you wish to delete.

request_url = f"{baseUrl}/iserver/watchlist?id=1234"
requests.delete(url=request_url)

 

curl \
--url {{baseUrl}}/iserver/watchlist?id=1234 \
--request DELETE

 

Response Object

Data: Object.
Returns the data about the deleted watchlist.

deleted: String.
Returns the ID for the deleted watchlist.

action: String.
Always returns “context”.

MID: String.
Returns the id for the number of times /iserver/watchlist was called this session.

{
  "data": {
    "deleted": "1234"
  },
  "action": "context",
  "MID": "2"
}

 

Websockets

Websocket topics expose the same underlying data as is delivered by the HTTP endpoints. Functionality that requires a brokerage session (that is, all features behind /iserver URIs) will also require a brokerage session when accessed via websocket. Please ensure you have an active brokerage session before attempting to use these features of the websocket. For information on getting started with Client Portal API, please refer to the Authentication section.

Websocket topics requiring a brokerage session: smd (live market data), smh (historical market data), sbd (live price ladder data), sor (order updates), str (trades), act (unsolicited account property info), sts (unsolicited brokerage session authentication status), blt (unsolicited bulletins), ntf (unsolicited notifications)

Websocket topics that do not require a brokerage session: spl (profit & loss updates), ssd (account summary updates), sld (account ledger updates), system (unsolicited connection-related messages).

The url for websockets is: wss://localhost:5000/v1/api/ws

Connection Guide

If you require brokerage functionality, you will need to establish a brokerage session prior to opening a websocket, just as is required before making requests to /iserver endpoints. Please see Authentication for more details.

First make request the /tickle endpoint and save the returned session value.

{
    "session": "d21b8cf5ebc8ea01c6ce37c8125ec83f",
    "ssoExpires": ssoExpires,
    "collission": collission,
    "userId": userId,
    "hmds": {
        "error": "no bridge"
    },
    "iserver": {
        "authStatus": {
            "authenticated": true,
            "competing": false,
            "connected": true,
            "message": "",
            "MAC": "MAC",
            "serverInfo": {
                "serverName": "serverName",
                "serverVersion": "serverVersion"
            }
        }
    }
}

 

We are then specifically interested in the “session” value in the response as we can pass this to our websocket for confirming our sessionId.

sessionToken = '{"session":"d21b8cf5ebc8ea01c6ce37c8125ec83f"}'

 

Next, you will need to build your websocket to wss://localhost:5000/v1/api/ws. In your request to establish the websocket, be sure to set your cookie header as “api={‘session’ value here}”

ws = websocket.WebSocketApp(
  url="wss://localhost:5000/v1/api/ws",
  on_open=on_open,
  on_message=on_message,
  on_error=on_error,
  on_close=on_close,
  cookie=f"api={sessionToken}"
)
ws.run_forever()

 

curl -i -k -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "origin: interactivebrokers.github.io" --cookie "api=d21b8cf5ebc8ea01c6ce37c8125ec83f" wss://localhost:5000/v1/api/ws

 

After establishing your session, you may send whichever topics are needed through the newly established websocket. 

on_open(ws):
    print("Opened Connection")
    time.sleep(3)
    ws.send('smd+265598+{"fields":["31","84","86"]}')

 

Please note that while the websocket session itself supports the ability to establish a websocket, cURL is unable to send future topic requests. This would need to be facilitated by either a third party terminal add-on, or a programming language such as Python, Java, or otherwise.

Solicited and Unsolicited Messages

There are two types of messages sent to clients via the websocket:

  • Solicited messages: Messages delivered to the client in response to an explicit, client-initiated subscription to a topic.
  • Unsolicited messages: Messages delivered automatically to the client by the server. These messages are not associated with a topic subscription that can be canceled, and they typically contain session or other administrative information.

Subscribing to Websocket Topics

Most data available via the websocket is delivered as a stream of messages in response to an explicit subscription to a topic. Such subscription messages are solicited, because the client must first ask to be subscribed to the relevant topic before messages will be sent by the server. To subscribe to a topic, a message is sent to the websocket in the following format:

TOPIC+[TOPIC_TARGET]+{PARAMETERS}

where:

  • TOPIC is the identifier of the topic (the type of data) to be subscribed.
  • The plus symbol + is used as a separator of the message elements.
  • TOPIC_TARGET identifies a specific resource, typically an account or instrument, as the subject of the subscription. Certain topics do not use a target.
  • {PARAMETERS} is a JSON-formatted string that describes filters or other modifiers to the topic subscription. If no parameters are available for the topic, or none are desired for your subscription, this is sent as an empty {} object.

Solicited message topics are generally three characters in length. A message sent to subscribe, as well as the messages received in response for the duration of the subscription, will use a topic starting with s (“subscribe”). The second two characters identify the particular datafeed in question, as in topic ssd, indicating “subscribe” + “account summary”.

When canceling a subscription (unsubscribing), a message is sent using a topic starting with u (“unsubscribe”), followed by the two-character identifier of the datafeed whose subscription will be terminated, as in topic usd, indicating “unsubscribe” + “account summary”. A single response message will be delivered with the same unsubscribe topic, confirming unsubscription.

Account Operations

Subscribe Account Summary

Subscribe to Account Summary Topic

Topic:

ssd
Subscribes to a stream of account summary messages for the specified account.

Topic Target:

accountId: Required.
Must pass the account ID whose account summary data will be subscribed.

Parameters:

{
keys: Array of Strings.
Pass specific account summary data keys to receive messages concerning only those keys. Passing no named keys when opening the subscription will deliver account summary messages containing values for the selected account.
Example Values: “AccruedCash-S”, “ExcessLiquidity-S”

fields: Array of Strings.
Pass specific account summary field names to filter responses to include only these fields for the requested keys. Passing no named fields when opening the subscription will deliver all available data points for the specified account summary keys.
Example Values: “currency”, “monetaryValue”
}

ssd+DU1234567+{
    "keys":["AccruedCash-S","ExcessLiquidity-S"],
    "fields":["currency","monetaryValue"]
}

 

Account Summary Topic Messages

{
result: Array of JSON objects, each corresponding to an account summary value for the account.
  [
    {
key: String.
The name of the account summary value.
This is always returned.

timestamp: Number (integer only).
The timestamp reflecting when the value was retrieved.
This is always returned.

value: String.
A non-monetary value associated with the key. This may include dates, account titles, or other relevant information.

monetaryValue: Number.
A monetary value associated with the key. Returned when the key pertains to pricing or balance details.

currency: String.
The currency reflected by monetaryValue.
Example Value: “USD”, “EUR”, “HKD”

severity: Number (integer only).
Internal use only.
    },
    …
  ]
}

{"result":[
    {
     "key":"key1",
     "currency":"currency", 
     "monetaryValue":monetaryValue, 
     "severity":0, 
     "timestamp":timestamp
    },
    {
     "key":"key2",
     "currency":"currency", 
     "value":value, 
     "severity":0, 
     "timestamp":timestamp
    },
]}

 

Unsubscribe Account Summary

Unsubscribe from Account Summary Topic

Topic:

usd
Unsubscribes the user from account summary information for the specified account.

Topic Target:

accountId: Required.
Must pass the account ID whose account summary messages will be unsubscribed.

Parameters:

none

usd+DU1234567+{}

 

Account Summary Unsubscribe Message

Arrives once.

{
result: String.
Confirms successful unsubscription.
}

{"result":"unsubscribed from summary"}

 

Subscribe Account Ledger

Subscribe to Account Ledger Topic

Topic:

sld
Subscribes to a stream of account ledger messages for the specified account, with contents sorted by currency.

Topic Target:

accountId: Required.
Must pass the account ID whose ledger data will be subscribed.

Parameters:

{
keys: Array of Strings.
Pass specific ledger currency keys to receive messages with data only for those currencies. Passing no named keys when opening the subscription will deliver ledger messages containing values for all currencies in the selected account.
Example Values: “LedgerListEUR”, “LedgerListUSD”, “LedgerListBASE” (for the account’s base currency)

fields: Array of Strings.
Pass specific ledger field names to receive messages only those data points for the currencies specified in the keys argument. Passing no named fields when opening the subscription will deliver all available data points for the specified currencies.
Example Values: “cashBalance”, “exchangeRate”
}

sld+DU1234567+{
    "keys":["LedgerListBASE","LedgerListEUR"],
    "fields":["cashBalance","exchangeRate"]
}

Account Ledger Topic Messages

A new message is published every 10 seconds until the sld topic is unsubscribed. A given message will only deliver a currency’s field data when a change occurred for that currency in the preceding interval. If no change occurred, the currency’s entry in the sld message will be “blank”, containing only the currency key and a timestamp.
Note that all currency values of JSON number type will be presented with a fractional component following a decimal point, and may also include an exponential component following an E if sufficiently large.

{
result: Array of JSON objects, with each object containing the set of key-value pairs for one currency in the account.
  [
    {
key: String.
Currency identifier string in the form “LedgerListXXX”, where XXX is the three-character currency code of a currency in the requested account, or “LedgerListBASE”, corresponding to the account’s base currency.
This is always returned.

timestamp: Number (integer only).
The timestamp reflecting when the currency’s set of values was retrieved.
This is always returned.

acctCode: String.
The account containing the currency position described by the accompanying data.

cashbalance: Number.
cashBalanceFXSegment: Number.
commodityMarketValue: Number.
corporateBondsMarketValue: Number.
dividends: Number.
exchangeRate: Number.
funds: Number.
marketValue: Number.
optionMarketValue: Number.
interest: Number.
issueOptionsMarketValue: Number.
moneyFunds: Number.
netLiquidationValue: Number.
realizedPnl: Number.
unrealizedPnl: Number.
secondKey: String.
settledCash: Number.
stockMarketValue: Number.
tBillsMarketValue: Number.
tBondsMarketValue: Number.
warrantsMarketValue: Number.

severity: Number (integer only).
Internal use only.
    },
    …
  ]
}

{
  "result": [
    {
      "acctCode": "DU1234567",
      "cashbalance": 2.0201311791131118E8,
      "cashBalanceFXSegment": 0.0,
      "commodityMarketValue": 0.0,
      "corporateBondsMarketValue": 0.0,
      "key": "LedgerListBASE",
      "dividends": 0.0,
      "exchangeRate": 1.0,
      "funds": 0.0,
      "marketValue": 0.0,
      "optionMarketValue": 0.0,
      "interest": 396687.69214935537,
      "issueOptionsMarketValue": 0.0,
      "moneyFunds": 0.0,
      "netLiquidationValue": 2.0280151634374067E8,
      "realizedPnl": 0.0,
      "unrealizedPnl": 249013.5397937378,
      "secondKey": "BASE",
      "settledCash": 2.0201311791131118E8,
      "severity": 0,
      "stockMarketValue": 391710.74028015137,
      "tBillsMarketValue": 0.0,
      "tBondsMarketValue": 0.0,
      "warrantsMarketValue": 0.0,
      "timestamp": 1700248325
    },
    {
      "key": "LedgerListCAD",
      "timestamp": 1700248325
    },
    {
      "key": "LedgerListUSD",
      "timestamp": 1700248325
    },
    {
      "key": "LedgerListEUR",
      "timestamp": 1700248325
    },
    {
      "key": "LedgerListCHF",
      "timestamp": 1700248325
    }
  ],
  "topic": "sld+DU1234567"
}

Unsubscribe Account Ledger

Unsubscribe from Account Ledger Topic

Topic:

uld
Unsubscribes from account ledger messages for the specified account.

Topic Target:

accountId: Required.
Must pass the account ID whose ledger messages will be unsubscribed.

Parameters:

none

uld+DU1234567+{}

Account Ledger Unsubscribe Message

Arrives once.

{
result: String.
Confirms successful unsubscription.
}

{"result":"unsubscribed from ledger"}

Market Data

Market Data Request

Market Data Request

Topic:

smd
Subscribes the user to watchlist market data.
Streaming, top-of-the-book, level one, market data is available for all instruments using Client Portal API’s websocket endpoint.

NOTE: The maximum number of market data subscriptions is based on your account’s Market Data Lines.

Topic Target:

conid: Required.
Must pass a single contract identifier.
Contracts requested use SMART routing by default. To specify the exchange, the contract identifier should be modified to: conId@EXCHANGE, where EXCHANGE is the requested data source.
Combos or Spreads market data can be retrieved using identical formatting to Combo or Spread Orders. The only difference is that a spread_conid of 0 must be passed.

Arguments:

fields: Array of Strings. Optional.
Pass an array of field IDs. Each ID should be passed as a string.
You can find a list of fields in the Market Data Fields section.

smd+conId+{
    [
    "fields":"field_1",
    "field_2",
    "field_n", 
    "field_n+1"
    ]
}

Market Data Response

server_id: String.
Returns the request’s identifier.

conidEx: String.
Returns the passed conid field. May include exchange if specified in request.

conid: int.
Returns the contract id of the request

_updated: int*.
Returns the epoch time of the update in a 13 character integer .

6119: String.
Field value of the server_id. Returns the request’s identifier.

fields*: String.
Returns a response for each request. Some fields not be as readily available as others. See the Market Data section for more details.

6509: String.
Returns a multi-character value representing the Market Data Availability.

topic: String.
Restates the requesting topic.

{
    "server_id":"server_id",
    "conidEx":"conidEx",
    "conid":conid,"
    _updated":_updated,
    "6119":"serverId",
    "field_1":field_1,
    "field_2":field_2,
    "field_n":field_n, 
    "field_n+1":field_n+1,
    "6509":"RB",
    "topic":"smd+conid"
}


 

Cancel Market Data

Market Data Unsubscribe Request

Topic:

umd
Unubscribes the user from watchlist market data.

Topic Target:

conids: Required.
Must pass a single contract identifier.

Arguments:

null.

umd+conId+{}

 

Market Data Unsubscribe Response

No response is returned upon unsubscribing from market data. There will just be an end to the market data from the given conid.

Historical Market Data Request

For streaming historical data, the topic smh+Id is used. There are also optional parameters available in JSON format. If no parameters are specified, the empty parameters array {} can be passed. Incorrectly specified parameters are ignored and the default (empty) response is returned.

NOTE: Only a max of 5 concurrent historical data request available at a time.

NOTE: Historical data will only respond once, though customers will still need to unsubscribe from the endpoint.

Historical Data Request

Topic:

smh
Subscribes the user to historical bar data.
Streaming, top-of-the-book, level one, historical data is available for all instruments using Client Portal API’s websocket endpoint.

Topic Target:

conids: Required.
Must pass a single contract identifier.
Contracts requested use SMART routing by default. To specify the exchange, the contract identifier should be modified to: conId@EXCHANGE, where EXCHANGE is the requested data source.

Arguments:

exchange: String.
Requested exchange to receive data.

period: String.
Total duration for which bars will be requested.

bar: String.
Interval of time to receive data.

outsideRth: Bool.
Determines if you want data outside regular trading hours (true) or only during market hours (false).

source: String.
The value determining what type of data to show.

format: String.
The format in which bars are returned.
 

smh+conid+{
    "exchange":"exchange",
    "period":"period",
    "bar":"bar",
    "outsideRth":outsideRth,
    "source":"source",
    "format":"format"
}

 

Historical Data Response

serverId: String.
Request identifier for the specific historical data request. Used for cancelling the data stream.

symbol: String.
Returns the symbol for the requested conid.

text: String.
Company long name.

priceFactor: int.
Price mutlipler (based on $0.01)

startTime: String.
Returns the starting time (in epoch time) of the response.

high: String.
Returns the highest “high value/Volume value/Outside RTH volume” of the period.

low: String.
Returns the lowest “Low value/Volume value/Outside RTH volume” of the period.

timePeriod: String.
Returns the period covered by the request.

barLength: int.
Returns the string length of the bar response.

mdAvailability: String.
Internal IBKR message.

mktDataDelay: int.
Returns if there is any delay in the market data.

outsideRth: Bool.
Returns if the data contains information outside regular trading hours.

volumeFactor: int.
Determines if the volume is returned as lots, multipliers, or as-is.

priceDisplayRule: int.
Internal IBKR message.

priceDisplayValue: String.
Internal IBKR message.

negativeCapable: Bool.
Returns contract rule whether the contract supports negative values or not.

messageVersion: int.
Internal IBKR message.

data: Array of Objects.
Returns all bars related that fall within the period.

o: float.
Opening value for the bar’s duration.

c: float.
Closing value for the bar’s duration.

l: float.
Lowest value for the bar’s duration.

h: float.
Highest value for the bar’s duration.

v: int.
Total volume of the bar.

t: int.
Epoch time of the bar return.

points: int.
Displays the total number of bars returned within ‘data’.

topic: String.
Represents the request sent.

{
    "serverId": "serverId",
    "symbol": "symbol",
    "text": "text",
    "priceFactor": priceFactor,
    "startTime": "startTime",
    "high": "high",
    "low": "low",
    "timePeriod": "timePeriod",
    "barLength": barLength,
    "mdAvailability": "mdAvailability",
    "mktDataDelay": mktDataDelay,
    "outsideRth": outsideRth,
    "volumeFactor": volumeFactor,
    "priceDisplayRule": priceDisplayRule,
    "priceDisplayValue": "priceDisplayValue",
    "negativeCapable": negativeCapable,
    "messageVersion": messageVersion,
    "data": [data],
    "points": points, 
    "topic": "topic",
}

 

The historical market data request takes the following parameters:

Parameter Description Valid Values
exchange: String Contract exchange Valid exchange on which the contract trades
period: String Request duration
  • {1-30}min
  • {1-8}h
  • {1-1000}d
  • {1-792}w
  • {1-182}m
  • {1-15}y
bar: String Request bar size
  • 1min
  • 2min
  • 3min
  • 5min
  • 10min
  • 15min
  • 30min
  • 1h
  • 2h
  • 3h
  • 4h
  • 8h
  • 1d
  • 1w
  • 1m
outsideRTH: Boolean Request data outside trading hours true/false
source: String Type of date requested
  • midpoint
  • trades
  • bid_ask
  • bid
  • ask
format: String Historical values returned
  • %o – open
  • %c – close
  • %h – high
  • %l – low
  • %v – volume

Cancel Historical Market Data

Cancel Historical Data Request

Topic:

umh
Unubscribes the user from historical bar data.

Arguments:

serverId: String. Required

serverId is passe initially from the historical data request.

umh+{serverId}

 

Historical Data Unsubscribe Response

No response is returned upon unsubscribing from historical data. There will just be an end to the historical data stream for the given serverId and one of the five subscriptions will be available again.

Subscribe to BookTrader Price Ladder

Price Ladder Request

Topic:

sbd
Subscribes the user to BookTrader price ladder data.
Streaming BookTrader data requires users to maintain a L2, Depth of Book, market data subscription. See the Market Data Subscriptions page for more details.

Topic Target:

acctId: Required.
Must pass a single AccountId.

conids: Required.
Must pass a single contract identifier.

exchange: Optional.
Must pass a single contract identifier.
If no exchange is specified, all available deep exchanges are assumed.

Arguments:

Do not pass arguments

 

sbd+acctId+conid+exchange

 

Price Ladder Response

topic: String.
Returns the request’s topic string.

data: Array of Objects.
Returns an array of objects to indicate ladder depth.

row: int.
Returns the row identifier of the ladder data.

focus: int.
Indicates if the value was marked as the last price for the contract.

price: String.
Returns the Last, or last executed trade, price.
In some instances, price and size will be returned in the structure ‘”price”:”size @ price”‘.

ask: String.
Returns the corresponding ask size.

bid: String.
Returns the corresponding bid size.

 

{
  "topic":"sbd+acctId+conid",
  "data":[
    {"row":0,"focus":0,"price":"price"},
    {"row":1,"focus":0,"price":"size @ price"},
    {"row":n,"focus":0,"price":"price", "bid":"bid"},
    {"row":n+1,"focus":0,"price":"price", "ask":"ask"},
    {"row":n+1,"focus":0,"price":"size @ price", "ask":"ask"}
  ]
}

 

Cancel Price Ladder Subscription

Cancel Price Ladder Request

Topic:

ubd
Unsubscribes the user from price ladder data.

Arguments:

acctId: Required.
Must pass the account ID of the account that made the request.

 

 

ubd+{acctId}

 

Price Ladder Unsubscribe Response

No response is returned upon unsubscribing from the price ladder. There will just be an end to the data stream for the given acctId and the user may subscribe to a new price ladder source.

Miscellaneous Operations

Ping Session

Websocket Ping request

Topic:

tic
Ping the websocket in order to keep the websocket session alive.
To maintain a session for accessing /iserver or /ccp endpoints, use the topic tic. It is advised to ping the session at least once per minute.

Note: It is still required to send a request to the /tickle endpoint every few minutes or when the session expires (/sso/validate is returning a 0).

Do not pass arguments

 

 

 

 

tic

 

Order & Position Operations

Request Live Order Updates

As long as an order is active, it is possible to retrieve it using Client Portal API. Live streaming orders can be requested by subscribing to the sor topic. Once live orders are requested we will start to relay back when there is an update. To receive all orders for the current day the endpoint /iserver/account/orders can be used. It is advised to query all orders for the current day first before subscribing to live orders.

Order Updates Request

Topic:

sor
Subscribes the user to live order updates.

Arguments:

Do not pass arguments

 

 

 

sor+{}

 

Order Updates Response

topic: String.

args: Array of Objects.

acct: String.
Returns the account Id of which account made the request.

conid: int.
Contract Identifier for the given order.

orderId: int.
Order identfier affiliated with the given order.

cashCcy: String.
Base currency used for the transaction.

sizeAndFills: String.
Total quantity filled in the order.

orderDesc: String.
Order description of the given order.
Describes the side, size, orderType, price, and tif of the orer.

description1: String.
Ticker symbol of the request.

ticker: String.
Ticker symbol of the request.

secType: String.
Security type of the request.

listingExchange: String.
Primary exchange where the contract is held.

remainingQuantity: float.
Percentage of the order quantity remaining.

filledQuantity: float.
Percentage of the ordr quantity filled.

companyName: String.
Longname of the contract’s company.

status: String.
Current order status.
Value Format: Presubmitted, Submitted, Filled, Cancelled.

origOrderType: String.
Returns the original order type of the given order.

supportsTaxOpt: String.
Determines if the order supports Tax Optimizer.

lastExecutionTime: String.
Returns the datetime object of the most recent execution.

lastExecutionTime_r: int.
Returns the epoch timestamp of the most recent execution.

orderType: String.
Returns the current order type of the order.
Value Format: MARKET, LIMIT, STOP

side: String.
Returns the side of the trade.
Value Format: BUY, SELL

timeInForce: String.
Returns the time in force for the given order.

price: int.
Provides the limit or stop price for the submitted order.

bgColor: String.
Background color. Used for Client Portal only.

fgColor: String.
Foreground color. Used for Client Portal only.

{
    "topic": "sor" ,
    "args": [
        {
            "acct": "acct",
            "conid": conid,
            "orderId": orderId,
            "cashCcy": "cashCcy",
            "sizeAndFills": "sizeAndFills",
            "orderDesc": "orderDesc",
            "description1": "description1",
            "ticker": "ticker",
            "secType": "secType",
            "listingExchange": "listingExchange",
            "remainingQuantity": remainingQuantity,
            "filledQuantity": filledQuantity,
            "companyName": "companyName",
            "status": "status",
            "origOrderType": "origOrderType",
            "supportsTaxOpt": "supportsTaxOpt",
            "lastExecutionTime": "lastExecutionTime",
            "lastExecutionTime_r": lastExecutionTime_r,
            "orderType": "orderType",
            "side": "side",
            "timeInForce": "timeInForce",
            "price": price,
            "bgColor": "#000000",
            "fgColor": "#00F000"
        }
    ]
}

 

Cancel Live Order Updates

Cancel Order Updates Request

Topic:

uor
Cancels the live order updates subscription.

Arguments:

Do not pass arguments

 

uor+{}

 

Cancel Order Updates Response

No response is returned upon unsubscribing from market data. There will just be an end to the market data from the given conid.

Request Profit & Loss

Profit & Loss Request

Topic:

spl
Subscribes the user to live profit and loss information.

Arguments:

Do not pass arguments

spl+{}

 

Order Updates Response

topic: String.
Returns the topic of the given request.

args: Object.
Returns the object containing the pnl data.

acctId.Core: Object.
Specifies the account for which data was requested.

rowType: int.
The row value of the request. Will increment with additional accounts.

dpl: float.
Daily Profit and Loss value.

nl: float.
Net Liquidity in the account.

upl: float.
Unrealized Profit and Loss for the day.

uel: float.
Unrounded Excess Liquidty in the account.

mv: float
Market value of held stocks in the account.

{ 
   "topic": "spl" , 
    "args": { 
        "acctId.Core": { 
            "rowType":rowType, 
            "dpl":dpl, 
            "nl":nl,
            "upl":upl,
            "uel": uel,
            "mv": mv
        }
    }
}

 

Cancel Profit & Loss

Cancel Order Updates Request

Topic:

upl
Cancels the subscriptions to profit and loss information.

Arguments:

Do not pass arguments

upl+{}

 

Cancel Order Updates Response

No response is returned

Request Trades data

Trades Data Request

Topic:

str
Subscribes the user to trades data. This will return all executions data while streamed.

Arguments:

realtimeUpdatesOnly: bool. Optional
Decide whether you want to display any historical executions, or only the executions available in real time.
Set to false by default.

days: int. Optional
Returns the number of days of executions for data to be returned.
Set to 1 by default.

str+{
    "realtimeUpdatesOnly":realtimeUpdatesOnly, 
    "days":days
}

 

Trades Data Response

topic: String.
Returns the topic of the given request.

args: Object.
Returns the object containing the pnl data.

execution_id: String.
Execution identifier of the specific trade.

symbol: String.
Ticker symbol of the traded contract.

supports_tax_opt: String.
Determines if the contract supports the tax optimizer. Client Portal only.

side: String.
Determines if the order was a buy or sell side.

order_description: String.
Describes the full content of the order.
Value format: “{SIDE} {SIZE} @ {PRICE} on {EXCHANGE}”

trade_time: String.
Traded date time in UTC.
Value format: “YYYYMMDD-HH:mm:ss”

trade_time_r: int.
Traded datetime of the execution in epoch time.

size: float.
Returns the quantity of shares traded.

price: String.
Returns the price used for the given trade.

exchange: String.
Returns the exchange the order executed at.

net_amount: float.
Returns the total amount traded after calculating multiplier.

account: String.
Returns the account the order was traded on.

accountCode: String.
Returns the account the order was traded on.

company_name: String.
Returns the title of the company for the contract.

contract_description_1: String.
Returns the underlying symbol of the contract.

contract_description_2: String.
Returns a full description of the derivative.

sec_type: String.
Returns the security type traded.

conid: int.
Contract identifier for the traded contract.

conidEx: String.
Returns the conidEx of the order if specified. Otherwise returns conid.

open_close: String.
Returns if the execution was a closing trade.
Returns “???” if the position was already open, but not a closing order.

liquidation_trade: String.
Returns if the trade was a result of liquidation.

is_event_trading: String.
Determines if the order can be used with EventTrader.

{
  "topic":"topic"
  "args":[
    {
    "execution_id":"execution_id"
    "symbol":"symbol"
    "supports_tax_opt":"supports_tax_opt"
    "side":"side"
    "order_description":"order_description"
    "trade_time":"trade_time"
    "trade_time_r":trade_time_r
    "size":size
    "price":"price"
    "exchange":"exchange"
    "net_amount":net_amount
    "account":"account"
    "accountCode":"accountCode"
    "company_name":"company_name"
    "contract_description_1":"contract_description_1"
    "contract_description_2":"contract_description_2"
    "sec_type":"sec_type"
    "conid":conid
    "conidEx":"conidEx"
    "open_close":"open_close"
    "liquidation_trade":"liquidation_trade"
    "is_event_trading":"is_event_trading"
    }
  ]
}

 

Cancel Trades data

Cancel Trades Data Request

Topic:

utr
Cancels the trades data subscription

 

utr

 

Cancel Trades Data Response

Nothing is returned upon cancellation request.

Unsolicited Messages

In many instances, Interactive Brokers will automatically return various messages over the websocket to alert the user to various issues. None of these messages can be directly requested but will be returned as certain events arise.

Account Updates

Returns details about the brokerage accounts that the currently logged in user has access to. An initial message is sent when the user a connection to the websocket is first established, with supplemental messages are sent whenever there is a change to the account details.

topic: String.
Returns the topic of the given request.

args: Object.
Returns the object containing the pnl data.

accounts: Array.
Displays all accounts currently accessible by the user.

acctProps: Object.
Returns an object detailing the account properties.

acctId: Object.
Returns the specific allocation group or account information.

hasChildAccounts: bool.
Returns whether there are any subaccounts attached to the listed account.

supportsCashQty: bool.
Returns where the account supports cash quantity orders.

noFXConv: bool.
Returns if the account supports forex conversion.

isProp: bool.

supportsFractions: bool.
Returns if the account supports fractional trading.

allowCustomerTime: bool.
Returns if the account returns data in the customer’s local time.

aliases: Object.
Returns a series of accounts and their affiliated aliases.

allowFeatures:  Object.
Displays the allowed features for the account.

showGFIS: bool.
Determines whether the account can display data or not.

showEUCostReport: bool.
Determines if the account receives the EU Cost Report.

allowEventContract: bool.
Determines if the account can receive event contracts.

allowFXConv: bool.
Determines if the account allows forex conversions.

allowFinancialLens: bool.
Determines if the account supports Financial Lens (Client Portal Only).

allowMTA: bool.
Determines if the account supports Mobile Trading Alerts.

allowTypeAhead: bool.
Determines if the account supports Type Ahead (Client Portal Only).

allowEventTrading: bool.
Determines if the account supports Event Trader (Client Portal Only).

snapshotRefreshTimeout: int.
Determines if the account can support snapshot refresh (Client Portal Only).

liteUser: bool.
Returns if the account is an IBKR Lite account.

showWebNews: bool.
Returns if the account

research: bool.
Determines if the account supports research subscriptions.

debugPnl: bool.
Determines if the account enables debug for PnL (Client Portal Only).

showTaxOpt: bool.
Determines if the account supports Tax Optimizer (Client Portal Only).

showImpactDashboard: bool.
Determines if the account should display the Impact Dashboard on startup (Client Portal Only).

allowDynAccount: bool.
Determines if the account supports Dynamic Account Structures (Client Portal Only).

allowCrypto: bool.
Determines if the account supports Crypto trading.

allowedAssetTypes: String.
Returns all support asset or security types.

chartPeriods: Object of Arrays.
Returns the trading hours supported by each approvided asset type.

groups: Array.
Lists all groups the account is listed under.

profiles: Array.
Lists all profiles the account is listed under.

selectedAccount: String.
Returns the acively selected account.

serverInfo: Object.
Returns a description of the server info.

sessionId: String.
Returns the sesion identifier.

isFT: bool.
Returns if the fractional trading account.

isPaper: bool.
Returns if the active account is a paper trading account.

{
    "topic":"act",
    "args":{
       "accounts":[],
       "acctProps":{
          "All":{
             "hasChildAccounts":hasChildAccounts,
             "supportsCashQty":supportsCashQty,
             "noFXConv":noFXConv,
             "isProp":isProp,
             "supportsFractions":supportsFractions,
             "allowCustomerTime":allowCustomerTime
          }
       },
       "aliases":{},
       "allowFeatures":{
          "showGFIS":showGFIS,
          "showEUCostReport":showEUCostReport,
          "allowEventContract":allowEventContract,
          "allowFXConv":allowFXConv,
          "allowFinancialLens":allowFinancialLens,
          "allowMTA":allowMTA,
          "allowTypeAhead":allowTypeAhead,
          "allowEventTrading":allowEventTrading,
          "snapshotRefreshTimeout":snapshotRefreshTimeout,
          "liteUser":liteUser,
          "showWebNews":showWebNews,
          "research":research,
          "debugPnl":debugPnl,
          "showTaxOpt":showTaxOpt,
          "showImpactDashboard":showImpactDashboard,
          "allowDynAccount":allowDynAccount,
          "allowCrypto":allowCrypto,
          "allowedAssetTypes":"allowedAssetTypes"
       },
       "chartPeriods":{
          "STK":[],
          "CFD":[],
          "OPT":[],
          "FOP":[],
          "WAR":[],
          "IOPT":[],
          "FUT":[],
          "CASH":[],
          "IND":[],
          "BOND":[],
          "FUND":[],
          "CMDTY":[],
          "PHYSS":[],
          "CRYPTO":[]
       },
       "groups":[],
       "profiles":[],
       "selectedAccount":"selectedAccount",
       "serverInfo":{
          "serverName":"serverName",
          "serverVersion":"serverVersion"
       },
       "sessionId":"sessionId",
       "isFT":isFT,
       "isPaper":isPaper
    }
 }

 

Authentication Status

When initially connecting to the websocket endpoint, the topic sts will relay back the current authentication status of the user. Authentication status updates, for example those resulting from competing sessions, are also relayed back to the websocket client via this topic.

topic: String.
Returns the topic of the given request.

args: Object.
Returns the data object.

authenticated: bool.
Returns whether the user is authenticated to the brokerage session.

{
    "topic": "sts" ,
    "args": {
        "authenticated": authenticated
    }
}

 

Bulletins

If there are urgent messages concerning exchange issues, system problems, and other trading information, the topic blt is sent along with the message argument and a unique identifier for the bulletin.

topic: String.
Returns the topic of the given request.

args: Object.
Returns the bulletins argument values.

id: String.
Returns the ID for the specific bulletin.

message: String.
Returns the bulletin information.

{
    "topic": "blt" ,
    "args": {
        "id": "id" ,
        "message": "message" 
    }
}

 

System Connection Messages

When initially connecting to websocket the topic system relays back a confirmation with the corresponding username. While the websocket is connecting every 10 seconds there after a heartbeat with corresponding unix time (in millisecond format) is relayed back.

topic: String.
Returns the topic of the given request.

success: String.
Returns the username logged in with that has built the websocket.

{
    "topic": "system" ,
    "success": "success"
}

 

Notifications

If there is a brief message regarding trading activity the topic ntf will be sent.

topic: String.
Returns the topic of the given request.

args: Object.
Returns the object containing the pnl data.

id: String.
Returns the identifier for the specific notification.

text: String.
Returns the body text for the affiliated notification.

title: String.
Returns the title or headline for the notification.

url: String.
If relevant, provides a url where a user can go to read more about the notification.

{
    "topic": "ntf",
    "args": {
        "id": "id",
        "text": "text",
        "title": "title",
        "url": "url"
    }
}

 

OAuth 1.0a

Introduction

Interactive Brokers offers an OAuth 1.0a authentication procedure for licensed Financial Advisors, Organizations, IBrokers, and third party services. Beyond the initial authentication procedure, the OAuth implementation will behave the same as the standard Client Portal API and it’s endpoints.

Authentication via tokens produced by our OAuth 1.0a workflow permits requests to be made directly to https://api.ibkr.com, without the need for any intermediary software such as the Client Portal Gateway. Resource paths remain the same regardless of the method of authentication.

Interactive Brokers makes a distinction between first-party use of OAuth directly by clients and third-party use of OAuth by vendors of software, described below.

First Party Oauth

Interactive Brokers classifies first party entities as institutions that will be trading on behalf of themselves or their institution. The same entity developing with the API platform will be the same entity that will be using it for trading.

Examples of first party entities include financial advisors, hedge funds, and organizations looking to trade their own capital.

For interested first party candidates, please create a web ticket with the API team with the following questions answered.

  1. What do you intend to do with OAuth access?
  2. Please list all accounts that will use the developed OAuth program.
  3. Will the client application be developed in-house or by a third-party developer?

Approved groups using First Party OAuth will need to use the Self Service Portal in order to generate their consumer key, encryption keys, and access tokens. This link will be provided directly to approved entities during the onboarding process. This is an essential step in creating your program and following the steps listed below.

Please note: Registering a consumer key requires a midnight reset in order to function on your account. After saving your consumer key, please wait until the following day to test your application.

Third Party OAuth

Interactive Brokers classifies third party entities as any organization offering a platform or medium of trading to individuals outside of the organization. Please note that interested groups that would like to register as a third party with Interactive Brokers must have an established platform with other brokerage firms, or a full proof of concept with an integration using the Client Portal API.

Examples of this would include auto-traders or robo-advisors, public mobile applications, and groups forwarding market data.

For organizations that meet the criteria above and have an interest in integrating with Interactive Brokers, we would ask that you please fill out this form and email it to webapionboarding@interactivebrokers.com.

Onboarding Questionaire

To give you a sense for the process ahead:

  1. Our onboarding team conducts the initial vetting process. Once we have collected a sufficient amount of information, we will complete a preliminary review. Estimated time to complete this step is 2-3 weeks. Assuming we are able to proceed, we will send your application to our Compliance team for review.
  2. IBKR Compliance conducts an enhanced due diligence review on all third party applicants, followed by a three tier approval process. Estimated time to complete Compliance related reviews and tasks is 3-6 weeks.
  3. If Compliance approval is reached, our Legal team will generate the WebAPI agreement which we will send to you for review and signature. In parallel, we will ask you to provide public keys and a CallbackURL which will be required in to generate your consumer key and finalize the setup. Detailed instructions for this process will be provided once we reach this stage. Estimated time for our side to complete the aforementioned work and processes is 3-5 weeks.

The above timelines are all estimations and can vary. We recommend providing as much information as possible up front. Not doing so can exaggerate timelines.

During the enhanced due diligence reviews conducted by our Compliance teams, they will expect to see that 3rd Party Vendors looking to offer their services to our clients have a completed website with details on all of the features/services that will be provided and finalized details on their offering. This typically includes a clear user work flow for all components and details on their functionality, capability.

As mentioned previously, should Compliance approval be reached we would be able to generate a live consumer key for you and any significant changes to the offering after it has been approved (like addition of trading functionality) would require additional review and approval from our Compliance Teams before being offered to IBKR clients.

Please be aware we expect 3rd Parties offering automated trading solutions would hold applicable registration with financial authority in all regions they plan offer the service, unless you are able to provide support (i.e. a legal opinion) as to why the business provided would not require registration that location. Additionally, the offering will need to be reviewed and approved by Compliance teams in all regions you intend to support IBKR clients.

The above timelines are all estimations and can vary. We recommend providing as much information as possible up front. Not doing so can exaggerate timelines.

Sessions with OAuth

A brokerage session (or trading session) is established by a username (your credentials), which in turn has trading permissions for one or more accounts (the actual pools of equity). A single username can only have one trading (or “brokerage”) session active at a time. Permissions for trading in general/ for specific asset classes, market data subscriptions (and thus access to the subscribed feeds), etc. are carried by usernames, not the underlying accounts. Hence references to brokerage sessions refer to a logged-in username that is in contact with IBKR’s backend trading infrastructure.

Interactive Brokers permits a single username to be signed in one brokerage session at any given time. However, the Client Portal API permits users to log in without connecting to a brokerage session. This allows brokerage sessions to continue trading while non-brokerage sessions can perform certain actions such as requesting portfolio information without breaking existing trading sessions.

Additional details:

  1. An IB username can only have one brokerage session (trading-enabled) session open at a time, i.e., it can only trade and use similarly restricted functionality on one platform (TWS, Client Portal, etc.) at any given moment, and switching to trading on a different platform entails closing the existing brokerage session and opening a new one from the new platform.
  2. Web API sessions in general are two-tiered:
    1. An “outer” prerequisite “read-only session” that is required to be active/valid in order to make any CP Web API request, though by itself it only permits access to non-/iserver endpoints.
    2. The “brokerage session”, established after the read-only, that permits access to trading, consumption of market data, and all other functionality behind /iserver endpoints.
  3. This two-tiered arrangement reflects the way our Client Portal website permits you to log into a read-only session for account management when that username is already logged into a brokerage session elsewhere (e.g., TWS), leaving the TWS brokerage session undisturbed.
  4. The CPAPI iframe actually behaves like the CP Gateway mentioned frequently in our CP Web API documentation (the Java-based reverse proxy tool for retail clients). The CPAPI iframe will attempt to establish a brokerage session automatically, as soon as a login occurs and the read-only session is created via SSO.

Understanding Brokerage Sessions

All resources behind /iserver are accessible only with an active “brokerage” session. Additionally:

  1. TWS being a trading platform requires that a username has trading permissions in order for it to be used to access TWS – there is no purely “read-only” TWS access
  2. The Client Portal website, on the other hand, contains all of the reporting and account management functionality, and consequently it is possible to log in to Client Portal with a read-only/no-trading-permissions username and access reports, portfolio info, etc.
  3. IServer is effectively TWS running on IB infrastructure, and it serves all of the trading-permissions-required resources, hence the need for a brokerage session to access those endpoints
  4. As a result of #2 and #3, the CP Web API also has this two-tiered session arrangement: The first tier is the read-only Portal session, and the second tier is the brokerage session through which you can talk to /iserver and actually trade the account(s), etc.
  5. Once you have a live session token, you have a Portal session and can visit non-IServer resources. The additional /ssodh/init endpoint is used to subsequently open a brokerage session with our backend, through which you can access the protected /iserver endpoints.
  6. The brokerage session is associated with the credentials in use – your username – so you don’t need to select an account here. Rather, once you have access to a brokerage session, you can manipulate all accounts visible/accessible to the username in use.
  7. Non-iserver endpoints like /portfolio are served by different backend processes that do not require trading permissions and are accessible without a brokerage session

The Authorization Header

OAuth requests require a header with the name “Authorization”. The authorization header must start with the string “OAuth”. Following “OAuth”, it has to contain the following key/value pairs separated by comma. All values should be percent-encoded.

realm
oauth_callback (only when getting request token)
oauth_consumer_key
oauth_nonce
oauth_signature
oauth_signature_method
oauth_timestamp
oauth_verifier (only when getting access token)
oauth_token (all requests except getting request token)
diffie_hellman_challenge (only when getting live session token)

 

Realm

The realm is set to “limited_poa” (when using a custom 9-character Consumer Key)
The realm is set to “test_realm” (when using TESTCONS, as the Consumer Key)

oauth_callback

This is only required when getting a request token, and should just be set to “oob”

oauth_nonce

The nonce needs to be a randomly generated, unique value. Each oauth request needs to have a different and unique nonce.

An example of how to generate a nonce is here: https://github.com/ddo/oauth-1.0a/blob/master/oauth-1.0a.js
Refer to the getNonce() method, found by searching for “OAuth.prototype.getNonce = function() {“

oauth_signature

The signature is the base string signed using a private signing key or live session token. More details about this value can be found in The OAuth Signature

oauth_signature_method

The method which we sign the base string. It is “RSA-SHA256” for the steps leading up to and including getting the live session token, and “HMAC-SHA256” when accessing protected resources.

oauth_timestamp

The timestamp in milliseconds of when the request is made.

oauth_verifier

After logging in with a user during the /authorize step, you will be redirected to a page with the verifier token in the URL as a query parameter. The
oauth_verifier value is the verifier token. This is only used for getting the access token and not required for any other request.

oauth_token

When getting the access token, this value is the same as the request token value. For all other requests (except request token requests where this is not required) this value is the access token.

diffie_hellman_challenge

This value is only required for the live session token step. Explanation on how to get it is below.

The OAuth Signature

The signature is acquired by signing the base string of the OAuth request using your private signing key and the OAuth signature method.

The Base String

The base string is a string generated based on the parameters of the OAuth request. The method the demo uses to build the base string can be found
here: https://github.com/ddo/oauth-1.0a/blob/master/oauth-1.0a.js. Search for “OAuth.prototype.getBaseString = function(request, oauth_data) {“.

The base string is in the following format:

[HTTP_METHOD]&[BASE_URL]&[PARAMETER_LIST]

 

There is a special case where there is a prepend string added to the front of the base string, only for live session token requests. In this case, the base string would be:

[PREPEND][HTTP_METHOD]&[BASE_URL]&[PARAMETER_LIST]

 

[HTTP_METHOD] = the HTTP method, such as GET, POST, DELETE etc.

[BASE_URL] = The percent encoded URL of the request, without any query parameters

[PARAMETER_LIST] = A lexicographically sorted list of key/value pairs including the authorization header pairs, query parameters and if the request
contains a body of type x-www-form-urlencoded, the body parameters. The list values are separated using the character ‘&’, then the list is percent
encoded. See section 1.2b.

[PREPEND] = A string needed to be included at the front of the base string. Unlike other parts of the base string, this value is not separated by &

Normal Base String Example

[HTTP_METHOD] = POST

[BASE_URL] = https%3A%2F%2Fapi.ibkr.com%2Fv1%2Fapi%2Foauth%2Fsession_token

[PARAMETER_LIST] = device_id%3DCCCCCC95%7C48-DF-37-57-33-80%26oauth_consumer_key%3DTESTCONS%26oauth_nonce%
3DmQfUqcZD3TjC5RNguaYVQwOXfFyCgt0m%26oauth_signature_method%3DRSA-SHA256%26oauth_timestamp%3D1605211475%
26oauth_token%3Deb31c080cc0bd45b2f55%26username%3D

POST&https%3A%2F%2Fapi.ibkr.com%2Fv1%2Fapi%2Foauth%2Fsession_token&device_id%3DCCCCCC95%7C48-DF-37-57-33-80%26oauth_consumer_key%3DTESTCONS%26oauth_nonce%3DmQfUqcZD3TjC5RNguaYVQwOXfFyCgt0m%26oauth_signature_method%3DRSA-SHA256%26oauth_timestamp%3D1605211475%26oauth_token%3Deb31c080cc0bd45b2f55%26username%3D

 

Live Session Token Base String

[PREPEND] = 901c5e47fc1abec4ae9b4747024ff4d3ba186f16522eaf823238f4cadbef9cdc

[HTTP_METHOD] = POST

[BASE_URL] = https%3A%2F%2Fapi.ibkr.com%2Fv1%2Fapi%2Foauth%2Flive_session_token

[PARAMETER_LIST] = device_id%3DCCCCCC95%7C48-DF-37-57-33-80%26diffie_hellman_challenge%
3D76ebad1411bb88283c3195498402ac238459ecfef83ab11c466a04e6cf7fb93c77a35e63f25055eae1720e702a0c218286d8dd00f04ae
40e42da57daa7f3a3d1560d2eada9cbb5b3d6f4e76d4d651c86bec396afeabdcb34fcc676bdcff017fa3ee5712198725b86a1a72e854d5da
17f8fc7f60801cecc6eeaa4892fae21effec8dc7d0514d0b7667d5c33ba32c502a908ddb7518a80f7221f76bde8b6e182d42c6ee30f925cd
c4e752c5907e0e9d3eeffc2e0ab314acb721fd83c45ca7ceba01e98c8e14623aeb19cad5a20093d937f29609f3336fa8214ba997f41c
c3a611d56128423229af7f01f8a21c6c9953c52f15c99d61cc472f05c4caf76183%26oauth_consumer_key%3DTESTCONS%
26oauth_nonce%3DHqx0Q3UxBdyEvo4I71bmAZ1lIj7LRRz7%26oauth_signature_method%3DRSA-SHA256%26oauth_timestamp%
3D1605211318%26oauth_token%3Deb31c080cc0bd45b2f

901c5e47fc1abec4ae9b4747024ff4d3ba186f16522eaf823238f4cadbef9cdcPOST&https%3A%2F%2Fapi.ibkr.com%2Fv1%2Fapi%2Foauth%2Flive_session_token&device_id%3DCCCCCC95%7C48-DF-37-57-33-80%26diffie_hellman_challenge%3D76ebad1411bb88283c3195498402ac238459ecfef83ab11c466a04e6cf7fb93c77a35e63f25055eae1720e702a0c218286d8dd00f04ae40e42da57daa7f3a3d1560d2eada9cbb5b3d6f4e76d4d651c86bec396afeabdcb34fcc676bdcff017fa3ee5712198725b86a1a72e854d5da17f8fc7f60801cecc6eeaa4892fae21effec8dc7d0514d0b7667d5c33ba32c502a908ddb7518a80f7221f76bde8b6e182d42c6ee30f925cdc4e752c5907e0e9d3eeffc2e0ab314acb721fd83c45ca7ceba01e98c8e14623aeb19cad5a20093d937f29609f3336fa8214ba997f41cc3a611d56128423229af7f01f8a21c6c9953c52f15c99d61cc472f05c4caf76183%26oauth_consumer_key%3DTESTCONS%26oauth_nonce%3DHqx0Q3UxBdyEvo4I71bmAZ1lIj7LRRz7%26oauth_signature_method%3DRSA-SHA256%26oauth_timestamp%3D1605211318%26oauth_token%3Deb31c080cc0bd45b2f

 

The Parameter List

The parameter list is a list of lexicographically sorted parameters in the following format: key=value&key=value&key=value

The list is then url encoded, so it would look something like this: key%3Dvalue%26key%3Dvalue%26key%3Dvalue

The method the demo uses to build the parameter list can be found here: https://github.com/ddo/oauth-1.0a/blob/master/oauth-1.0a.js. Search for “OAuth.prototype.getParameterString = function(request, oauth_data) {”

Parameters consist of the following:

  • They key/value pairs in the authorization header, such as oauth_signature_method, oauth_nonce, but NOT the oauth_signature
  • Any key/value pairs in the body of the request if the content-type of the request is x-www-urlencoded (so the body is excluded if it is of type JSON)

The Prepend

When we successfully request an access token, we are given an oauth_token_secret in the response. This secret must be decrypted using your private encryption key, and then converted to a hex value. The hex value of the decrypted secret is the prepend string we add in front of the base string when requesting a live session token.’

Generating The Signature

Once the base string has been successfully created, it must then be signed. When getting the request, access or live session token, the key used for signing is the private signing key, and the signature method is RSA-SHA256.

When accessing any other endpoint, which means any protected resource, the key used is the live session token as a byte array and the signature method is HMAC-SHA256.

The OAuth Process

It is important to note that the OAuth Process will begin and end differently depending on whether you are implementing first or third party access.

First Party OAuth users should skip to the Live Session Token

Request Token

For Third Party OAuth users to start the OAuth process, we must first get a request token.

To get a request token, an OAuth request to https://api.ibkr.com/v1/api/oauth/request_token must be made.

The request should be a POST request but with no body. Remember that an authorization header we mentioned has to be added. Refer to the example there.

This step is a good indicator of whether or not something is wrong with your OAuth request. If you are missing any portion of the authorization header, the response will tell you so. If something is wrong with either the base string or signature creation, then you will be met with a 401 response.

Important: This step is not necessary for First Party OAuth users. Please proceed to Requesting the Live Session Token.

/authorization step

After getting the request token, you must then redirect the user to https://www.interactivebrokers.com/authorize?oauth_token=REQUEST_TOKEN

Replace REQUEST_TOKEN with the request token you generated

After the user logs in, they will be redirected to a URL specified during consumer key creation, and there will be two query parameters in the URL:
oauth_token and oauth_verifier

oauth_token is the request token, and oauth_verifier is the verifier token required for the next step.

An example of url after the user logs in http://localhost:20000/?oauth_token=dc75fcf43e3752c1a1ce&oauth_verifier=f11e2c5d9b6d0624e

Important: This step is not necessary for First Party OAuth users. Please proceed to Requesting the Live Session Token.

Access Token

A POST OAuth request to https://api.ibkr.com/v1/api/oauth/access_token must now be made.

This time, oauth_verifier must be added to the authorization header, with the value being the verifier token retrieved from the previous step.

oauth_token must also be added to the authorization header, the value being the request token.

If the request succeeds, the response will contain two values: oauth_token and oauth_token_secret.

The oauth_token in the response is the access token, and the oauth_token_secret will be used for the next step.

The method for getting the access token in the demo can be found in src/ib/ib-oauth-settings.vue. Search for “accessTokenRequest: function”.

Important: This step is not necessary for First Party OAuth users. Please proceed to Requesting the Live Session Token.

Live Session Token

The final step in the OAuth authorization process is the live session token. A POST OAuth request to https://api.ibkr.com/v1/api/oauth/live_session_token must be made.

If you are an IB customer who registered using the Self-Service OAuth page then on that same page you should have completed the Access Token step. You would now proceed to this final step to complete the OAuth authorization process.

In this step we must calculate a Diffie-Hellman challenge using the prime and generator in the Diffie-Hellman spec provided when registering your consumer key.

Diffie-Hellman Challenge

To calculate the Diffie-Hellman challenge, we must use the following formula

A is the Diffie-Hellman challenge

g is the Diffie-Hellman generator

p is the Diffie-Hellman prime

a is the Diffie-Hellman random value, randomly generated

The calculation can be see in the Live Session Token request

Prepend

For live session token requests, we have to add a prepend to the base string.

The prepend in this case is the decrypted oauth_token_secret received from the access token step.

oauth_token_secret needs to be decrypted using your private encryption key with scheme pkcs1. The result needs to be recorded as a hex value.

The prepend is therefore the hex value of oauth_token_secret decrypted.

The Response

If the live session token request is successful, the response will contain a value “diffie_hellman”response”. This diffie_hellman_response is used to calculate the live session token. diffie_hellman_response will be in hex form.

Calculation of the Live Session Token

To calculate a live session token, we must first calculate to value of K.

  • B is the diffie_hellman_response
  • a is the Diffie-Hellman random value from step 2.4a
  • p is the Diffie-Hellman prime

To calculate the live session token, we must use K as the key to signing oauth_token_secret (as a byte array) from the access token response. The
method of signing is HMAC-SHA1. The result is the live session token.

Remember that when using the live session token to sign requests, it must be a byte array.

Important:

When K is a byte array, it MUST have a leading zero bit denoting the sign. This is because Java's BigInteger's toByteArray() method always includes a sign bit. In our case, the sign bit will always be 0 because the value of K is always positive.

If your conversion of K to a byte array does not include this sign bit, please make sure to add it before using K to calculate the live session
token. Otherwise, it will be wrong. So if you are using any sort of library that includes this function, such as Java’s BigInteger, then you don’t need to
worry about this.

An easy way to ensure your K byte array includes a sign bit, convert K to bits. If there is no remainder after dividing the length of bits by 8, then you need
to manually add a 0 byte at the beginning of the K byte array.
This is because when the number of bits is divisible by 8, then adding an extra sign bit would result in one extra byte in the array.

LST Calculation Example 1

In this example, we produce K with 8 total digits. Given this value is divisible by 8, we must prepend 0 to the beginning to the byte array in order to guarantee our sign bit.

K = 0xff
K in bytes = [255]
K in bits = 11111111
K in bits length = 8
8 % 8 = 0
K byte array = [0, 255]

 

LST Calculation Example 2

Meanwhile, this example shows K with 7 total digits. No longer divisible by 8, we must do not need to add the sign bit as this will be produced automatically.

K = 0x7f
K in bytes = [127]
K in bits = 1111111
K in bits length = 7
7 % 8 = 7
Result K byte array = [127]

 

Verification of the Live Session Token

In the live session token response, there is a value called “live_session_token_signature”. The purpose of this is to verify whether or not the live session
token you calculated was correct.

To verify, create an HMAC-SHA1 hash of your consumer key in bytes, with the live session token you calculated in bytes as the signing key. Then convert
the result to hex format. If hex result is the same as live_session_token_signature, the live session token you calculated is correct. Now that you have a live session token, non-brokerage endpoints (non-/iserver endpoints) are now accessible.

In order to access /iserver endpoints, users will need to initialize their brokerage session.

SSODH Init Request

An OAuth protected-resource POST request must be made to https://api.ibkr.com/v1/api/iserver/auth/ssodh/init

There are two required parameters: compete and publish.

“compete” is whether or not the session should compete, usually set to false, but can be set to true if you want to disconnect other sessions.

“publish” must be set to true.

The parameters can be sent as request parameters or in the POST body. If sent in the body, the body must be of type x-www-form-urlencoded.

If the request is successful, the response will contain a JSON object telling you if you are authenticated and connected.

OAuth-Specific Endpoints

The endpoints included below require some structure to implement. As such, we have included a list of variables and packages referenced throughout the code samples. These requests are structured using the TESTCONS consumer keys. These can be adjusted or modified with the First Party OAuth implementation or a consumer key of your own.

Please note these are sample references not intended for production use. The underlying structure for these requests are listed above in The OAuth Process section.

key_dir = "C:\\web.demo\\keys\"

with open(key_dir+"private_encryption.pem", "r") as f:
    encryption_key = RSA.import_key(f.read())

with open(key_dir+"private_signature.pem", "r") as f:
    signature_key = RSA.import_key(f.read())

dh_prime = "f51d7ab737a452668fd8b5eec12fcdc3c01a0744d93db2e9b1dc335bd2551ec67e11becc60c33a73497a0f7c086d87e45781ada35b7af72708f31ae221347a1c6517575a347df83a321d05450547ee13a8182280ed81423002aa6337b48a251d840bfdabe8d41b8109284933a6c33bc6652ea9c7a5fd6b4945b7b39f1d951ae19b9192061e2f9de84768b67c425258724cdb96975917cabdea87e7e0bc72b01a331d06f2f34229a5ec742b399fcffa510bf6b8f9b5bf9858f058371a49aa4f950f7fbfb3f47710af34baa83fff1b467d38d0e6b1b0a2d117f178cf930d7dfdcc8f6755a2229d48492a967f493041121e382b9e87ca1368c09f54e6352d909f2b"
dh_generator = 2
consumer_key = "TESTCONS"
realm = "test_realm"
callback = "oob"

 

# Python Imports Used
import json
import requests
import random
import base64
from datetime import datetime
from urllib.parse import quote, quote_plus
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5 as PKCS1_v1_5_Signature
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_v1_5_Cipher
from Crypto.Hash import SHA256, HMAC, SHA1
import websocket
import time

 

Request Token

Obtain a request token. See section 6.1 of the OAuth v1.0a specification for more information.

Endpoint

Note we do not return an oauth_token_secret in the response as we are using RSA signatures rather than PLAINTEXT authentication.

Important: This step is not necessary for First Party OAuth users. Please proceed to Requesting the Live Session Token.

POST /oauth/request_token

 

OAuth Params

oauth_consumer_key: String. Required
The 25-character hexadecimal string that was obtained from Interactive Brokers during the OAuth consumer registration process.

oauth_signature_method: String. Required
The signature method used to sign the request. Currently only ‘RSA-SHA256’ is supported.

oauth_signature: String. Required
The signature for the request generated using the method specified in the oauth_signature_method parameter. See section 9 of the OAuth v1.0a specification for more details on signing requests.

oauth_timestamp: String. Required
Timestamp expressed in seconds since 1/1/1970 00:00:00 GMT. Must be a positive integer and greater than or equal to any timestamp used in previous requests.

oauth_nonce: String. Required
A random string uniquely generated for each request.

oauth_callback: String. Required
An absolute URL to which IB will redirect the user. This URL is provided by the consumer during registration. This parameter must be set to ‘oob’.

{
  "oauth_consumer_key": "string",
  "oauth_signature_method": "string",
  "oauth_signature": "string",
  "oauth_timestamp": "string",
  "oauth_nonce": "string",
  "oauth_callback": "string"
}

 

Request Structure

url = f'https://api.ibkr.com/v1/api/oauth/request_token'
oauth_params = {
  "oauth_callback": {{oauth_callback }},
  "oauth_consumer_key": {{consumer_key}},
  "oauth_nonce": hex(random.getrandbits(128))[2:],
  "oauth_signature_method": "RSA-SHA256",
  "oauth_timestamp": str(int(datetime.now().timestamp())),
  }
params_string = "&".join([f"{k}={v}" for k, v in sorted(oauth_params.items())])

# Base string successfully created
base_string = f"POST&{quote_plus(url)}&{quote(params_string)}"

# Base string should then signed with the private key in RSA-SHA256
encoded_base_string = base_string.encode("utf-8")
sha256_hash = SHA256.new(data=encoded_base_string)
bytes_pkcs115_signature = PKCS1_v1_5_Signature.new(
  rsa_key=signature_key
  ).sign(msg_hash=sha256_hash)
b64_str_pkcs115_signature = base64.b64encode(bytes_pkcs115_signature).decode("utf-8")

# Establish the authorization header
oauth_params["oauth_signature"] = quote_plus(b64_str_pkcs115_signature)
oauth_params["realm"] = realm
oauth_header = "OAuth " + ", ".join([f'{k}="{v}"' for k, v in sorted(oauth_params.items())])
headers = {"authorization": oauth_header}
headers["User-Agent"] = "python/3.11"

rToken_request = requests.post(url=url, headers=headers)
rToken = rToken_request.json()["oauth_token"]

 

Response Object

oauth_token: String.
Resulting oauth or access token used as an encoded authentication value.

{
  "oauth_token": "b9082d68cfef06b030de"
}

 

Authorization

After retrieving our request token, we need to authorize the value against the Interactive Brokers server. This is done by directing users to https://interactivebrokers.com/authorize?oauth_token={{ Request Token }} where they will log in with their Interactive Brokers credentials. Because we are using “oob” as our callback url, users will be presented with an error page.

Our verifier token is returned in the url; however, this value is returned directly for fully implemented third parties who have established their redirect URL with the Interactive Brokers Onboarding team.

Authorization URL

Direct the client to the Interactive Brokers authorize uri where they can then log in to establish the request token to their user.

https://interactivebrokers.com/authorize?oauth_token={{ Request Token }}

 

Request

For our programmatic implementation without an official callback url, we can introduce a simple line to direct the user to the login page and save the verifier token for later.

url = f'https://interactivebrokers.com/authorize?oauth_token={rToken}'
vToken = input(f"Please log in to {url} and paste the 'oauth_verifier' value here: ")

 

Response

A successful login will direct them to the callback url, which displays both the oauth_token (request token) and the oauth_verifier (verifier token). This can be pasted back to our original request, and saved as a variable for the Access Token request.

The /authorize response

Access Token

Obtain an access token using the request token and the verification code you received after the user provided authorization. See section 6.1 of the OAuth v1.0a specification for more information.

Endpoint

Note we do not return an oauth_token_secret in the response as we are using RSA signatures rather than PLAINTEXT authentication.

Important: This step is not necessary for First Party OAuth users. Please proceed to Requesting the Live Session Token.

POST /oauth/access_token

 

OAuth Params

oauth_consumer_key: String. Required
The 25-character hexadecimal string that was obtained from Interactive Brokers during the OAuth consumer registration process.

oauth_token: String. Required
The request token obtained from IB via /request_token.

oauth_signature_method: String. Required
The signature method used to sign the request. Currently only ‘RSA-SHA256’ is supported.

oauth_signature: String. Required
The signature for the request generated using the method specified in the oauth_signature_method parameter. See section 9 of the OAuth v1.0a specification for more details on signing requests.

oauth_timestamp: String. Required
Timestamp expressed in seconds since 1/1/1970 00:00:00 GMT. Must be a positive integer and greater than or equal to any timestamp used in previous requests.

oauth_nonce: String. Required
A random string uniquely generated for each request.

oauth_verifier: String. Required
The verification code received from IB after the user has granted authorization.

{
  "oauth_consumer_key": "string",
  "oauth_token": "string",
  "oauth_signature_method": "string",
  "oauth_signature": "string",
  "oauth_timestamp": "string",
  "oauth_nonce": "string",
  "oauth_verifier": "string"
}

 

Request Structure

url = f'https://api.ibkr.com/v1/api/oauth/access_token'
oauth_params = {
  "oauth_callback":callback,
  "oauth_consumer_key": consumer_key,
  "oauth_nonce": hex(random.getrandbits(128))[2:],
  "oauth_signature_method": "RSA-SHA256",
  "oauth_timestamp": str(int(datetime.now().timestamp())),
  "oauth_token": rToken,
  "oauth_verifier": vToken,
  }
params_string = "&".join([f"{k}={v}" for k, v in sorted(oauth_params.items())])

# Base string successfully created
base_string = f"POST&{quote_plus(url)}&{quote(params_string)}"

# Base string should then signed with the private key in RSA-SHA256
encoded_base_string = base_string.encode("utf-8")
sha256_hash = SHA256.new(data=encoded_base_string)
bytes_pkcs115_signature = PKCS1_v1_5_Signature.new(
  rsa_key=signature_key
  ).sign(msg_hash=sha256_hash)
b64_str_pkcs115_signature = base64.b64encode(bytes_pkcs115_signature).decode("utf-8")

# Establish the authorization header
oauth_params["oauth_signature"] = quote_plus(b64_str_pkcs115_signature)
oauth_params["realm"] = realm
oauth_header = "OAuth " + ", ".join([f'{k}="{v}"' for k, v in sorted(oauth_params.items())])
headers = {"authorization": oauth_header}
headers["User-Agent"] = "python/3.11"

# Send the request and save the tokens to variables
atoken_request = requests.post(url=url, headers=headers)
aToken = atoken_request.json()["oauth_token"]
aToken_secret = atoken_request.json()["oauth_token_secret"]

 

Response Object

Response Object

oauth_token: String.
Resulting oauth or access token used as an encoded authentication value.

oauth_token_secret: String.
Resulting access token secret used as an encoded authentication value.

{
  "oauth_token": "string",
  "oauth_token_secret": "string"
}

 

Live Session Token

In order to access protected IB resources, a live session token is required. This endpoint allows consumers to obtain a live session token to access these resources using an OAuth access token and the Diffie-Hellman prime and generator supplied during the registration process. Note this is an additional IB-specific step, and not part of the OAuth v1.0a specification.

Endpoint

The live session token will allow the user to access their API, for trading or for portfolio access, over a 24 hour period. The creation of the Live Session Token does not establish a complete trading session, as that would be handled by Initializing the Brokerage Session.

POST /oauth/live_session_token

 

OAuth Params

oauth_consumer_key: String. Required
The 9-character string that was obtained from Interactive Brokers during the OAuth consumer registration process. This is set in the Self Service Portal.

oauth_token: String. Required
The access token obtained from IB via /access_token or the Self Service Portal.

oauth_signature_method: String. Required
The signature method used to sign the request. Currently only ‘RSA-SHA256’ is supported.

oauth_signature: String. Required
The signature for the request generated using the method specified in the oauth_signature_method parameter. See section 9 of the OAuth v1.0a specification for more details on signing requests.

oauth_timestamp: String. Required
Timestamp expressed in seconds since 1/1/1970 00:00:00 GMT. Must be a positive integer and greater than or equal to any timestamp used in previous requests.

oauth_nonce: String. Required
A random string uniquely generated for each request.

diffie_hellman_challenge: String. Required
Challenge value calculated using the Diffie-Hellman prime and generated provided during the registration process. See the “OAuth at Interactive Brokers” document for more details.

{
  "oauth_consumer_key": "string",
  "oauth_token": "string",
  "oauth_signature_method": "string",
  "oauth_signature": "string",
  "oauth_timestamp": "string",
  "oauth_nonce": "string",
  "diffie_hellman_challenge": "string"
}

 

Request

dh_random = str(random.getrandbits(256))
dh_unchallenged = pow(dh_generator, int(dh_random, 16), int(dh_prime, 16))
dh_challenge = hex(dh_unchallenged)[2:]
bytes_decrypted_secret = PKCS1_v1_5_Cipher.new(
  key=encryption_key
  ).decrypt(
    ciphertext=base64.b64decode(access_token_secret), 
    sentinel=None,
    )
prepend = bytes_decrypted_secret.hex()
base_string = prepend
method = 'POST'
url = f'https://api.ibkr.com/v1/api/oauth/live_session_token'
oauth_params = {
  "oauth_consumer_key": consumer_key,
  "oauth_nonce": hex(random.getrandbits(128))[2:],
  "oauth_timestamp": str(int(datetime.now().timestamp())),
  "oauth_token": access_token,
  "oauth_signature_method": "RSA-SHA256",
  "diffie_hellman_challenge": dh_challenge,
}
params_string = "&".join([f"{k}={v}" for k, v in sorted(oauth_params.items())])
base_string += f"{method}&{quote_plus(url)}&{quote(params_string)}"
encoded_base_string = base_string.encode("utf-8")
sha256_hash = SHA256.new(data=encoded_base_string)
bytes_pkcs115_signature = PKCS1_v1_5_Signature.new(
  rsa_key=signature_key
  ).sign(msg_hash=sha256_hash)
b64_str_pkcs115_signature = base64.b64encode(bytes_pkcs115_signature).decode("utf-8")
oauth_params['oauth_signature'] = quote_plus(b64_str_pkcs115_signature)
oauth_params["realm"] = realm
oauth_header = "OAuth " + ", ".join([f'{k}="{v}"' for k, v in sorted(oauth_params.items())])
headers = {"Authorization": oauth_header}
headers["User-Agent"] = "python/3.11"

'''
Make the request, and manage any potential fails
If your request fails, it may be possible the OAuth verifier was copied incorrectly.
It is also important to confirm the signature and encryption keys are valid and correspond to the dh_prime.
'''
lst_request = requests.post(url=url, headers=headers)
lst_response = json.dumps(lst_request.json())
if lst_request.status_code != 200:
  print(f"ERROR: Request to /live_session_token failed. Exiting...")
  raise SystemExit(0)

response_data = lst_request.json()
dh_response = response_data["diffie_hellman_response"]
lst_signature = response_data["live_session_token_signature"]
lst_expiration = response_data["live_session_token_expiration"]

 

Response

diffie_hellman_response: String.
Response based on the calculated Diffie Hellman challenge.
The full value should be 512 characters long.

live_session_token_signature: String.
Signature value used to prove authenticated status for subsequent requests.

live_session_token_expiration: Number.
Returns the epoch timestamp of the live session token’s expiration.
The live session token is valid for approximately 24 hours after creation.
 

{
  "diffie_hellman_response": "62933e{...}d64d6db34d",
"live_session_token_signature": "9bd5922b2b79effef23c6fb03cc715dcdc8d6219",
 "live_session_token_signature": "9bd5922b2b79effef23c6fb03cc715dcdc8d6219",
"live_session_token_expiration": 1700691802316
}

 

Compute Live Session Token

prepend_bytes = bytes.fromhex(prepend)

# To calculate a live session token, we must first calculate to value of K.
INT_BASE = 16
B = int(dh_response, INT_BASE)
a = int(dh_random, INT_BASE)
p = int(dh_prime, INT_BASE)
K = pow(B, a, p)
hex_str_K = hex(K)[2:]

# To calculate the live session token, we must use K as the key to signing oauth_token_secret (as a byte array) from the access token response.
if len(hex_str_K) % 2:
  print("adding leading 0 for even number of chars")
  hex_str_K = "0" + hex_str_K
hex_bytes_K = bytes.fromhex(hex_str_K)
if len(bin(K)[2:]) % 8 == 0:
  hex_bytes_K = bytes(1) + hex_bytes_K

# The method of signing is HMAC-SHA1. The result is the live session token.
bytes_hmac_hash_K = HMAC.new(
  key=hex_bytes_K,
  msg=prepend_bytes,
  digestmod=SHA1,
  ).digest()

computed_lst = base64.b64encode(bytes_hmac_hash_K).decode("utf-8")

hex_str_hmac_hash_lst = HMAC.new(
  key=base64.b64decode(computed_lst),
  msg=consumer_key.encode("utf-8"),
  digestmod=SHA1,
).hexdigest()

# Remember that when using the live session token to sign requests, it must be a byte array.
if hex_str_hmac_hash_lst == lst_signature:
  live_session_token = computed_lst
  lst_expiration = lst_expiration
  print("Live session token computation and validation successful.")
  print(f"LST: {live_session_token}; expires: {datetime.fromtimestamp(lst_expiration/1000)}\n")
else:
  print(f"ERROR: LST validation failed. Exiting...")
  raise SystemExit(0)

 

Initialize sesion

Endpoint

After 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,

POST /iserver/auth/ssodh/init

 

OAuth Params

oauth_consumer_key: String. Required
The 25-character hexadecimal string that was obtained from Interactive Brokers during the OAuth consumer registration process.

oauth_token: String. Required
The request token obtained from IB via /request_token.

oauth_signature_method: String. Required
The signature method used to sign the request. Currently only ‘RSA-SHA256’ is supported.

oauth_signature: String. Required
The signature for the request generated using the method specified in the oauth_signature_method parameter. See section 9 of the OAuth v1.0a specification for more details on signing requests.

oauth_timestamp: String. Required
Timestamp expressed in seconds since 1/1/1970 00:00:00 GMT. Must be a positive integer and greater than or equal to any timestamp used in previous requests.

oauth_nonce: String. Required
A random string uniquely generated for each request.

{
  "oauth_consumer_key": consumer_key,
  "oauth_token": access_token,
  "oauth_signature_method": "HMAC-SHA256",
  "oauth_timestamp": "string",
  "oauth_nonce": "string"
}

 

Request

method = "POST"
url = f'https://api.ibkr.com/v1/api/iserver/auth/ssodh/init?publish=true&compete=true'
oauth_params = {
    "oauth_consumer_key": consumer_key,
    "oauth_nonce": hex(random.getrandbits(128))[2:],
    "oauth_signature_method": "HMAC-SHA256",
    "oauth_timestamp": str(int(datetime.now().timestamp())),
    "oauth_token": access_token
  }
params_string = "&".join([f"{k}={v}" for k, v in sorted(oauth_params.items())])
base_string = f"{method}&{quote_plus(url)}&{quote(params_string)}"
bytes_hmac_hash = HMAC.new(
  key=base64.b64decode(live_session_token), 
  msg=base_string.encode("utf-8"),
  digestmod=SHA256
  ).digest()
b64_str_hmac_hash = base64.b64encode(bytes_hmac_hash).decode("utf-8")
oauth_params["oauth_signature"] = quote_plus(b64_str_hmac_hash)
oauth_params["realm"] = realm
oauth_header = "OAuth " + ", ".join([f'{k}="{v}"' for k, v in sorted(oauth_params.items())])
headers = {"Authorization": oauth_header}
headers["User-Agent"] = "python/3.11"
init_request = requests.post(url=url, headers=headers)
init_response = json.dumps(init_request.json(), indent=2)
print(init_response)

 

Response

Response Object

authenticated: bool.
Returns whether your brokerage session is authenticated or not.

competing: bool.
Returns whether you have a competing brokerage session in another connection.

connected: bool.
Returns whether you are connected to the gateway, authenticated or not.

message: String.
If there is a message about your authenticate status, it will be returned here.
Authenticated sessions return an empty string.

MAC: String.
IBKR MAC information. Internal use only.

serverInfo: Object.

serverName: String.
IBKR server information. Internal use only.

serverVersion: String.
IBKR version information. Internal use only.

{
  "authenticated":authenticated,
  "competing":competing,
  "connected":connected,
  "message":"message",
  "MAC":"MAC",
  "serverInfo":{
    "serverName":"serverName",
    "serverVersion":"serverVersion"
  },
}

 

Websockets Over OAuth

In some ways, we see that websockets will behave differently from how they function for the conventional Client Portal Gateway connection. This would be in addition to the standard connection process, including sending the session token as a cookie or through the websocket upon opening. To read more about this behavior, please see the Client Portal Websocket Connection Guide.

Please keep in mind that the CPAPI Websocket Topics themselves will remain consistent with OAuth.

OAuth users, both First and Third party, must include the additional parameters of “oauth_token” which should be set to the user’s access token.

wss://api.ibkr.com/v1/api/ws?oauth_token={{access_token}}

 

Flex Web Service

The Flex Web Service is a small, standalone HTTP API for programmatically generating and retrieving pre-configured Flex Queries. Flex Queries are first constructed manually as templates in Client Portal, after which the Flex Web Service API is used to generate an instance of a report populated with up-to-date data and deliver it back to the requesting client. The Flex Web Service offers access to the same Flex Query reports that you’d otherwise retrieve manually from within Client Portal.

For more information about Flex Queries and about IB’s reporting functionality overall, please consult the following documentation:

Usage Notes:

  1. Though Flex Query reports can be generated and retrieve at any time, the data they contain will not necessarily change throughout the day. “Activity Statement” Flex Queries contain data that is only updated once daily at close of business, so there is no benefit to generating and retrieving these reports more than once per day. Normally one would retrieve the prior day’s Activity Statements at the start of the following day, which guarantees that all values have been updated by IB’s reporting backend.
  2. “Trade Confirmation” Flex Queries, however, will yield updated data throughout the day as executions occur against working orders, but these execution entries are also not available in Trade Confirmation Flex Queries in real-time. Typically a new execution will be available for inclusion in a newly generated Flex Query report within 5 to 10 minutes.
  3. Given the above restrictions on the refresh rate of Flex Query data, the Flex Web Service is not suitable for active polling for newly generated reports. Rather, it is best used to capture the desired reports once daily, or at most intermittently throughout the day in the case of Trade Confirmation reports.
  4. Depending on the size of the report to be generated, there may be a slight delay between the initial request to generate the report and the report’s availability via the second request. Time to availability is also dependent on system utilization, so please permit some flexibility in the timing of the final report retrieval, either via an explicit “wait” between the first and second requests, or via periodic reattempts of the second request. See the Using the API section for details of this two-request workflow.
  5. Note that the same Flex Query reports (as well as many other report types) can also be scheduled for delivery via email or FTP:

Client Portal Configuration

Before using the Flex Web Service API to programmatically retrieve Flex Query reports, you’ll need to manually obtain some values from within Client Portal:

  1. An access token to authenticate our requests
  2. One or more query IDs corresponding to the reports you’d like to fetch

If you want to retrieve Flex Queries that you’ve already created, you’ll need to log into Client Portal with the username that created them, as these Flex Query report configurations are username-specific. Once we obtain these values, however, the use of the Flex Web Service API does not involve your IB credentials. Your username will only be involved in any subsequent management of the access token or reconfiguration of the report templates.

Note: these steps can only be completed by logging in to the Client Portal directly.

Enable and Create Access Token

Navigate to Settings, and locate the Account Report section toward the bottom of the page, and click on the Flex Web Service link.

Navigate to Account Settings and click on Flex Web Service

In the pop-over window, place a check mark next to the Flex Web Service Status box at the top to enable the Flex Web Service, and then click on Generate New Token at the bottom:

Enable Flex Web Service and click Generate New Token

When generating a new access token, you must select a token lifespan from the Expire After dropdown (6 hours to 1 year). You may also set an optional whitelisted IP address to restrict the origin of requests using this token using the Valid for IP Address field. If this IP address field is left blank, there will be no IP restriction enforced against this token. Click Save at the bottom right when done to create the new token, and then capture the numeric token value.

Set lifespan and IP whitelist and save

Retrieve a Query ID

Click the Performance & Reports menu to reveal its subsections, and then click on Flex Queries.

In Client Portal, click Performance & Reports and then Flex Queries

Next, click on the Info icon to the left of a Flex Query.

Click on the Info icon to the left

From the info pop-over, capture the Query ID number listed at the top.

Capture the Query ID number

Using Flex Web Service

The Flex Web Service API consists of two endpoints. Obtaining Flex Query reports via the Flex Web Service API is a two-step workflow involving requests to both endpoints in sequence. First, you will make a request to trigger IB’s backend to generate an instance of your report, which will populate your Flex Query template with the available data. In response, you’ll receive a reference code identifying this particular instance of the report. Next, you’ll make a request to fetch the generated report using the reference code. All generated reports are delivered in binary XML.

Note that all requests must include a User-Agent header, though the value does not matter.

Generate a Report

To begin, you’ll make a GET request to the /SendRequest endpoint, passing your access token and the desired Flex Query template’s query ID as query parameters:

https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?t={{AccessToken}}&q={{QueryID}}&v=3

Make request to /SendRequest

Query Params

t. Required
Accepts the Access Token created for the Flex Web Service in Client Portal’s Account Settings interface.

q. Required
The Query ID identifier for the desired report template, obtained from the Client Portal’s Flex Query interface.

v. Required, leave value = 3
Specifies the version of the Flex Web Service to be used. Values 2 and 3 are supported, but version 3 should always be used.

import requests
import xml.etree.ElementTree as ET

sendUrl = "https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?"
token = "t=123456789123456789123456"
queryId = "&q=123456"
version = "&v=3"

requestUrl = "".join([requestBase, token, queryId, version])
flexReq = requests.get(url=requestUrl)

 

curl --request GET \
  --url "https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?t={{ AccessToken }}&q={{ QueryID }}&v=3" \
  --header "User-Agent: curl/7.81.0"

Success response from /SendRequest

Successful Response Values

Status.
A value of Success indicates a successful request to generate the report. If the request failed, Status will deliver Fail.

ReferenceCode.
If the request was successful, the XML response will contain this numeric reference code. This code will be used in the subsequent request to retrieve the generated Flex Query.

url.
This is the URL to be used in the subsequent request to retrieve the generated Flex Query.

<FlexStatementResponse timestamp="28 August, 2012 10:37 AM EDT">
    <Status>Success</Status>
    <ReferenceCode>1234567890</ReferenceCode>
    <url>https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/GetStatement</url>
</FlexStatementResponse>

Failure response from /SendRequest

Unsuccessful Response Values

Status.
A failed request will deliver a Status of Fail.

ErrorCode.
A numeric code indicating the nature of the failure. See Error Codes for a list of error code values and their descriptions.

ErrorMessage.
A human-readable description of the error. See Error Codes for a list of error code values and their descriptions.

<FlexStatementResponse timestamp="28 August, 2012 10:37 AM EDT">
    <Status>Fail</Status>
    <ErrorCode>1012</ErrorCode>
    <ErrorMessage>Token has expired.</ErrorMessage>
</FlexStatementResponse>

Retrieve the Report

Next, you’ll make a GET request to the /GetStatement endpoint, again passing your access token, but now passing the reference code obtained from the prior endpoint:

https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/GetStatement?t={{AccessToken}}&q={{ReferenceCode}}&v=3

Make request to /GetStatement

Query Params

t. Required
Accepts the Access Token created for the Flex Web Service in Client Portal’s Account Settings interface.

q. Required
Accepts the ReferenceCode returned by the previous successful request, which identifies the instance of the report to be retrieved. Note that a given Flex Query template can be used to generate multiple reports over time, each populated with data at the time of generation, so this ReferenceCode identifier is used to retrieve a specific instance, presumably the one generated immediately prior.

v. Required, leave value = 3
Specifies the version of the Flex Web Service to be used. Values 2 and 3 are supported, but version 3 should always be used.

if flexReq.status_code != 200:
  print("Error!")
  exit()
tree = ET.ElementTree(ET.fromstring(flexReq.content))
root = tree.getroot()
getURL = root.find('Url').text
refCode = "&q=%s" % root.find('ReferenceCode').text
receiveUrl = "".join([getURL, "?",token, refCode, version])

print("Hold for Request.")
time.sleep(20)

receiveUrl = requests.get(url=receiveUrl, allow_redirects=True)

open('C:\\flex_web_test.xml', 'wb').write(receiveUrl.content)
print("Done!")

 

curl --request GET \
     --url 'https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/GetStatement?t={{ AccessToken }}&q={{ ReferenceCode }}&v=3' \
     --header 'User-Agent: curl/7.81.0'

Success response from /GetStatement

A successful response will deliver your Flex Query report in binary XML.

Example Trade Confirmation Flex Query report:
<FlexQueryResponse queryName="Trades" type="AF">
    <FlexStatements count="1">
        <FlexStatement accountId="DU1234567" fromDate="20230829" toDate="20230927" period="Last30CalendarDays" whenGenerated="20230928;174413">
            <Trades>
                <Trade accountId="DU1234567" currency="USD" symbol="AAPL" conid="265598" listingExchange="NASDAQ" dateTime="20230829;101454" tradeDate="20230829" quantity="100" />
                <Trade accountId="DU1234567" currency="USD" symbol="AAPL" conid="265598" listingExchange="NASDAQ" dateTime="20230830;114005" tradeDate="20230830" quantity="10" />
                <Trade accountId="DU1234567" currency="USD" symbol="AAPL" conid="265598" listingExchange="NASDAQ" dateTime="20230905;103346" tradeDate="20230905" quantity="5" />
            </Trades>
        </FlexStatement>
    </FlexStatements>
</FlexQueryResponse>

Please consult our Reporting Guide for clarification of report fields.

Failure response from /GetStatement

Unsuccessful Response Values

Status.
A failed request will deliver a Status of Fail.

ErrorCode.
A numeric code indicating the nature of the failure. See Error Codes for a list of error code values and their descriptions.

ErrorMessage.
A human-readable description of the error. See Error Codes for a list of error code values and their descriptions.

<FlexStatementResponse timestamp="28 August, 2012 10:37 AM EDT">
    <Status>Fail</Status>
    <ErrorCode>1012</ErrorCode>
    <ErrorMessage>Token has expired.</ErrorMessage>
</FlexStatementResponse>

Error Codes

The following is a consolidated list of error codes returnable by the /SendRequest and /GetStatement endpoints when a server-side failure occurs.

ErrorCode ErrorMessage
1001 Statement could not be generated at this time. Please try again shortly.
1003 Statement is not available.
1004 Statement is incomplete at this time. Please try again shortly.
1005 Settlement data is not ready at this time. Please try again shortly.
1006 FIFO P/L data is not ready at this time. Please try again shortly.
1007 MTM P/L data is not ready at this time. Please try again shortly.
1008 MTM and FIFO P/L data is not ready at this time. Please try again shortly.
1009 The server is under heavy load. Statement could not be generated at this time. Please try again shortly.
1010 Legacy Flex Queries are no longer supported. Please convert over to Activity Flex.
1011 Service account is inactive.
1012 Token has expired.
1013 IP restriction.
1014 Query is invalid.
1015 Token is invalid.
1016 Account in invalid.
1017 Reference code is invalid.
1018 Too many requests have been made from this token. Please try again shortly.
Limited to one request per second, 10 requests per minute (per token).
1019 Statement generation in progress. Please try again shortly.
1020 Invalid request or unable to validate request.
1021 Statement could not be retrieved at this time. Please try again shortly.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.