How to Build an IBKR AI Trading Bot With Claude

Building an IBKR AI trading bot takes more than connecting an AI assistant to a brokerage account. A useful system needs trustworthy market data, explicit trading rules, secure account access, and safeguards that remain effective when the AI makes a mistake.

Claude can help interpret information, review trading signals, explain portfolio changes, and assist with development. Interactive Brokers provides the brokerage infrastructure and interfaces for account data and order execution. Your application connects those capabilities while controlling what the AI can actually do.

This guide explains how to create a Claude AI trading bot around Interactive Brokers, beginning with a read-only connection and progressing toward supervised paper trading.

It also distinguishes IBKR’s official AI integration from a custom Python trading application. These are different approaches with different permissions and responsibilities.

This article is for educational purposes, not personalized investment advice. Automated trading can lose money, and neither AI-generated analysis nor successful paper trading guarantees live results.

Related product: IBKR Trading Bot Hub – Automated Multi-Strategy Trading with Claude AI

Explore a Python source-code learning and development package covering a central trading hub, Interactive Brokers connectivity, multi-strategy examples, and optional Claude AI integration. Its 48-page technical reference covers setup, architecture, and troubleshooting, making it a closely related resource for studying the concepts in this guide.

This is a technical learning package, not a turnkey trading service. Independently review the code, disable startup order routines before any live use, and test in a verified paper-trading environment. No profitability is promised; third-party account, data, and API charges may apply.

1. What Is an IBKR AI Trading Bot?

An IBKR AI trading bot is software that combines Interactive Brokers connectivity with an AI-assisted workflow.

A typical system performs five jobs:

  1. Retrieves approved market and account data.
  2. Calculates signals using predefined strategy rules.
  3. Asks an AI model to interpret selected information.
  4. Checks proposed actions against independent risk limits.
  5. Records or submits approved orders through a brokerage interface.

The important distinction is between analysis and execution.

Claude might explain that a signal conflicts with an upcoming earnings event. Your application—not the model—should decide whether the event triggers a trading restriction.

Likewise, Claude should not invent account balances, assume buying power, or select unlimited position sizes.

The most practical first version is an AI-assisted trading workflow, not an unrestricted autonomous trader. Begin with a system that explains and logs decisions before allowing it to place even simulated orders.

2. Choose Between the Official Claude Integration and a Custom Bot

There are now two distinct ways to approach Interactive Brokers AI connectivity.

Option A: Use IBKR’s official AI integration

IBKR announced its direct Claude integration in June 2026 and subsequently expanded connectivity to additional tools supporting Model Context Protocol, or MCP.

The official integration supports account-aware analysis and the creation of trade instructions. Crucially, IBKR states that instructions do not automatically become orders: the client controls approval and submission.

This approach suits users who want conversational portfolio analysis and supervised trading without building their own execution service.

See IBKR’s AI integration overview and its announcement expanding MCP connectivity. Check current availability and supported actions for your account and region.

Option B: Build a custom Python application

A custom Interactive Brokers trading bot uses brokerage APIs alongside a separate Claude API connection.

You write the scheduling, strategy logic, risk checks, logging, and execution behavior.

This provides greater engineering flexibility but makes you responsible for preventing duplicate orders, handling outages, protecting credentials, and validating every proposed action.

The remaining steps focus on this custom route. Do not assume the official connector’s approval protections automatically apply to software you build yourself.

3. Design the Architecture Before Writing Trading Code

A reliable Claude trading bot separates responsibilities:

text
IBKR market and account data
             ↓
Data validation and strategy calculations
             ↓
Claude analysis of a restricted snapshot
             ↓
Schema validation and deterministic risk checks
             ↓
Human approval during initial testing
             ↓
Paper-trading execution adapter
             ↓
Order reconciliation, logs, and alerts

Each component should have a narrow purpose.

The data service checks timestamps and normalizes prices. The strategy calculates indicators. Claude supplies bounded interpretation. The risk service rejects unacceptable proposals. The execution adapter communicates with IBKR.

This separation makes failures easier to diagnose. A malformed AI response should not crash the brokerage connection or accidentally submit an order.

Start with one instrument, one strategy, and one decision schedule. A daily or hourly workflow is generally easier to inspect than a system reacting to every tick.

A language-model request should not sit inside a latency-critical execution loop. Model response times are variable, and an answer can arrive after its underlying market snapshot is obsolete.

4. Prepare Your Accounts and Development Environment

