Close Navigation
Learn more about IBKR accounts

Flex Web Service

The Flex Web Service is a small, standalone HTTP API for programmatically generating and retrieving pre-configured Flex Queries. Flex Queries are first constructed manually as templates in Client Portal, after which the Flex Web Service API is used to generate an instance of a report populated with up-to-date data and deliver it back to the requesting client. The Flex Web Service offers access to the same Flex Query reports that you’d otherwise retrieve manually from within Client Portal.

For more information about Flex Queries and about IB’s reporting functionality overall, please consult the following documentation:

Usage Notes:

  1. Though Flex Query reports can be generated and retrieve at any time, the data they contain will not necessarily change throughout the day. “Activity Statement” Flex Queries contain data that is only updated once daily at close of business, so there is no benefit to generating and retrieving these reports more than once per day. Normally one would retrieve the prior day’s Activity Statements at the start of the following day, which guarantees that all values have been updated by IB’s reporting backend.
  2. “Trade Confirmation” Flex Queries, however, will yield updated data throughout the day as executions occur against working orders, but these execution entries are also not available in Trade Confirmation Flex Queries in real-time. Typically a new execution will be available for inclusion in a newly generated Flex Query report within 5 to 10 minutes.
  3. Given the above restrictions on the refresh rate of Flex Query data, the Flex Web Service is not suitable for active polling for newly generated reports. Rather, it is best used to capture the desired reports once daily, or at most intermittently throughout the day in the case of Trade Confirmation reports.
  4. Depending on the size of the report to be generated, there may be a slight delay between the initial request to generate the report and the report’s availability via the second request. Time to availability is also dependent on system utilization, so please permit some flexibility in the timing of the final report retrieval, either via an explicit “wait” between the first and second requests, or via periodic reattempts of the second request. See the Using the API section for details of this two-request workflow.
  5. Note that the same Flex Query reports (as well as many other report types) can also be scheduled for delivery via email or FTP:

Client Portal Configuration

Before using the Flex Web Service API to programmatically retrieve Flex Query reports, you’ll need to manually obtain some values from within Client Portal:

  1. An access token to authenticate our requests
  2. One or more query IDs corresponding to the reports you’d like to fetch

If you want to retrieve Flex Queries that you’ve already created, you’ll need to log into Client Portal with the username that created them, as these Flex Query report configurations are username-specific. Once we obtain these values, however, the use of the Flex Web Service API does not involve your IB credentials. Your username will only be involved in any subsequent management of the access token or reconfiguration of the report templates.

Note: these steps can only be completed by logging in to the Client Portal directly.

Enable and Create Access Token

Navigate to Settings, and locate the Account Report section toward the bottom of the page, and click on the Flex Web Service link.

Navigate to Account Settings and click on Flex Web Service

In the pop-over window, place a check mark next to the Flex Web Service Status box at the top to enable the Flex Web Service, and then click on Generate New Token at the bottom:

Enable Flex Web Service and click Generate New Token

When generating a new access token, you must select a token lifespan from the Expire After dropdown (6 hours to 1 year). You may also set an optional whitelisted IP address to restrict the origin of requests using this token using the Valid for IP Address field. If this IP address field is left blank, there will be no IP restriction enforced against this token. Click Save at the bottom right when done to create the new token, and then capture the numeric token value.

Set lifespan and IP whitelist and save

Retrieve a Query ID

Click the Performance & Reports menu to reveal its subsections, and then click on Flex Queries.

In Client Portal, click Performance & Reports and then Flex Queries

Next, click on the Info icon to the left of a Flex Query.

Click on the Info icon to the left

From the info pop-over, capture the Query ID number listed at the top.

Capture the Query ID number

Using Flex Web Service

The Flex Web Service API consists of two endpoints. Obtaining Flex Query reports via the Flex Web Service API is a two-step workflow involving requests to both endpoints in sequence. First, you will make a request to trigger IB’s backend to generate an instance of your report, which will populate your Flex Query template with the available data. In response, you’ll receive a reference code identifying this particular instance of the report. Next, you’ll make a request to fetch the generated report using the reference code. All generated reports are delivered in binary XML.

Note that all requests must include a User-Agent header, though the value does not matter.

Generate a Report

To begin, you’ll make a GET request to the /SendRequest endpoint, passing your access token and the desired Flex Query template’s query ID as query parameters:

https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?t={{AccessToken}}&q={{QueryID}}&v=3

Make request to /SendRequest

Query Params

t. Required
Accepts the Access Token created for the Flex Web Service in Client Portal’s Account Settings interface.

q. Required
The Query ID identifier for the desired report template, obtained from the Client Portal’s Flex Query interface.

v. Required, leave value = 3
Specifies the version of the Flex Web Service to be used. Values 2 and 3 are supported, but version 3 should always be used.

import requests
import xml.etree.ElementTree as ET

sendUrl = "https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?"
token = "t=123456789123456789123456"
queryId = "&q=123456"
version = "&v=3"

requestUrl = "".join([requestBase, token, queryId, version])
flexReq = requests.get(url=requestUrl)

 

curl --request GET \
  --url "https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?t={{ AccessToken }}&q={{ QueryID }}&v=3" \
  --header "User-Agent: curl/7.81.0"

Success response from /SendRequest

Successful Response Values

Status.
A value of Success indicates a successful request to generate the report. If the request failed, Status will deliver Fail.

ReferenceCode.
If the request was successful, the XML response will contain this numeric reference code. This code will be used in the subsequent request to retrieve the generated Flex Query.

