Miles Free AI Library
← Back to resources
GuideMiles FinanceSep 9, 2026

Build a Claude Portfolio Assistant for Interactive Brokers

Connect live account data for risk analysis, policy checks, Telegram reports and alerts, plus manually confirmed paper trades through Trader Workstation.

Get the full MD

Download the complete portfolio assistant tutorial

Free
Download MD

Build a Claude Portfolio Assistant for Interactive Brokers

Connect live portfolio data, add mobile access through Telegram, and safely test trade execution with a paper account.

What you will achieve

You will build a layered assistant that can inspect an Interactive Brokers portfolio, answer risk and performance questions, send alerts and reports to Telegram, and optionally submit test orders through Trader Workstation.

Who this is for

Investors and traders who use Interactive Brokers and want AI assisted portfolio analysis, monitoring, and experimental execution while retaining control over investment decisions.

Difficulty: Advanced

Short tutorial

Connect live portfolio data, add mobile access through Telegram, and safely test trade execution with a paper account.

Guide: Build a Claude Portfolio Assistant for Interactive Brokers

Time: 45 to 90 minutes for setup, plus additio

What you will build

This tutorial creates the infrastructure connecting Claude, Interactive Brokers, and optionally Telegram. The recommended approach is to keep all investment decisions discretionary while delegating portfolio queries, reporting, alerts, and routine order preparation to the assistant.

Build the system in layers. Complete the read only connection first. Add paper trade execution only after validating the analysis layer. Telegram can then provide mobile access to either version.

Important: Trade execution through an AI assistant is experimental and can produce incorrect results. Start with an Interactive Brokers paper trading account. Keep manual confirmation enabled, verify the connected account before every order, and continue handling large transactions manually.

Architecture

LayerComponentsCapabilityRecommended use
Portfolio analysisClaude plus the Interactive Brokers connectorReads positions, cash, margin, profit and loss, transactions, and exposureStart here
Paper executionClaude Code, Python, and Trader WorkstationReads the account and submits paper ordersAdd after validating analysis
Mobile interfaceTelegram bot plus an always available computerSends requests to Claude and returns results to your phoneAdd to either setup
MonitoringScheduled Claude tasks plus TelegramSends reports and movement alertsAdd after mobile access works

1. Create a dedicated project folder

Keep the configuration, prompts, and portfolio goals in one local folder that Claude Code can access.

Suggested structure:

TEXT
ibkr-assistant/
  PORTFOLIO_POLICY.md
  prompts/
    analysis-prompts.md
    alert-prompts.md
  bot/
  logs/

Do not place passwords, broker credentials, or Telegram tokens in the portfolio policy file.

2. Connect Claude to Interactive Brokers in read only mode

Use the Interactive Brokers connector or MCP connection available for your account. Availability can vary, so confirm the current capabilities inside your brokerage account.

The authorization flow described in the source is:

  1. Open the Interactive Brokers connection or authorization address in Claude Code.
  2. Sign in through the broker's own login page.
  3. Authorize the requested connection.
  4. Copy the returned authorization code, if one is provided.
  5. Give that code back to Claude Code to finish the connection.
  6. Confirm that the connection is read only.

Use this prompt after authorization:

TEXT
Connect to my selected Interactive Brokers account using the authorized connector.

Before performing any analysis:
1. Tell me the account identifier you are connected to.
2. Confirm whether the connection is read only.
3. Retrieve the account summary and open positions.
4. Report cash, margin, total account value, unrealized profit and loss, and major risk exposures.
5. Do not create or submit any order.

If any requested field is unavailable, identify the missing field instead of estimating it.

Validate the connection

Confirm that Claude can retrieve:

  • The intended account identifier
  • Current positions and quantities
  • Cash and available buying capacity
  • Margin information, if applicable
  • Realized and unrealized profit and loss
  • Transaction history
  • Currency and market exposure

If the account identifier is wrong, stop before continuing.

3. Add your portfolio policy as persistent context

Claude can compare your live account against your goals more effectively when those goals are stored in a local Markdown file.

First, use this interview prompt:

TEXT
Help me define a portfolio policy that can be saved as PORTFOLIO_POLICY.md.

Interview me about:
1. My financial situation and investment horizon.
2. My risk tolerance.
3. My maximum acceptable drawdown.
4. My desired asset allocation.
5. My maximum exposure to one company, sector, country, or currency.
6. My desired domestic and foreign exposure.
7. My liquidity needs and minimum cash reserve.
8. The conditions under which I normally add to, reduce, or exit a position.

Ask one focused group of questions at a time. Do not recommend trades during the interview.

When the interview is complete, produce a concise Markdown policy with explicit percentages, limits, and any unresolved decisions clearly marked.

A useful policy file can follow this template:

MARKDOWN
# Portfolio Policy

## Objectives

Primary objective:
Investment horizon:
Liquidity requirements:

## Risk Limits

Maximum acceptable drawdown:
Maximum single position exposure:
Maximum sector exposure:
Maximum country exposure:
Minimum cash reserve:

## Allocation Targets

