convez.ai
MCP ServerFinanceiroAvançado
jluzny

IBKR MCP Server em Rust

jluzny/ibkr-mcp-rs

Acesso a dados vivos de brokerage do IBKR para agentes IA via MCP

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP que expõe dados de mercado, informações de conta e posições do Interactive Brokers para agentes LLM via JSON-RPC. Implementado em Rust com suporte a transporte HTTP (SSE) ou stdio, cache distribuído e fallback automático de dados com entitlements.

Instalação

$npx convez-ai jluzny/ibkr-mcp-rs

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 1 semana
Versão
—
Issues abertas
0
Contribuidores
3

Casos de uso

  • Agentes IA consultarem cotações e histórico de mercado em tempo real
  • Automação de decisões de trading baseadas em dados atualizados de conta
  • Monitoramento de posições e PnL em dashboards inteligentes

Veredito

Implementação sólida em Rust com design robusto (cache, retry, fallback automático). Bem documentado e pronto para integração em pipelines de trading quantitativo ou assistentes financeiros, mas requer conhecimento técnico e setup local do IB Gateway.

README

A tradução para o português deste README ainda está na fila.

ibkr-mcp-rs

Interactive Brokers MCP Server in Rust. Exposes market data, account information, positions, and connection status via the Model Context Protocol (MCP) so LLM agents can query live brokerage data.

Features

FeatureDescription
Market Data QuotesReal-time or delayed stock quotes with automatic entitlement fallback
Account InfoNet liquidation, available funds, buying power, daily PnL
PositionsCurrent holdings with unrealized / daily PnL
Connection StatusLive IBKR gateway connectivity check
Order ManagerOrder placement infrastructure (extensible for trading agents)
Dual TransportHTTP (SSE/streamable) or stdio for local integrations
Health Checks/health/live, /health/ready, /health/broker, /version

Architecture

graph LR
    A[LLM Agent / MCP Client] -->|MCP JSON-RPC| B(MCP Server)
    B -->|ibapi crate| C[IB Gateway / TWS]
    B --> D[(DashMap Cache)]
    B --> E[Axum Health Router]

    subgraph "Transport"
        F[HTTP SSE / Streamable]
        G[Stdio]
    end

    A --> F
    A --> G
    F --> B
    G --> B

MCP Tools Reference

ToolParametersReturns
get_market_datasymbol (string), data_type ("quote", "historical", "option_chain"), period, expirationQuote JSON with bid/ask/last/volume/high/low/close/source
get_account_infoaccount_id (optional)Account summary: netLiquidation, availableFunds, buyingPower, dailyPnL
get_positionsaccount_id (optional)Array of positions: symbol, quantity, averageCost, marketPrice, marketValue, unrealizedPnL, dailyPnL
get_connection_statusnonebrokerConnected: true/false + timestamp

Quote Source Fallback

If a real-time market data subscription is not available (IBKR error codes 10089, 10167, 10168, 10169, 354), the server automatically retries with delayed data and caches the result.

Prerequisites

  • Rust 1.75+
  • IB Gateway or TWS running with API enabled
  • Paper trading recommended for initial setup

Quick Start

Local Build

cargo build --release

# HTTP mode (default)
./target/release/ibkr-mcp-rs

# Stdio mode (for e.g. Claude Desktop)
./target/release/ibkr-mcp-rs --stdio

Docker

docker build -t ibkr-mcp-rs .
docker run -p 8881:8881 -e IBKR__HOST=host.docker.internal ibkr-mcp-rs

Configuration

Configuration is layered (highest precedence first):

  1. Environment variables: IBKR__HOST, MCP__PORT, LOGGING__LEVEL
  2. config/docker.yaml (auto-loaded when ENV=docker)
  3. config/default.yaml

Default config/default.yaml

ibkr:
  host: "127.0.0.1"
  port: 4002          # Gateway paper trading; 4001 for live
  client_id: 100
  paper_trading: true
  read_only: true
  connection_timeout_secs: 10
  retry_attempts: 100
  retry_delay_ms: 500

mcp:
  host: "0.0.0.0"
  port: 8881
  session_timeout_secs: 0

market_data:
  real_time_ttl_secs: 5
  delayed_ttl_secs: 60
  max_cache_entries: 1000

logging:
  level: "info"
  format: "json"      # or "text"

Health Endpoints

When running in HTTP mode:

EndpointPurpose
GET /health/liveServer process is running
GET /health/readyServer ready to accept MCP connections
GET /health/brokerIBKR gateway connection status
GET /versionServer version (ibkr-mcp-rs 0.1.0)

Testing

# Unit tests
cargo test

# MCP server integration tests (random ephemeral port)
cargo test --test mcp_server_test

# Live E2E against a running IB Gateway (requires localhost:4003)
cargo test --test live_ibkr_test -- --ignored

Project Structure

src/
  main.rs          # Entry point — transport mode selection, signal handling
  lib.rs           # Crate root
  config.rs        # Figment-based layered config
  logging.rs       # Tracing subscriber (JSON/text, stderr)
  mcp/
    server.rs      # HTTP / stdio server startup helpers
    tools.rs       # MCP tool definitions (4 tools)
    health.rs      # Axum health check router
  ibkr/
    client.rs      # IBKR connection manager with retry
    market_data.rs # Quotes, caching, delayed fallback
    account.rs     # Account summary & positions
    orders.rs      # Order placement
    error.rs       # Error types & code mapping
    contract.rs    # Contract builders (stock, option call)

License

MIT

Ver o original no GitHub

Bom para

Relacionados