Skip to main content
Glama

Server Configuration

Describes the environment variables required to run the server.

NameRequiredDescriptionDefault
IB_HOSTNoTWS/Gateway host.127.0.0.1
IB_MODENopaper or live.paper
IB_PORTNoAPI port.4002 (paper) / 4001 (live)
LOG_LEVELNodebug, info, warn, error.info
IB_CLIENT_IDNoClient ID.1
IB_READ_ONLYNoBlock all order mutations.true
IB_ACCOUNT_IDNoAccount ID override. Default: auto.
RISK_MAX_ORDER_QTYNoMax shares/contracts per order.1000
RISK_SYMBOL_DENYLISTNoBlock these symbols. Default: none.
RISK_DAILY_LOSS_LIMITNoDaily loss limit ($).10000
RISK_SYMBOL_ALLOWLISTNoOnly allow these symbols. Default: none.
RISK_ALLOW_OUTSIDE_RTHNoAllow outside-hours orders.false
RISK_MAX_ORDER_NOTIONALNoMax order notional ($).100000
RISK_ALLOWED_ORDER_TYPESNoAllowed 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

  1. Always qualify contracts first. Before requesting market data, placing orders, or any operation that needs a contract, call contract_qualify or contract_search to get a valid conId. Never guess contract IDs.

  2. Use order_preview before order_place. Always preview orders to verify commission, margin impact, and price before submitting. This is especially important for options and futures.

  3. 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.

  4. Handle streaming subscriptions carefully.

    • Always unsubscribe when data is no longer needed

    • Use subscriptions_list to see active subscriptions

    • IB limits the number of concurrent market data lines (typically 100)

  5. Check connection before operations. If you get connection errors, call connection_status to diagnose. The server handles reconnection automatically, but operations during reconnection will fail.

Tool Categories

Contract/Instrument Tools

  • contract_search — Find instruments by name/symbol

  • contract_qualify — Qualify partial contract → full conId (REQUIRED before use)

  • contract_details — Full specs, trading hours, min tick

  • contract_rules — Trading rules and order type support

  • option_chain — Full option chain for an underlying

  • security_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 once

  • historical_data — OHLCV bars (1 min to 1 month)

  • historical_ticks — Individual tick data

  • fundamental_data — Financial summaries, ratios, earnings

  • market_depth_snapshot — Order book (Level 2)

  • market_data_stream_subscribe/unsubscribe — Live tick stream

  • realtime_bars_stream_subscribe/unsubscribe — 5-second bars

Order Management Tools

  • order_preview — What-if analysis (commission, margin)

  • order_place — Submit new order

  • order_modify — Modify existing open order

  • order_cancel — Cancel specific order

  • orders_cancel_all — Global cancel (use with caution!)

  • orders_open_list — List open/pending orders

  • orders_completed_list — List filled/cancelled orders

  • executions_list — Execution reports (fills)

  • bracket_order — Entry + take-profit + stop-loss

  • oco_order — One-cancels-other group

Account/Portfolio Tools

  • accounts_list — List managed accounts

  • account_summary — Net liquidation, equity, margin, cash

  • positions_list — Open positions with PnL

  • portfolio_list — Portfolio with market values

  • pnl_account — Real-time account PnL

  • pnl_position — Real-time position PnL

  • buying_power — Available buying power

  • cash_balances — Cash by currency

  • leverage_metrics — Leverage and margin utilization

  • margin_requirements — Current margin requirement

Risk/Analytics Tools

  • greeks_calculate — Option Greeks for a contract

  • portfolio_greeks — Aggregate portfolio Greeks

  • option_price_calculate — Theoretical option pricing

  • implied_volatility_calculate — IV from price

  • stress_test_portfolio — Scenario analysis

  • value_at_risk — Portfolio VaR (parametric)

  • beta_exposure — Beta relative to benchmark

  • correlation_matrix — Pairwise correlations

  • exposure_by_symbol / exposure_by_sector — Exposure breakdown

  • simulate_trade_impact — Pre-trade risk analysis

News & Scanner Tools

  • news_headlines — Recent headlines by provider/contract

  • news_article — Full article text

  • scanner_run — Custom market scanner

  • scanner_run_preset — Pre-configured scans (top gainers, losers, etc.)

Admin/Health Tools

  • ping — Health check

  • connection_status — Detailed connection info

  • server_config — Current configuration

  • error_log — Recent error buffer

  • server_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 down

  • CONTRACT_NOT_FOUND — Invalid conId or symbol

  • PACING_VIOLATION — Too many requests, retry after delay

  • ORDER_REJECTED — Order rejected by IB

  • RISK_GUARDRAIL_BLOCKED — Server guardrail prevented action

  • MARKET_DATA_UNAVAILABLE — No data subscription or market closed

Best Practices

  1. Start workflows with ping or connection_status to verify connectivity

  2. Cache contract qualifications (conId) within a conversation

  3. Use market_data_bulk_snapshot for multiple quotes instead of individual calls

  4. For options analysis, get the chain first, then qualify specific strikes

  5. Monitor error_log if operations are failing unexpectedly

  6. Use scanner_run_preset for common scans instead of building from scratch

Capabilities

Features and capabilities supported by this server

Protocol revision2025-11-25

CapabilityDetails
tools
{}
resources
{}

Tools

Functions exposed to the LLM to take actions

NameDescription
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

NameDescription

No prompts

Resources

Contextual data attached and managed by the client

NameDescription
Server InstructionsAgent guidance for using the IBKR MCP server tools effectively.
Connection StatusLive connection status and health information.
Server ConfigurationCurrent server configuration (sanitized).
Recent ErrorsRecent error log from the IB connection.

TDQS

C2.7/5.0

Scored across 84 tools

Disambiguation2/5

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.

Naming Consistency3/5

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.

Tool Count1/5

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.

Completeness4/5

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.

Maintenance

ActivityInactive
ResponsivenessNo recent community issues