Domestic equities:
Foreign equities:
Fixed income:
Commodities:
Cash:
Other:

## Currency Targets

Base currency:
Maximum unhedged foreign currency exposure:

## Decision Rules

Conditions for adding to a position:
Conditions for reducing a position:
Conditions for exiting a position:
Transactions that always require manual review:

## Current Unresolved Decisions

1.
2.

Tell Claude Code to load this file before portfolio reviews:

TEXT
Read PORTFOLIO_POLICY.md and treat it as my portfolio evaluation framework.

Compare the live Interactive Brokers account against the stated targets and limits. Separate factual account data from interpretation. Highlight breaches and material deviations, but do not submit orders or assume that a deviation should automatically be corrected.

4. Run practical portfolio analysis

Save the following prompts in prompts/analysis-prompts.md or use them directly.

Account snapshot

TEXT
Give me a current portfolio snapshot using live account data.

Include:
1. Total account value.
2. Cash and available buying capacity.
3. Realized and unrealized profit and loss.
4. My five largest positions by portfolio weight.
5. Sector, country, and currency concentration.
6. Any breach of PORTFOLIO_POLICY.md.

Show the source account identifier and retrieval time. Do not estimate unavailable values.

Monthly trading review

TEXT
Summarize all trades from the last calendar month.

Calculate, where the account data supports it:
1. Number of trades.
2. Total commissions paid.
3. Realized profit and loss.
4. Win rate for closed trades.
5. Average trade size.
6. Largest gain and largest loss.
7. Turnover by position.

Explain any calculation that depends on incomplete trade history. Do not infer missing transactions.

Concentration review

TEXT
Analyze my current concentration risk.

Break down the portfolio by:
1. Company.
2. Sector.
3. Country or market.
4. Currency.
5. Asset class, where identifiable.

Compare the results with PORTFOLIO_POLICY.md. Rank the three largest concentration risks and explain which live positions create each risk. Do not recommend or execute trades unless I ask separately.

Currency stress test

TEXT
Using my current positions, estimate the portfolio impact if the US dollar weakens by 10 percent against my largest foreign currency exposures.

State:
1. Which currencies and positions are included.
2. Any assumptions required.
3. Estimated impact by currency.
4. Estimated total portfolio impact.
5. Whether the resulting exposure breaches PORTFOLIO_POLICY.md.

Keep estimates clearly separated from live account values.

Opportunity cost review

TEXT
Review my portfolio performance over the last 12 months using the available account history.

Identify:
1. Positions that contributed most to returns.
2. Positions that detracted most from returns.
3. Capital that remained unused for material periods.
4. Concentration that increased drawdown.
5. Plausible allocation changes that would have improved the historical result.

Treat this as retrospective analysis, not proof that the same allocation will work in the future. Do not submit orders.

Additional market data connectors can be added for cross referencing fundamentals and earnings information. Keep broker account data and external market data clearly labeled so you know which source supports each conclusion.

5. Prepare Trader Workstation for paper execution

Skip this section if you only want analysis and alerts.

Install Interactive Brokers Trader Workstation on the machine that will run the assistant. Sign in to a paper trading account, not a live account.

In the Trader Workstation API settings:

  1. Enable connections from external programs.
  2. Check the read only setting. Turning read only off allows connected software to place orders.
  3. Restrict connections to the current device.
  4. Keep order confirmation enabled during testing.
  5. Configure the workstation to restart daily if you intend to keep it running continuously.
  6. Record the displayed API socket port.
  7. Verify that the port belongs to the paper account, since paper and live ports may differ.

Use this checklist before connecting:

TEXT
[ ] Trader Workstation is running
[ ] I am signed in to the paper trading account
[ ] External API connections are enabled
[ ] I recorded the displayed socket port
[ ] The connection is restricted to this device
[ ] Manual order confirmation remains enabled
[ ] I know the paper account identifier

6. Connect Claude Code to Trader Workstation

Replace [SOCKET_PORT] with the value displayed in Trader Workstation.

TEXT
I have Interactive Brokers Trader Workstation running and logged into my paper trading account.

API access is enabled. The socket port is [SOCKET_PORT]. Read only access has been turned off so the paper account can accept test orders. Manual order confirmation should remain enabled.

Please complete the following steps:
1. Check whether Python is installed on this machine.
2. If Python is missing, explain what must be installed before continuing.
3. Create an isolated Python environment inside this project folder.
4. Select a compatible Python library for the Trader Workstation API and tell me which library you selected.
5. Connect to Trader Workstation through the stated socket port.
6. Pull my account summary and open positions.
7. Tell me the connected account identifier before doing anything else.
8. Confirm explicitly that it is a paper trading account.
9. Do not submit an order during this connection test.

If the account type or identifier cannot be verified, stop and ask me to inspect Trader Workstation.

The two most important checks are the connected account identifier and confirmation that it is the paper account.

Test an order safely

Use a small paper order and state every important parameter explicitly.

TEXT
Prepare a paper trade for review. Do not submit it until I confirm.

