Language

Multilingual content from IBKR

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

To retrieve order information for a specific account, clients must first query the /iserver/account endpoint to switch to the appropriate account.

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.

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

 

curl \
--url {{baseUrl}}/iserver/account/orders?filters=filled&force=true \
--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.

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

 

curl \
--url {{baseUrl}}/iserver/account/trades?days=3 \
--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)