Before creating the bot, prepare:

  • An eligible Interactive Brokers account and paper-trading access.
  • Trader Workstation, or TWS, or IB Gateway.
  • The official TWS API distribution.
  • A compatible Python environment.
  • Claude API access for the custom application.
  • Appropriate market-data subscriptions and trading permissions.
  • Private storage for configuration, logs, and secrets.

Do not assume that a consumer Claude subscription includes API usage. Confirm current API billing separately.

For IBKR Python development, use a virtual environment and install the Python client from IBKR’s official API distribution following its current instructions. IBKR explicitly distinguishes its supported download from packages distributed through unrelated repositories.

The official TWS API documentation is the reference for installation, supported versions, and callbacks.

Keep dependencies pinned once your prototype works. An unreviewed upgrade immediately before a trading session can change behavior at the worst possible time.

Separate development, paper, and live configurations from the beginning.

5. Configure Interactive Brokers API Automated Trading Access

For the TWS API route, your application connects to a running TWS or IB Gateway session.

In TWS, locate the API settings and enable socket-client access as described in the current documentation.

Common default ports are:

Application Paper session Live session
TWS 7497 7496
IB Gateway 4002 4001

These ports are configurable. Always match your application to the actual session settings.

A port number is not proof that an account is a paper account. Verify the logged-in environment and returned account identity independently.

During initial development:

  • Keep the API in read-only mode.
  • Connect through localhost where possible.
  • Restrict network access.
  • Use a distinct client ID.
  • Enable useful API logging.

Only disable read-only mode after confirming that you are operating in the intended paper environment and have working order controls.

IBKR documents these settings in its TWS installation and configuration lesson.

Do you need IBKR API keys?

For this TWS socket connection, you authenticate through TWS or IB Gateway. You do not simply paste a generic “Interactive Brokers API key” into Python.

Other IBKR interfaces have different authentication arrangements. Follow the documentation for your chosen interface rather than combining incompatible setup instructions.

6. Test a Read-Only IBKR API Python Connection

The following connection check uses the official Python client. It waits for the API handshake and requests the broker’s current time.

It does not retrieve market data or submit trades.

python
        print("Broker timestamp:", timestamp)
        self.received_time.set()

    def error(self, *args):
        # Flexible for API-version differences.
        print("API message:", args)


app = ConnectionCheck()

try:
    # Confirm TWS is logged into your paper environment.
    app.connect("127.0.0.1", 7497, clientId=21)
    Thread(target=app.run, daemon=True).start()

    if not app.ready.wait(10):
        raise RuntimeError("API handshake timed out")

    app.reqCurrentTime()

    if not app.received_time.wait(10):
        raise RuntimeError("Broker time request timed out")
finally:
    app.disconnect()

Keep read-only mode enabled while running this example.

If it fails, check whether TWS is running, the socket port matches, socket clients are allowed, and another application is already using your chosen client ID.

A successful connection proves only that the application can communicate with the session. It does not prove trading permissions, data entitlements, or strategy correctness.

Next, implement account and position retrieval. Reject unexpected account identities before adding any order functionality.

7. Build a Trustworthy Market-Data Pipeline

A Python AI trading bot cannot compensate for stale or incorrectly interpreted prices.

For every market snapshot, store:

  • The resolved contract identifier.
  • Exchange and currency.
  • Price and volume fields.
  • Source timestamps and local receipt times.
  • Whether data is live, delayed, or frozen.
  • The applicable trading session.

Resolve instruments through contract details rather than relying solely on ticker text. Similar symbols can identify different listings or securities.

Keep delayed data clearly labeled. A live clock does not make a delayed quote current.

Market-data access also needs separate verification. Prices visible inside TWS are not necessarily available through the API under the same entitlement conditions. Consult IBKR’s market-data subscription documentation.

Add automatic rejection rules for missing values, impossible prices, crossed quotes where relevant, and excessive data age.

For historical research, handle splits, dividends, missing sessions, and timezone conversions consistently. Otherwise, an apparently attractive trading signal may simply reflect a data-processing error.

8. Define the Strategy Before Adding Claude

Start with a strategy that can be described without mentioning AI.

For example, an educational paper strategy might:

  • Evaluate one liquid ETF after each completed hourly bar.
  • Calculate short- and long-window moving averages.
  • Permit only long positions.
  • Consider an entry after a confirmed crossover.
  • Limit exposure using a fixed account-level rule.
  • Avoid opening another position while an entry order is pending.

This is a testable specification, not a claim that moving-average strategies are profitable.

