ibkr-mcp
Server Configuration
Describes the environment variables required to run the server.
| Name | Required | Description | Default |
|---|---|---|---|
| IB_HOST | No | TWS/Gateway host. | 127.0.0.1 |
| IB_MODE | No | paper or live. | paper |
| IB_PORT | No | API port. | 4002 (paper) / 4001 (live) |
| LOG_LEVEL | No | debug, info, warn, error. | info |
| IB_CLIENT_ID | No | Client ID. | 1 |
| IB_READ_ONLY | No | Block all order mutations. | true |
| IB_ACCOUNT_ID | No | Account ID override. Default: auto. | |
| RISK_MAX_ORDER_QTY | No | Max shares/contracts per order. | 1000 |
| RISK_SYMBOL_DENYLIST | No | Block these symbols. Default: none. | |
| RISK_DAILY_LOSS_LIMIT | No | Daily loss limit ($). | 10000 |
| RISK_SYMBOL_ALLOWLIST | No | Only allow these symbols. Default: none. | |
| RISK_ALLOW_OUTSIDE_RTH | No | Allow outside-hours orders. | false |
| RISK_MAX_ORDER_NOTIONAL | No | Max order notional ($). | 100000 |
| RISK_ALLOWED_ORDER_TYPES | No | Allowed order types. | MKT,LMT,STP,STP_LMT,TRAIL |
Instructions
Guidance the server publishes about itself, which clients place ahead of the tool catalog so the model reads it before choosing anything.
IBKR MCP Server — Agent Instructions
You are connected to a production-grade MCP server that interfaces with Interactive Brokers (IB Gateway / TWS). Follow these guidelines carefully.
Workflow Rules
Always qualify contracts first. Before requesting market data, placing orders, or any operation that needs a contract, call
contract_qualifyorcontract_searchto get a validconId. Never guess contract IDs.Use
order_previewbeforeorder_place. Always preview orders to verify commission, margin impact, and price before submitting. This is especially important for options and futures.Respect guardrails. The server enforces risk guardrails:
Read-only mode blocks all order mutations
Maximum order quantity and notional limits
Allowed order types whitelist
Symbol allowlist/denylist
Outside-RTH restrictions
Daily loss limits If a guardrail blocks your action, explain to the user what limit was hit and suggest alternatives.
Handle streaming subscriptions carefully.
Always unsubscribe when data is no longer needed
Use
subscriptions_listto see active subscriptionsIB limits the number of concurrent market data lines (typically 100)
Check connection before operations. If you get connection errors, call
connection_statusto diagnose. The server handles reconnection automatically, but operations during reconnection will fail.
Tool Categories
Contract/Instrument Tools
contract_search— Find instruments by name/symbolcontract_qualify— Qualify partial contract → full conId (REQUIRED before use)contract_details— Full specs, trading hours, min tickcontract_rules— Trading rules and order type supportoption_chain— Full option chain for an underlyingsecurity_definitions_option_parameters— Available expirations and strikes
Market Data Tools
market_data_snapshot— Point-in-time quote (bidprice, ask, last, volume)market_data_bulk_snapshot— Multiple contracts at oncehistorical_data— OHLCV bars (1 min to 1 month)historical_ticks— Individual tick datafundamental_data— Financial summaries, ratios, earningsmarket_depth_snapshot— Order book (Level 2)market_data_stream_subscribe/unsubscribe— Live tick streamrealtime_bars_stream_subscribe/unsubscribe— 5-second bars
Order Management Tools
order_preview— What-if analysis (commission, margin)order_place— Submit new orderorder_modify— Modify existing open orderorder_cancel— Cancel specific orderorders_cancel_all— Global cancel (use with caution!)orders_open_list— List open/pending ordersorders_completed_list— List filled/cancelled ordersexecutions_list— Execution reports (fills)bracket_order— Entry + take-profit + stop-lossoco_order— One-cancels-other group
Account/Portfolio Tools
accounts_list— List managed accountsaccount_summary— Net liquidation, equity, margin, cashpositions_list— Open positions with PnLportfolio_list— Portfolio with market valuespnl_account— Real-time account PnLpnl_position— Real-time position PnLbuying_power— Available buying powercash_balances— Cash by currencyleverage_metrics— Leverage and margin utilizationmargin_requirements— Current margin requirement
Risk/Analytics Tools
greeks_calculate— Option Greeks for a contractportfolio_greeks— Aggregate portfolio Greeksoption_price_calculate— Theoretical option pricingimplied_volatility_calculate— IV from pricestress_test_portfolio— Scenario analysisvalue_at_risk— Portfolio VaR (parametric)beta_exposure— Beta relative to benchmarkcorrelation_matrix— Pairwise correlationsexposure_by_symbol/exposure_by_sector— Exposure breakdownsimulate_trade_impact— Pre-trade risk analysis
News & Scanner Tools
news_headlines— Recent headlines by provider/contractnews_article— Full article textscanner_run— Custom market scannerscanner_run_preset— Pre-configured scans (top gainers, losers, etc.)
Admin/Health Tools
ping— Health checkconnection_status— Detailed connection infoserver_config— Current configurationerror_log— Recent error bufferserver_time— IB server time
Error Handling
All responses follow a standard envelope:
{
"success": true|false,
"data": { ... }, // on success
"error": { // on failure
"code": "ERROR_CODE",
"message": "...",
"details": { ... }
},
"meta": {
"requestId": "uuid",
"timestamp": "ISO8601",
"latencyMs": 123
}
}Common error codes:
NOT_CONNECTED— IB connection is downCONTRACT_NOT_FOUND— Invalid conId or symbolPACING_VIOLATION— Too many requests, retry after delayORDER_REJECTED— Order rejected by IBRISK_GUARDRAIL_BLOCKED— Server guardrail prevented actionMARKET_DATA_UNAVAILABLE— No data subscription or market closed
Best Practices
Start workflows with
pingorconnection_statusto verify connectivityCache contract qualifications (conId) within a conversation
Use
market_data_bulk_snapshotfor multiple quotes instead of individual callsFor options analysis, get the chain first, then qualify specific strikes
Monitor
error_logif operations are failing unexpectedlyUse
scanner_run_presetfor common scans instead of building from scratch
Capabilities
Features and capabilities supported by this server
Protocol revision2025-11-25
| Capability | Details |
|---|---|
| tools | {} |
| resources | {} |
Tools
Functions exposed to the LLM to take actions
| Name | Description |
|---|---|
| contract_searchB | Search for contracts/instruments by query string. Returns matching candidates with conId, symbol, secType, exchange. |
| contract_detailsA | Get full contract details including trading hours, min tick, valid exchanges, etc. Provide conId or contract specification. |
| contract_qualifyA | Qualify a partial contract specification to get the full conId and resolved exchange. MUST be called before using contracts in market data or order tools. |
| contract_rulesB | Get trading rules for a contract: min tick, size increment, valid exchanges, order types. |
| security_definitions_option_parametersB | Get available option expirations, strikes, and trading classes for an underlying. |
| option_chainB | Get the full option chain for an underlying: expirations, strikes, rights (C/P), multipliers. |
| instrument_metadataB | Get metadata for an instrument: symbol, primary exchange, industry, category, subcategory. |
| symbol_to_conid_mappingB | Resolve a symbol to its conId. Results are cached. |
| market_data_snapshotB | Get a point-in-time snapshot of market data for one contract: bid/ask/last/volume/OHLC etc. Resolves when data arrives or times out. |
| market_data_bulk_snapshotB | Get snapshots for multiple contracts simultaneously. Uses frozen snapshot (type 3). Returns array of results. |
| historical_dataC | Get OHLCV historical bars. Supports durations like "1 D", "1 W", "1 M", "1 Y". Bar sizes: "1 min", "5 mins", "1 hour", "1 day", etc. |
| historical_ticksC | Get individual tick data (time & sales). Returns up to 1000 ticks for a given time range. |
| fundamental_dataC | Get fundamental data for a stock: financial summary, ratios, earnings, etc. |
| market_depth_snapshotC | Get an order book snapshot (Level 2 data). Returns the current market depth rows. |
| market_data_stream_subscribeC | Subscribe to a live streaming market data feed (ticks) for a contract. Events are delivered via MCP resources. |
| market_data_stream_unsubscribeC | Unsubscribe from a market data stream by subscription_id. |
| tick_by_tick_stream_subscribeC | Subscribe to tick-by-tick data (Last, AllLast, BidAsk, MidPoint) for highest resolution. |
| tick_by_tick_stream_unsubscribeB | Unsubscribe from tick-by-tick data stream. |
| market_depth_stream_subscribeC | Subscribe to streaming market depth (Level 2) updates. |
| market_depth_stream_unsubscribeC | Unsubscribe from market depth stream. |
| realtime_bars_stream_subscribeC | Subscribe to 5-second realtime bars. |
| realtime_bars_stream_unsubscribeC | Unsubscribe from realtime bars stream. |
| list_market_data_subscriptionsA | List all active market data streaming subscriptions. |
| order_placeB | Place a new order. Requires: side, quantity, order type, and a qualified contract. Enforces all guardrails (read-only check, max qty, max notional, allowed order types, symbol allowlist/denylist). |
| order_modifyB | Modify an existing open order. Requires the same fields as order_place plus the orderId to modify. |
| order_cancelB | Cancel an open order by orderId. |
| orders_cancel_allA | Cancel ALL open orders via global cancel. Use with extreme caution. |
| orders_open_listC | List all open/pending orders with their current status. |
| orders_completed_listA | List completed (filled, cancelled) orders. |
| executions_listB | List execution reports (fills) with optional filter by symbol, side, time, etc. |
| order_previewB | Preview/what-if an order: see estimated commission, margin impact, equity with loan before actually sending. |
| exercise_optionsC | Exercise or lapse an option contract. |
| bracket_orderC | Place a bracket order: parent + take-profit + stop-loss. All three orders are linked and submitted together. |
| oco_orderC | Place a One-Cancels-Other (OCO) order group. When one order fills, the other is cancelled. |
| order_status_stream_subscribeA | Subscribe to live order status updates. Events are delivered via MCP notifications. |
| order_status_stream_unsubscribeB | Unsubscribe from order status updates. |
| accounts_listB | List all managed accounts associated with the connection. |
| account_summaryA | Get account summary: net liquidation, equity, cash, margin, buying power, etc. Supports filtering by tags. |
| account_valuesB | Get all key-value pairs from account: all balances, margin values, etc. |
| positions_listA | List all open positions across all accounts, with conId, size, avgCost, unrealized PnL. |
| portfolio_listB | Get portfolio positions with market value, unrealized/realized PnL from the account model. |
| pnl_accountC | Get real-time account PnL: daily, unrealized, realized PnL. |
| pnl_positionB | Get real-time PnL for a specific position by conId. |
| account_updates_subscribeC | Subscribe to live account updates (values and portfolio changes). |
| account_updates_unsubscribeC | Unsubscribe from live account updates. |
| buying_powerC | Get buying power details for an account. |
| cash_balancesC | Get cash balance breakdown by currency. |
| leverage_metricsB | Get leverage and margin utilization metrics: gross/net leverage, margin used vs available, cushion. |
| margin_requirementsA | Get margin requirements for a hypothetical trade (uses order what-if). |
| fa_groups_listA | List Financial Advisor account groups (FA accounts only). |
| fa_profiles_listA | List Financial Advisor allocation profiles (FA accounts only). |
| fa_aliases_listB | List Financial Advisor account aliases (FA accounts only). |
| fa_replaceB | Replace Financial Advisor configuration XML (groups, profiles, or aliases). |
| option_price_calculateC | Calculate theoretical option price using Black-Scholes model via IB API. |
| implied_volatility_calculateC | Calculate implied volatility from option price using IB API. |
| greeks_calculateC | Calculate option Greeks (delta, gamma, theta, vega) for one or more contracts. |
| portfolio_greeksA | Aggregate Greeks for all option positions in the portfolio. Returns portfolio-level delta, gamma, theta, vega. |
| stress_test_portfolioB | Stress test the current portfolio under hypothetical market scenarios: price moves, vol changes, time decay. |
| exposure_by_symbolB | Get portfolio exposure breakdown by symbol: market value, weight, delta exposure. |
| exposure_by_sectorC | Get portfolio exposure breakdown by sector/industry. |
| value_at_riskB | Calculate portfolio Value-at-Risk (VaR) using parametric method. Returns 1-day and N-day VaR at given confidence. |
| beta_exposureC | Calculate portfolio beta exposure relative to a benchmark (e.g., SPY). |
| correlation_matrixC | Compute pairwise correlation matrix for a set of symbols based on historical returns. |
| simulate_trade_impactC | Simulate the impact of a hypothetical trade on portfolio risk metrics (margin, Greeks, VaR). |
| dividends_and_splits_historyC | Get historical dividends and stock splits for a symbol. |
| corporate_actions_calendarA | Get upcoming corporate actions (dividends, splits, earnings) for contracts. NOTE: Requires Thomson Reuters subscription. |
| news_providers_listA | List available news providers with their codes. |
| news_bulletins_subscribeC | Subscribe to IB system news bulletins (exchange messages, system status, etc.). |
| news_bulletins_unsubscribeB | Unsubscribe from IB news bulletins. |
| news_headlinesC | Get recent news headlines, optionally filtered by provider codes and contract ID. |
| news_articleA | Get the full text of a news article by providerCode and articleId. |
| historical_newsC | Get historical news headlines for a contract. |
| scanner_parametersA | Get available scanner parameters: scan types, instruments, location codes, filter types. Returns XML — parse for valid values. |
| scanner_runB | Run a market scanner with custom parameters. Returns matching instruments. |
| scanner_cancelB | Cancel a running scanner subscription by reqId. |
| scanner_presets_listB | List all available scanner presets with their configurations. |
| scanner_run_presetC | Run a pre-configured scanner preset by name: top_gainers, top_losers, most_active, high_iv, unusual_volume, breakout_candidates, gap_up, gap_down. |
| connection_statusA | Check the IB Gateway/TWS connection status: connected, server version, managed accounts, error buffer, active subscriptions count. |
| connection_reconnectA | Force a reconnect to IB Gateway/TWS. Disconnects and reconnects the session. |
| server_configA | Get the current server configuration (sanitized — no secrets). Shows mode, risk limits, cache TTL, reconnect settings. |
| error_logB | Get the recent error log ring buffer. Returns the last N errors from the IB connection. |
| subscriptions_listB | List all active streaming subscriptions (market data, ticks, depth, bars, order status). |
| server_timeA | Request current server time from IB Gateway. Useful for health checks and clock sync verification. |
| pingA | Simple health check — returns "pong" with uptime and connection status. |
Prompts
Interactive templates invoked by user choice
| Name | Description |
|---|---|
No prompts | |
Resources
Contextual data attached and managed by the client
| Name | Description |
|---|---|
| Server Instructions | Agent guidance for using the IBKR MCP server tools effectively. |
| Connection Status | Live connection status and health information. |
| Server Configuration | Current server configuration (sanitized). |
| Recent Errors | Recent error log from the IB connection. |
TDQS
Scored across 84 tools
The set contains many overlapping tools: subscriptions_list vs list_market_data_subscriptions, positions_list vs portfolio_list, account_summary/account_values/buying_power/cash_balances, and multiple contract resolution paths (contract_search, contract_details, contract_qualify, symbol_to_conid_mapping). An agent can often choose a plausible but non-canonical tool, especially across market data, news, and account queries.
Mostly snake_case, but verb/noun order and prefixing vary: list_market_data_subscriptions (verb_noun) alongside subscriptions_list (noun_list), contract_search (noun_verb), contract_details (noun), news_article (noun), and fa_groups_list (prefix_entity_list). The subscribe/unsubscribe pairs are consistent, but the overall convention is mixed.
84 tools is far beyond a well-scoped set; many are granular variants such as snapshot vs bulk snapshot, multiple stream subscribe/unsubscribe pairs, and several account summary views. This creates a large surface area with overlapping choices and raises selection cost.
Covers the core IBKR lifecycle broadly: contract discovery, market data, historical data, orders and bracket/OCO, positions/account, risk analytics, scanners, news, and FA admin. Some gaps exist (e.g., alerts, richer order-history filtering, and some specialty data), but major workflows are represented.