Interactive Brokers Flex Queries are a hidden superpower. Most traders have no idea they exist. Those who discover them unlock a level of portfolio tracking and analysis that separates professionals from amateurs.
A Flex Query is basically a customizable export tool that pulls granular data from your IBKR account—every trade, every assignment, every dividend, every cash transaction—and outputs it to CSV. Once you have that data, you can analyze it, feed it into dashboards, calculate true returns, identify tax issues, and optimize ruthlessly.
This guide shows you how to set up Flex Queries and use them to transform your portfolio data into actionable intelligence.
What is a Flex Query?
A Flex Query is an automated report generator. You configure it once (specifying which data fields you want, what date range, etc.), and IBKR generates the report and either:
- Sends it to you via email on a schedule (daily, weekly, monthly)
- Makes it available for download from your account portal
- Exposes it via API so you can pull it programmatically
Most traders use option 1 or 2. Advanced traders use the API to feed data directly into dashboards.
Setting Up Your First Flex Query
Step 1: Navigate to Flex Queries
- Log into your IBKR account
- Go to: Reports > Flex Queries
- Click "Create a Query"
Step 2: Name and Configure Your Query
Give it a name: Monthly Portfolio Activity or Weekly Trades
Choose query frequency:
- On-demand: You request it manually whenever you want
- Scheduled: Daily, weekly, or monthly (most useful)
Set date range:
- Current quarter
- Custom date range
- Or leave open to query always-current data
Step 3: Select Sections
Flex Queries have multiple sections. Start with these essentials:
| Section | What You Get | Why It Matters |
|---|---|---|
| Trades | Every trade executed (buy/sell) | Understand entry prices, fills, commissions |
| Cash Transactions | Deposits, withdrawals, interest | Track capital in/out and cash drain |
| Dividends | All dividend payments received | Reconcile income, identify dividend captures |
| Option Exercises | Assignment and exercise records | Know exactly when/how positions were assigned |
| Corporate Actions | Stock splits, mergers, conversions | Understand historical position changes |
| Positions | End-of-period holdings | Verify account statement accuracy |
Step 4: Select Columns (Choose Wisely)
Each section has many available columns. You don't need all of them. Select the essentials:
For Trades:
- Date/Time
- Symbol
- Quantity
- Price
- Commission
- Order Type (BUY/SELL/EXERCISE/ASSIGNMENT)
- T+0 P&L (profit or loss on execution)
For Cash Transactions:
- Date
- Type (DEPOSIT, WIRE, INTEREST, etc.)
- Amount
- Description
For Options Exercises:
- Date
- Symbol
- Quantity
- Strike Price
- Underlying Price
- Assignment/Exercise Type
Step 5: Create and Download
Click "Create" and IBKR generates the report. Download as CSV and you're ready to analyze.
Common Flex Query Setups
Setup 1: Weekly Trade Review
Purpose: Analyze every trade for quality and consistency
Sections:
- Trades (all columns)
- Positions (symbol, quantity, price, P&L)
- Cash transactions
Frequency: Weekly How to use:
- Import to spreadsheet
- Calculate average price paid vs. filled price (slippage)
- Count wins vs. losses
- Identify best and worst performing positions
- Review commission costs
Setup 2: Monthly Performance Report
Purpose: Understand true return accounting for all cash flows
Sections:
- Trades
- Cash transactions
- Dividends
- Positions
Frequency: Monthly How to use:
- Calculate net cash flow (deposits - withdrawals)
- Calculate portfolio return (ending value + withdrawals - deposits - beginning value) ÷ beginning value
- Calculate Sharpe ratio or other metrics
- Identify best and worst performing positions
- Compare actual return to target
Setup 3: Assignment Tracking
Purpose: Understand your assignment patterns and costs
Sections:
- Option exercises (all columns)
- Trades filtered to assignment-related trades
- Positions
Frequency: Monthly or on-demand How to use:
- Count assignments by strategy (covered calls vs. puts)
- Identify which underlyings get assigned most (hints at bid-ask manipulation)
- Calculate effective fill prices after assignment
- Plan cash requirements for next period
Setup 4: Tax Reporting
Purpose: Export all data needed for tax calculation and wash sale detection
Sections:
- Trades
- Dividends
- Fees
- Interest
- Corporate actions
- Option exercises
Frequency: Annual or quarterly How to use:
- Feed to tax software (TaxTracks, GruntWorx, etc.)
- Manually calculate short-term vs. long-term gains
- Identify wash sale transactions
- Calculate cost basis adjustments
Analyzing Flex Query Data: Practical Examples
Example 1: Understanding Slippage
Your Flex Query shows:
Date | Symbol | Qty | Order Price | Fill Price | Commission
1/15 | VTSAX | 100 | $145.50 | $145.52 | $0.65
1/18 | VTSAX | 100 | $146.00 | $146.02 | $0.65
1/20 | VTI | 100 | $210.00 | $210.05 | $0.65
Analysis:
- Slippage: $0.02–$0.05 per share (market orders in liquid stocks)
- Commission: $0.65 per trade
- Total cost per trade: $1.65–$5.65 (0.01–0.03% of position value)
- Insight: Your execution is efficient. Interactive Brokers' pricing is competitive.
Example 2: Assignment Pattern Detection
Your Flex Query shows assignments:
Date | Symbol | Type | Strike | Qty | Underlying Price | Dividend?
1/31 | VTSAX | Assignment | $148 | 100 | $147.02 | Yes (ex-div 1/30)
2/15 | VTI | Assignment | $220 | 200 | $220.50 | No
3/10 | SPY | Assignment | $450 | 50 | $449.95 | No
Analysis:
- 1/31 assignment coincided with ex-dividend (dividend capture)
- Other assignments were at/near strikes (normal)
- Insight: Watch for ex-dividend dates on short calls; plan for early assignment
Example 3: Return Attribution
Your Flex Query shows (monthly):
Beginning Portfolio Value: $100,000
Deposits: $5,000
Withdrawals: $0
Realized Gains/Losses: +$450
Unrealized Gains/Losses: +$1,200
Dividends: $120
Interest: $15
Ending Portfolio Value: $106,785
Calculation:
Simple Return = (Ending - Beginning - Deposits + Withdrawals) / Beginning
= ($106,785 - $100,000 - $5,000) / $100,000
= $1,785 / $100,000
= 1.785% for the month
Annualized: 1.785% × 12 = ~21.4% annualized
This is your true return, accounting for all cash flows and timing.
Example 4: Tax Planning
Your Flex Query shows (YTD):
Short-term Capital Gains: +$3,200
Long-term Capital Gains: +$1,500
Wash Sales Identified: 3 transactions (must adjust cost basis)
Dividend Income: +$1,200
Interest Income: +$45
Total Taxable Income: ~$6,000 (estimated taxes: ~$1,500–$2,000 depending on bracket)
Insight: You're on track for a $1,500–$2,000 tax bill by year-end. Plan quarterly estimated taxes or adjust trading size.
Flex Queries + Python: Automating Analysis
Once you've mastered the manual export, consider automating. The IBKR Flex Query API lets you pull data programmatically.
Basic Python workflow:
import requests
import pandas as pd
# Set up your query (get token from IBKR)
query_id = 123456 # Your query ID
token = "YOUR_API_TOKEN"
# Pull data from IBKR API
url = f"https://flex.interactivebrokers.com/data/{query_id}/{token}"
response = requests.get(url)
# Parse as DataFrame
df = pd.read_csv(pd.StringIO(response.text))
# Analyze
total_trades = len(df[df['Type'] == 'Trade'])
avg_slippage = df['Slippage'].mean()
realized_pl = df['RealizationPrice - Strike'].sum()
print(f"Total trades: {total_trades}")
print(f"Average slippage: ${avg_slippage:.4f}")
print(f"Realized P&L: ${realized_pl:.2f}")
Once automated, you can:
- Run daily analysis
- Feed into your dashboard
- Generate alerts (e.g., "Slippage exceeding 5 cents")
- Calculate metrics on schedule
For non-technical traders, the manual export is sufficient. For serious traders tracking 50+ positions, automation becomes valuable.
Troubleshooting Flex Queries
Issue: Flex Query Not Available
Requirement: Professional subscription (higher IB account tier)
- Comes automatically with active trader status (18+ trades/month, $130K AUM)
- Can upgrade manually in Account Settings if you have the balance
Issue: Data Not Matching Account Statement
Common causes:
- Different date ranges (Flex Query might be querying previous month)
- Pending transactions (not settled yet)
- Rounding differences (usually less than $1)
Solution: Compare dates carefully; ensure both are querying same time period.
Issue: API Token Expired
If using programmatic access, tokens expire after 180 days.
Solution: Regenerate token in IBKR Account Settings, then go to API Tokens
Issue: Too Much Data to Analyze
If your query returns 10,000+ rows, it's unmanageable by hand.
Solution: Use Python/Excel to:
- Filter to specific symbols
- Aggregate by strategy
- Calculate summary statistics
Best Practices for Flex Query Success
Run Queries Consistently (1)
Set a weekly or monthly schedule. Consistency helps you spot trends (e.g., "My average slippage has improved 2 cents over 3 months").
Compare to Targets (2)
After each query, ask:
- Am I trading more/less than planned?
- Are my fills better or worse than expected?
- Is my commission as low as I targeted?
- Is my return tracking to goal?
Archive Historical Data (3)
Keep queries from previous months/years. This lets you:
- Identify seasonal patterns
- Compare long-term performance
- Track improvement over time
Use for Accountability (4)
Share Flex Query summaries with yourself monthly. If you're not hitting targets, data makes it obvious.
Integrate into Your Dashboard (5)
Don't just download Flex Queries; feed them into your trading dashboard or spreadsheet. Automate your analysis.
The Bottom Line
Interactive Brokers Flex Queries are the missing link between your broker's platform and serious portfolio analysis. Most traders don't use them and stay blind to important patterns. Those who do use them transform raw trade data into actionable insights.
Spend an hour setting up your first Flex Query. Download it. Import to Excel. Calculate your true return and slippage. The clarity will immediately show you opportunities for improvement. That's worth far more than the effort to set it up.