How to Set Up IBKR Flex Queries: The Complete Guide for Traders
If you trade on Interactive Brokers, your broker already has every piece of data you need to build a serious trading journal. Every fill, every commission, every P/L calculation, every timestamp. It's all there.
The problem is getting it out. IBKR's default statements are clunky PDFs or pre-formatted HTML. They're designed for accountants, not traders. You can't filter by strategy, you can't track metrics over time, and you definitely can't pipe them into a journal automatically.
That's what Flex Queries solve. They let you define exactly what data you want, in what format, and pull it on demand or on a schedule. Once set up, you never manually export a trade again.
A Flex Query is a custom report template in IBKR that exports your trade data as structured XML. Setup takes about 10 minutes. Once configured, you can pull trade data automatically via the Flex Web Service API using a query ID and token.
What Is a Flex Query?
A Flex Query is IBKR's custom reporting system. Unlike the standard Activity Statement (which dumps everything into a fixed format), a Flex Query lets you choose:
- Which sections to include (trades, cash transactions, positions, etc.)
- Which fields within each section (symbol, P/L, commissions, dates, etc.)
- What date range to cover (last 7 days, last 30 days, custom range)
- What format to deliver it in (XML or CSV)
The result is a clean, structured data export that contains exactly what you need and nothing you don't. XML format is particularly useful because it preserves field names and data types, making it easy for software to parse automatically.
Activity Flex Query vs. Trade Confirmation Flex Query
IBKR offers two types of Flex Queries. Understanding the difference matters.
| Type | What It Contains | Best For |
|---|---|---|
| Activity Flex Query | Trades, positions, cash transactions, P/L, dividends, fees, transfers, and more | Trading journals (full picture) |
| Trade Confirmation Flex Query | Individual trade executions only | Execution-level analysis |
For journaling purposes, you want an Activity Flex Query. It includes realized P/L (calculated by IBKR using FIFO matching), commissions, open positions, and cash transactions. This is the complete picture.
Step-by-Step Setup
This process takes about 10 minutes. You only need to do it once.
Step 1: Open the Flex Query Page
Log into your IBKR account at Client Portal. Navigate to:
You'll see two sections: Activity Flex Queries and Trade Confirmation Flex Queries. We're working with Activity.
Step 2: Create a New Activity Flex Query
Click the +(plus) icon next to Activity Flex Queries to create a new one. Give it a clear name you'll recognize later.
Something like Trading Journal Export or Optimus Edge Sync. Avoid generic names like “Query 1” since you may create more Flex Queries later for tax or accounting purposes.
Step 3: Select Sections
IBKR will show you a list of data sections you can include. For a trading journal, you need at minimum:
- Trades (required) - every fill with P/L, commissions, and position details
- Cash Transactions (recommended) - deposits, withdrawals, dividend payments, fee adjustments
- Open Positions (recommended) - current holdings with unrealized P/L
Click each section name to open it. A popup appears showing all available fields for that section. You can also add Equity Summary for account value over time, but the three sections above cover what most traders need.
Step 4: Configure Trade Fields
This is the most important step. When you click into the Tradessection, IBKR shows a list of available fields. Select all of them if you're unsure. More data is better than less, and it doesn't affect performance.
The fields that matter most for journaling:
| Field | Why It Matters |
|---|---|
| symbol | The ticker. Required for everything. |
| dateTime | When the trade executed. Used for calendar views and time-of-day analysis. |
| assetCategory | STK, OPT, FUT, CASH, etc. Determines how the trade is categorized. |
| putCall | For options: P or C. Essential for options journal tracking. |
| strike | Options strike price. Needed to identify the specific contract. |
| expiry | Options expiration date. Needed to distinguish contracts. |
| buySell | BUY or SELL. Determines trade direction. |
| quantity | Number of shares or contracts. Used for position sizing analysis. |
| tradePrice | Execution price. Entry and exit levels. |
| fifoPnlRealized | IBKR's calculated realized P/L using FIFO matching. This is the number to trust. |
| ibCommission | Commission charged. Important for true net P/L. |
| closePrice | Market close price on the trade date. Used for unrealized P/L on open positions. |
Pro tip:select all fields. There's no penalty for including extra data, and you may need it later for features like spread detection or commission analysis. It's much easier to include everything now than to recreate the query later.
Step 5: Set the Date Range and Format
Under delivery configuration, you'll set the output format and time period:
- Format: Choose XML. Other options are CSV, Text (Pipe), and Text (Tab). XML is the structured format that trading tools can parse automatically. CSV works for spreadsheets but loses some data structure.
- Period: IBKR offers options like Last 365 Calendar Days, Last 30 Calendar Days, Month to Date, Year to Date, and more. Use Last 365 Calendar Days for your first sync to pull a full year of history. After that, Last 30 Calendar Days works for ongoing syncs.
Step 6: Review, Create, and Note Your Query ID
Click Continue to review your configuration, then Create to finalize. (If something looks off, click Back to revise.) IBKR will assign a Query ID(a numeric code). Copy it. You'll need it to pull data programmatically.
You can find the Query ID anytime by going back to the Flex Queries page. It's displayed next to each saved query. Note that saved Flex Queries cover data for the four previous calendar years plus the current year.
Setting Up Your Flex Web Service Token
The Query ID tells IBKR what data to pull. The token tells IBKR who is allowed to pull it. You need both.
How to Generate a Token
From the Flex Queries page, click Flex Web Service Configuration (or navigate to Performance & Reports → Flex Queries → Flex Web Service Configuration).
- Toggle the Flex Web Service Status to enable it
- Click Save. The status will show ACTIVE and a token will appear.
- Copy the token from Current Token Details
By default, the token expires after 6 hours, but you can set it to stay active for up to a year using the expiration dropdown. You can also restrict the token to specific IP addresses for extra security (optional).
Important:generating a new token invalidates the previous one. If you're already using the token in a trading journal or script, update it there immediately after regenerating.
Your Flex token is read-only. It can only pull reports. It cannot place orders, move money, or modify your account in any way. This is by design. IBKR's Flex Web Service is a reporting API, not a trading API.
Testing Your Flex Query
Before connecting anything, verify the query works:
- Go back to the Flex Queries page
- Click the run (play) icon next to your saved query
- IBKR will generate the report. This usually takes 10-30 seconds.
- Download the XML file and open it in a text editor
You should see structured XML with <Trade> nodes containing the fields you selected. Each trade is one node with attributes like symbol="AAPL", buySell="BUY", fifoPnlRealized="125.50".
If the file is empty or shows an error, check that the date range covers a period when you actually had trades. A query over a weekend with no positions will return an empty result.
Common Mistakes
These are the issues traders run into most often when setting up Flex Queries:
| Mistake | Symptom | Fix |
|---|---|---|
| Wrong query type | Missing P/L data, no position info | Use Activity Flex Query, not Trade Confirmation |
| Missing fields | Partial data, options trades without strike/expiry | Go back and select all fields in the Trades section |
| Token expired | API returns error code 1012. Default token lifetime is only 6 hours. | Generate a new token and set expiration to 1 year |
| Date range too short | Missing older trades | Set to 365 days for first sync, then use shorter windows |
| CSV instead of XML | Import tool can't parse the file | Change format to XML in query settings |
Why IBKR's P/L Numbers Are the Ones to Trust
One thing traders get wrong: trying to calculate their own P/L from entry and exit prices. This breaks immediately with options, spreads, partial fills, and FIFO lot matching.
IBKR's fifoPnlRealized field handles the P/L calculation correctly, and ibCommission tracks fees separately. Together they account for:
- FIFO matching when you have multiple lots at different prices
- Commissions and exchange fees (via
ibCommission) - Options assignment and exercise
- Corporate actions (splits, mergers)
- Currency conversion for multi-currency accounts
Always use your broker's realized P/L.It's the number your tax forms will match. It's the number your account balance reflects. Calculating your own introduces errors that compound over time and give you a false picture of your performance.
What to Do With Your Flex Query Data
Once your Flex Query is set up, you have three options for using the data:
The third option is what most traders end up with. The manual approach is fine for a one-time look, but nobody downloads and re-imports XML files every day for months. The script approach works if you're a developer, but you're building infrastructure instead of analyzing trades.
Optimus Edge connects directly to IBKR via your Flex Query token and query ID. Once you paste them into the Integrations page, every trade syncs automatically. You get 40+ metrics, strategy tagging, calendar views, and AI coaching on top of the raw data.
Quick Reference: The Full Setup Checklist
1. Log into IBKR Client Portal
2. Go to Performance & Reports → Flex Queries
3. Click the + icon to create a new Activity Flex Query
4. Name it (e.g., “Trading Journal Export”)
5. Add sections: Trades, Cash Transactions, Open Positions
6. Select all fields in each section
7. Set format to XML, period to Last 365 Calendar Days
8. Click Continue → Create, then copy the Query ID
9. Open Flex Web Service Configuration
10. Enable the service, set token expiration to 1 year, copy the token
11. Test by running the query manually with the play icon
That's it. Ten minutes of setup, and you never manually export a trade again. Your broker does the heavy lifting. All you need to do is review the data and find your edge.
Connect Your IBKR Account
Paste your Flex Query token and query ID into Optimus Edge. Trades sync automatically. Strategy breakdowns, 40+ metrics, and AI coaching included.
Get Started