url.
This is the URL to be used in the subsequent request to retrieve the generated Flex Query.

<FlexStatementResponse timestamp="28 August, 2012 10:37 AM EDT">
    <Status>Success</Status>
    <ReferenceCode>1234567890</ReferenceCode>
    <url>https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/GetStatement</url>
</FlexStatementResponse>

Failure response from /SendRequest

Unsuccessful Response Values

Status.
A failed request will deliver a Status of Fail.

ErrorCode.
A numeric code indicating the nature of the failure. See Error Codes for a list of error code values and their descriptions.

ErrorMessage.
A human-readable description of the error. See Error Codes for a list of error code values and their descriptions.

<FlexStatementResponse timestamp="28 August, 2012 10:37 AM EDT">
    <Status>Fail</Status>
    <ErrorCode>1012</ErrorCode>
    <ErrorMessage>Token has expired.</ErrorMessage>
</FlexStatementResponse>

Retrieve the Report

Next, you’ll make a GET request to the /GetStatement endpoint, again passing your access token, but now passing the reference code obtained from the prior endpoint:

https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/GetStatement?t={{AccessToken}}&q={{ReferenceCode}}&v=3

Make request to /GetStatement

Query Params

t. Required
Accepts the Access Token created for the Flex Web Service in Client Portal’s Account Settings interface.

q. Required
Accepts the ReferenceCode returned by the previous successful request, which identifies the instance of the report to be retrieved. Note that a given Flex Query template can be used to generate multiple reports over time, each populated with data at the time of generation, so this ReferenceCode identifier is used to retrieve a specific instance, presumably the one generated immediately prior.

v. Required, leave value = 3
Specifies the version of the Flex Web Service to be used. Values 2 and 3 are supported, but version 3 should always be used.

if flexReq.status_code != 200:
  print("Error!")
  exit()
tree = ET.ElementTree(ET.fromstring(flexReq.content))
root = tree.getroot()
getURL = root.find('Url').text
refCode = "&q=%s" % root.find('ReferenceCode').text
receiveUrl = "".join([getURL, "?",token, refCode, version])

print("Hold for Request.")
time.sleep(20)

receiveUrl = requests.get(url=receiveUrl, allow_redirects=True)

open('C:\\flex_web_test.xml', 'wb').write(receiveUrl.content)
print("Done!")

 

curl --request GET \
     --url 'https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/GetStatement?t={{ AccessToken }}&q={{ ReferenceCode }}&v=3' \
     --header 'User-Agent: curl/7.81.0'

Success response from /GetStatement

A successful response will deliver your Flex Query report in binary XML.

Example Trade Confirmation Flex Query report:
<FlexQueryResponse queryName="Trades" type="AF">
    <FlexStatements count="1">
        <FlexStatement accountId="DU1234567" fromDate="20230829" toDate="20230927" period="Last30CalendarDays" whenGenerated="20230928;174413">
            <Trades>
                <Trade accountId="DU1234567" currency="USD" symbol="AAPL" conid="265598" listingExchange="NASDAQ" dateTime="20230829;101454" tradeDate="20230829" quantity="100" />
                <Trade accountId="DU1234567" currency="USD" symbol="AAPL" conid="265598" listingExchange="NASDAQ" dateTime="20230830;114005" tradeDate="20230830" quantity="10" />
                <Trade accountId="DU1234567" currency="USD" symbol="AAPL" conid="265598" listingExchange="NASDAQ" dateTime="20230905;103346" tradeDate="20230905" quantity="5" />
            </Trades>
        </FlexStatement>
    </FlexStatements>
</FlexQueryResponse>

Please consult our Reporting Guide for clarification of report fields.

Failure response from /GetStatement

Unsuccessful Response Values

Status.
A failed request will deliver a Status of Fail.

ErrorCode.
A numeric code indicating the nature of the failure. See Error Codes for a list of error code values and their descriptions.

ErrorMessage.
A human-readable description of the error. See Error Codes for a list of error code values and their descriptions.

<FlexStatementResponse timestamp="28 August, 2012 10:37 AM EDT">
    <Status>Fail</Status>
    <ErrorCode>1012</ErrorCode>
    <ErrorMessage>Token has expired.</ErrorMessage>
</FlexStatementResponse>

Error Codes

The following is a consolidated list of error codes returnable by the /SendRequest and /GetStatement endpoints when a server-side failure occurs.

ErrorCode ErrorMessage
1001 Statement could not be generated at this time. Please try again shortly.
1003 Statement is not available.
1004 Statement is incomplete at this time. Please try again shortly.
1005 Settlement data is not ready at this time. Please try again shortly.
1006 FIFO P/L data is not ready at this time. Please try again shortly.
1007 MTM P/L data is not ready at this time. Please try again shortly.
1008 MTM and FIFO P/L data is not ready at this time. Please try again shortly.
1009 The server is under heavy load. Statement could not be generated at this time. Please try again shortly.
1010 Legacy Flex Queries are no longer supported. Please convert over to Activity Flex.
1011 Service account is inactive.
1012 Token has expired.
1013 IP restriction.
1014 Query is invalid.
1015 Token is invalid.
1016 Account in invalid.
1017 Reference code is invalid.
1018 Too many requests have been made from this token. Please try again shortly.
Limited to one request per second, 10 requests per minute (per token).
1019 Statement generation in progress. Please try again shortly.
1020 Invalid request or unable to validate request.
1021 Statement could not be retrieved at this time. Please try again shortly.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.