Account: [PAPER_ACCOUNT_ID]
Symbol: [SYMBOL]
Action: BUY or SELL
Quantity: [QUANTITY]
Order type: [MARKET OR LIMIT]
Limit price, if applicable: [PRICE]
Time in force: [VALUE]

Before submission, repeat:
1. The connected account identifier.
2. Whether it is a paper account.
3. Symbol and instrument description.
4. Buy or sell action.
5. Quantity.
6. Order type and price.
7. Estimated order value.

Wait for my explicit confirmation after presenting the complete order summary.

After submission, ask for a status report:

TEXT
Report the status of the paper order I just confirmed.

Include the order identifier, account identifier, symbol, quantity, order type, submitted price, fill price, filled quantity, remaining quantity, commissions if available, and final status. Do not place a replacement order unless I explicitly request one.

7. Add Telegram as the mobile interface

Telegram acts as a bridge. The broker connection, project files, and Claude context remain on the computer.

Use a separate computer when possible. It does not need powerful hardware, but it must remain on with Trader Workstation and the assistant process running. A remote server can also fill this role, although the source recommends keeping the trading environment separate from your everyday computer.

Secure the machine first

  • Use a strong computer password.
  • Enable two factor authentication on Interactive Brokers.
  • Enable two factor authentication on Telegram.
  • Treat the Telegram bot token as a password.
  • Do not share the token in messages or screenshots.
  • Keep manual trade confirmation enabled while experimenting.
Copy
Create a Telegram bot through BotFather and copy the resulting token. Give the token only to the setup process on the dedicated machine.

Then use this build prompt:

TEXT
Add a Telegram interface to this Interactive Brokers assistant.

The Telegram bot should:
1. Listen for text messages sent to the bot.
2. Pass each message to the Claude Code workflow in this project.
3. Return the response to Telegram.
4. Preserve access to PORTFOLIO_POLICY.md and the existing broker connection.
5. Support portfolio queries without requiring Trader Workstation execution.
6. For any trade request, show a complete order summary and wait for explicit confirmation before submission.
7. State the connected broker account identifier in every order confirmation.
8. Refuse execution if the account identifier or account type cannot be verified.
9. Record request time, response time, and order status in a local log without exposing the Telegram token.
10. Reconnect cleanly after Trader Workstation performs its daily restart.

Ask me for the Telegram bot token only when it is required. Treat it as a secret and do not include it in normal output or logs.

First implement and test a read only command that returns my account value and open positions. Do not test order execution yet.

If you want voice messages, ask Claude Code to add local speech transcription using Whisper. Alternatively, transcribe speech to text on the phone before sending it to Telegram.

8. Add reports and alerts

Start with notifications, not automated trading rules. Alerts preserve your discretion while reducing the chance that you miss a material portfolio move.

Morning portfolio report

TEXT
Create a scheduled morning portfolio report and send it to my Telegram bot.

For each report:
1. Verify and display the connected account identifier.
2. Show total account value, cash, margin, and daily profit and loss.
3. Summarize material overnight changes.
4. List the largest positive and negative position moves.
5. Flag breaches of PORTFOLIO_POLICY.md.
6. Separate live broker data from external market context.
7. Do not submit orders.

If the broker connection is unavailable, send an error notification instead of using stale values.

Large movement alert

TEXT
Monitor my current positions and message me on Telegram if any position falls more than 3 percent during a single trading day.

The alert must include:
1. Account identifier.
2. Symbol and position size.
3. Current price and percentage move.
4. Unrealized profit or loss impact.
5. Current portfolio weight.
6. Whether the move creates a breach of PORTFOLIO_POLICY.md.

This is an alert only. Do not create, prepare, or submit an order automatically.

9. Use a conservative operating policy

Before leaving the system running, apply these rules:

TEXT
Operating rules for this project:

1. Investment selection remains my decision.
2. Default to analysis only.
3. Never infer missing symbols, quantities, prices, or account identifiers.
4. Never submit an order when the connected account cannot be verified.
5. Require an explicit order summary and my confirmation before execution.
6. Keep large transactions under manual control.
7. Use the paper account for all new workflows and strategy experiments.
8. Clearly distinguish live broker data, external data, assumptions, and estimates.
9. If instructions conflict or are ambiguous, stop and ask for clarification.
10. Do not convert alerts into automatic trades.

Final verification checklist

Before relying on the assistant, confirm:

TEXT
[ ] Read only portfolio queries return the correct account
[ ] Cash, positions, and profit and loss match Interactive Brokers
[ ] PORTFOLIO_POLICY.md contains explicit risk limits
[ ] Trader Workstation connects only to the intended device
[ ] The recorded socket port belongs to the paper account
[ ] Manual order confirmation is enabled
[ ] A small paper order completed correctly
[ ] Telegram returns read only account information
[ ] Telegram and broker accounts use two factor authentication
[ ] The bot token is protected
[ ] Alerts do not submit orders
[ ] Scheduled reports handle connection failures without inventing values

The most useful version of this system is often the conservative one: live portfolio analysis, policy checks, scheduled reporting, movement alerts, and manually confirmed paper orders. Move beyond that only after extensive forward testing and account verification.

Continue exploring

What to watch next