Your program should compute indicators directly. Asking Claude to repeatedly calculate averages from raw prices creates unnecessary variability and cost.

Then assign Claude a limited role:

Review the supplied strategy snapshot for missing information and contradictions. Explain the signal and return either REVIEW or HOLD. Do not choose quantity, invent prices, or issue orders.

This makes trading with Claude AI easier to evaluate. You can compare the original rules-based strategy against an otherwise identical version using the AI review.

If Claude adds no measurable benefit, remove it from that part of the workflow.

9. Create the IBKR Claude Integration Layer

Your custom IBKR Claude integration should send a compact, sanitized snapshot to Claude.

Include only what the assigned task requires:

json
{
  "instrument": "EXAMPLE_ETF",
  "snapshot_age_seconds": 2,
  "data_status": "LIVE",
  "strategy_signal": "LONG_CANDIDATE",
  "current_position": 0,
  "pending_entry_order": false,
  "risk_checks_passed": true
}

This is an illustrative payload, not actual market data.

Define a response schema with fields such as:

  • decision: restricted to REVIEW or HOLD.
  • reason: a short explanation.
  • missing_data: a list of unavailable inputs.

Use supported structured outputs rather than relying solely on a prompt requesting JSON. Anthropic documents schema-constrained responses in its structured outputs guide.

Still validate the result locally. Valid JSON is not evidence of accurate financial reasoning.

If the request times out, the response is refused, or validation fails, record the event and take no new entry action.

Keep order placement unavailable to this analysis component. Its output is a review artifact, not an executable instruction.

10. Put Risk Controls Outside the AI Model

The most important part of an IBKR trading bot is the control layer that can say no.

Enforce limits through ordinary application code, including:

  • Allowed instruments and account identities.
  • Maximum order value and total exposure.
  • Position limits that include pending orders.
  • Buying-power and currency checks.
  • Trading-hours restrictions.
  • Maximum spread and data age.
  • Daily loss and drawdown thresholds.
  • Limits on order frequency.
  • Duplicate-intent detection.

Illustrative paper-testing limits might include one open position, no leverage, and a small maximum order notional. These are engineering examples, not suitable risk settings for every account.

Recheck risk immediately before submission. The account and market may have changed while Claude was responding.

A model’s self-reported confidence should never determine leverage or override a limit. Fluent reasoning is not a calibrated probability of profit.

Also distinguish stopping new entries from managing existing exposure. A daily-loss trigger should activate a predefined response rather than leaving the system’s behavior ambiguous.

Protective orders can help manage risk, but gaps, liquidity shortages, and execution conditions mean they cannot guarantee a maximum loss.

11. Implement a Paper-Only Order Lifecycle

After read-only testing, add an execution adapter restricted to the explicitly verified paper account.

Before calling the order-submission method:

  1. Resolve the instrument contract.
  2. Refresh account state and open orders.
  3. Validate the proposed quantity and price.
  4. Assign an internal trade-intent identifier.
  5. Persist the intent.
  6. Obtain approval during supervised testing.
  7. Submit once.
  8. Track broker acknowledgments and execution reports.

Order submission is not equivalent to a fill.

An order can be rejected, remain open, fill partially, or encounter a cancellation race. Your state machine must represent these outcomes.

Limit orders constrain acceptable execution prices but do not guarantee execution. Market orders prioritize execution without guaranteeing the final price.

After a network timeout, do not blindly resend. First reconcile broker orders, executions, and positions to establish what happened.

An internal identifier helps detect duplicates, but it does not by itself make broker submission idempotent. Durable records and reconciliation are still necessary.

This is where Interactive Brokers API automated trading becomes an ongoing state-management problem, not merely an API call.

12. Backtest Without Giving the AI Future Information

Backtesting should answer whether the strategy has evidence behind it—not whether a convincing chart can be produced.

Include:

  • Commissions and relevant fees.
  • Bid-ask spreads.
  • Plausible slippage.
  • Delayed execution assumptions.
  • Corporate actions.
  • Out-of-sample periods.
  • Turnover and capital constraints.

Compare your results with a relevant baseline and with the same strategy operating without Claude.

LLM-assisted historical tests require extra caution. A model may already know events that happened after the date of your simulated decision. Restricting the prompt to historical inputs does not necessarily remove that knowledge.

This can contaminate tests involving company news, earnings, or major market events.

Forward paper testing provides a cleaner check of how the system behaves using information genuinely available at decision time.

Freeze prompts, model versions where supported, and strategy settings during each evaluation period. Repeatedly tuning them against the same test sample encourages overfitting.

