mcp-ibkr-agent
Enables AI agents to trade on Interactive Brokers: check quotes, balance, positions, and execute buy/sell orders (including fractional shares by dollar amount) via the Client Portal API.
README
mcp-ibkr-agent
Servidor MCP que dá a um agente de IA (como o Claude Code) a capacidade de operar na Interactive Brokers: consultar cotações, saldo, posições e ordens, e comprar/vender — inclusive ações fracionárias por valor em dólar (cashQty) via Client Portal API.
A decisão de investimento (o que/quando comprar ou vender) fica com você e com o prompt da sua skill. Este projeto entrega só o encanamento de trading confiável — com travas de segurança por padrão.
⚠️ Não é aconselhamento financeiro. Opera em conta paper por padrão; operação live exige destravar explicitamente. Use por sua conta e risco.
Arquitetura
Hexagonal (ports & adapters):
domain/ modelos (OrderRequest com quantity OU cash_qty) e portas (Broker/MarketData/Auth)
adapters/ cpapi/ — implementação sobre a IBKR Client Portal API (REST)
safety/ GuardedBroker — travas: live lock, dry-run, limite de valor, horário de pregão
server/ servidor MCP (FastMCP) + composição das dependências
Trocar/estender o broker no futuro (ex.: um adapter de dados em ib_async) é mexer só em adapters/ + server/services.py.
Pré-requisitos
- Python 3.12+
- Conta Interactive Brokers aberta, fundeada e do tipo IBKR Pro (exigência da API, mesmo para usar o paper associado).
- Permissão de fracionário habilitada: Client Portal → Settings → Trading → Trading Permissions → seção Stocks → marcar "Global (Trade in Fractions)".
- IBKR Client Portal Gateway rodando localmente (Java 8u192+).
- Username dedicado ao bot: a IBKR permite só uma brokerage session por username — logar no TWS/celular com o mesmo usuário derruba a sessão do gateway.
Instalação
git clone https://github.com/pedrobraiti/mcp-ibkr-agent.git
cd mcp-ibkr-agent
python -m venv .venv
# Windows (PowerShell): & ".venv\Scripts\Activate.ps1" (se erro de policy: Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass)
# Linux/macOS: source .venv/bin/activate
pip install -e ".[dev]"
cp .env.example .env # preencha IBKR_ACCOUNT_ID etc.
Configuração (.env)
Veja .env.example. Principais chaves:
| Chave | Default | Descrição |
|---|---|---|
IBKR_API_BASE_URL |
https://localhost:5000/v1/api |
Endpoint do Client Portal Gateway |
IBKR_ACCOUNT_ID |
— | ID da conta (ex.: DU1234567 em paper) |
IBKR_TRADING_MODE |
paper |
paper ou live |
TRADING_ALLOW_LIVE |
false |
Trava dura: live só opera se true |
TRADING_DRY_RUN |
true |
Valida mas não envia ordens |
MAX_ORDER_VALUE |
100.0 |
Limite (US$) por ordem |
Rodando
-
Inicie o Client Portal Gateway e faça login no navegador em
https://localhost:5000(com 2FA). -
Registre o servidor MCP no Claude Code:
claude mcp add ibkr -- /caminho/para/.venv/Scripts/python.exe -m ibkr_agent.server.app(ou rode direto para testar:
python -m ibkr_agent.server.app) -
Verifique a conexão a qualquer momento (com o gateway logado):
python -m ibkr_agent.healthcheck # ou: ibkr-healthcheckMostra versão do servidor, status de auth, flags da conta (
supportsCashQty/supportsFractions), saldo e uma cotação.
Troubleshooting do login
Se o navegador mostra "Client login succeeds" mas a API segue authenticated:false/connected:false (ou ssodh/init dá HTTP 500 / no bridge):
- Reinicie o gateway limpo (encerre o processo Java e suba de novo).
- Logue numa aba anônima do Chrome (cookies antigos atrapalham).
- Deslogue sessões concorrentes: IBKR Mobile e Client Portal web (1 brokerage session por username).
- A versão antiga do launcher (2023) não é o problema — em runtime o gateway conecta no backend atual.
Tools expostas
session_status, market_status, get_quote, account_summary, positions, buy, sell, cancel_order, open_orders.
buy/sell aceitam cash_amount (US$, fracionário) ou quantity (ações inteiras).
Segurança (padrões)
- paper por padrão; live bloqueado a menos que
TRADING_ALLOW_LIVE=true. - dry-run ligado por padrão (não envia ordem de verdade).
- Ordem acima de
MAX_ORDER_VALUEé recusada. - Ordens só durante o pregão (RTH).
- Warnings de confirmação da CPAPI só são auto-aceitos via allow-list; warning desconhecido bloqueia a ordem.
Desenvolvimento
python -m pytest -q # testes
python -m ruff check . # lint
Licença
MIT.
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
Neon Database
MCP server for interacting with Neon Management API and databases
E2B
Using MCP to run code via e2b.
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.