Measure drawdown, risk-adjusted returns, and operational errors—not only win rate.

13. Test Failures, Not Just Successful Trades

A paper account is also a place to rehearse breakdowns.

Test what happens when:

  • Claude is unavailable.
  • Market data stops updating.
  • TWS disconnects.
  • The process restarts with an open order.
  • An order fills partially.
  • A cancellation is rejected.
  • Two scheduled evaluations overlap.
  • The broker rejects an instrument or quantity.

Each case should produce a predictable, logged response.

Paper fills are simulated and may differ materially from live execution, especially in thin markets or during volatility.

Run the system across enough decisions and operating conditions to examine reliability. A handful of profitable trades is not meaningful validation.

Before considering live use, require successful reconciliation after restarts, consistent account checks, a tested shutdown procedure, and no unexplained duplicate orders.

When uncertainty remains about broker state, stop new entries and alert the operator rather than guessing.

14. Is It Safe to Connect Claude to IBKR?

Safety depends on the connection method, granted permissions, software quality, and operational controls.

For the official integration, use IBKR’s documented authorization flow and review what information and actions the connector exposes. IBKR states that its MCP integration authenticates through IBKR without passing brokerage login credentials to the AI platform.

For a custom application:

  • Store Claude credentials in a secret manager or protected environment variables.
  • Never include brokerage passwords in prompts.
  • Send only necessary account information.
  • Keep brokerage services off the public internet.
  • Review dependencies and third-party MCP servers.
  • Separate analysis permissions from execution permissions.
  • Maintain a manual shutdown path.

Treat news articles and retrieved webpages as untrusted data. They may contain text attempting to redirect the model or invoke tools.

A safe design does not let external content rewrite strategy rules or expand permissions.

Read-only access reduces execution risk, but portfolio information can still be sensitive. Review retention, logging, access controls, and applicable provider terms before sharing account data.

15. Monitor Costs and Live Operating Behavior

An IBKR AI workflow has several potential costs: market data, commissions, exchange charges, Claude API usage, hosting, storage, and maintenance.

TWS API access is generally provided without a separate API access charge, but that does not make the complete trading system free. Confirm current account conditions and pricing directly with IBKR.

Control model costs by calculating indicators locally, sending concise snapshots, and calling Claude only when its assigned task requires analysis.

Create a monitoring dashboard showing:

  • Connection and data status.
  • Last successful strategy evaluation.
  • Current positions and pending orders.
  • Realized and unrealized P&L.
  • Risk-limit usage.
  • Model failures and response latency.
  • Reconciliation warnings.

Alert on account mismatches, repeated rejections, stale data, unexpected exposure, and restarts.

A kill switch should stop new submissions immediately. Define separately whether it cancels pending orders or closes positions; those actions have different consequences.

Never deploy the application somewhere you cannot reliably monitor or disable it.

16. Frequently Asked Questions

Can a Claude trading bot trade automatically?

A custom application can connect Claude-assisted analysis to programmatic brokerage execution. That capability comes from your application and its permissions, not from Claude alone.

IBKR’s official AI integration follows a different workflow in which trade instructions require client approval.

Is IBKR autonomous trading a good starting point?

No. Begin with read-only analysis, then supervised paper trading. Expand automation only after testing execution handling, independent risk checks, and recovery procedures.

Autonomy is an engineering choice, not evidence of better returns.

Can I build this without Python?

The official integration offers a route to conversational account analysis without developing a Python execution service.

For custom automation, other supported API languages and third-party tools may be options. Evaluate their maintenance, permissions, and actual safeguards before relying on them.

Does an AI trading bot need machine learning?

Not necessarily. A rules-based strategy can use Claude for explanation, information extraction, or review. Adding a language model does not automatically make the underlying signal predictive.

Is an “Interactive Brokers AI hub” the same as a bot?

Not necessarily. The phrase may refer to a dashboard, integration directory, or third-party service. Verify the provider and distinguish analysis tools from software authorized to submit orders.

Conclusion: Build Controls Before Autonomy

Creating an IBKR AI trading bot with Claude is best approached as a sequence of controlled engineering steps.

Establish a read-only connection, validate market data, define a testable strategy, and give Claude a narrow analytical role. Add independent risk controls before implementing paper orders, then test outages and reconciliation as carefully as trading signals.

The strongest system is not the one that gives AI the most freedom. It is the one that remains observable, predictable, and controllable when its assumptions fail.

Back to blog