interactive-brokers-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .DS_Store
5
+ .env
6
+ cache/
7
+ dist/
8
+ *.egg-info/
9
+ .mypy_cache/
10
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Henry Chien
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: interactive-brokers-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for Interactive Brokers Gateway — 6 tools for market data and account access via Claude
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: certifi
9
+ Requires-Dist: fastmcp
10
+ Requires-Dist: ib-async
11
+ Requires-Dist: nest-asyncio
12
+ Requires-Dist: pandas
13
+ Requires-Dist: pyarrow
14
+ Requires-Dist: python-dotenv
15
+ Requires-Dist: pyyaml
16
+ Requires-Dist: zstandard
17
+ Description-Content-Type: text/markdown
18
+
19
+ # ibkr-mcp
20
+
21
+ MCP server for Interactive Brokers Gateway — 6 tools for market data and account access via Claude.
22
+
23
+ ## Tools
24
+
25
+ | Tool | Description |
26
+ |------|-------------|
27
+ | `get_ibkr_market_data` | Historical OHLCV bars for any contract |
28
+ | `get_ibkr_positions` | Current portfolio positions and P&L |
29
+ | `get_ibkr_account` | Account summary (balances, margin, NAV) |
30
+ | `get_ibkr_contract` | Contract lookup and details |
31
+ | `get_ibkr_option_prices` | Option chain pricing |
32
+ | `get_ibkr_snapshot` | Real-time quote snapshot |
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install ibkr-mcp
38
+ ```
39
+
40
+ ## Prerequisites
41
+
42
+ - [IB Gateway](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) or TWS running
43
+ - API access enabled in Gateway/TWS settings
44
+ - Host/port/client ID matching your environment variables
45
+
46
+ ## Environment Variables
47
+
48
+ | Variable | Default | Description |
49
+ |----------|---------|-------------|
50
+ | `IBKR_GATEWAY_HOST` | `127.0.0.1` | Gateway hostname |
51
+ | `IBKR_GATEWAY_PORT` | `7496` | Gateway port |
52
+ | `IBKR_CLIENT_ID` | `1` | API client ID |
53
+ | `IBKR_TIMEOUT` | `10` | Connection timeout (seconds) |
54
+ | `IBKR_READONLY` | `false` | Read-only mode |
55
+ | `IBKR_AUTHORIZED_ACCOUNTS` | | Comma-separated account whitelist |
56
+ | `IBKR_CACHE_DIR` | | Optional cache directory override |
57
+
58
+ The package auto-loads `.env` from the package directory and parent.
59
+
60
+ ## Usage
61
+
62
+ ### Claude Code
63
+
64
+ ```bash
65
+ claude mcp add ibkr-mcp -- ibkr-mcp
66
+ ```
67
+
68
+ Or in `~/.claude.json`:
69
+
70
+ ```json
71
+ {
72
+ "mcpServers": {
73
+ "ibkr-mcp": {
74
+ "type": "stdio",
75
+ "command": "ibkr-mcp"
76
+ }
77
+ }
78
+ }
79
+ ```
80
+
81
+ ### Standalone
82
+
83
+ ```bash
84
+ ibkr-mcp # via installed entry point
85
+ python -m ibkr.server # via module
86
+ ```
87
+
88
+ ## License
89
+
90
+ MIT
@@ -0,0 +1,72 @@
1
+ # ibkr-mcp
2
+
3
+ MCP server for Interactive Brokers Gateway — 6 tools for market data and account access via Claude.
4
+
5
+ ## Tools
6
+
7
+ | Tool | Description |
8
+ |------|-------------|
9
+ | `get_ibkr_market_data` | Historical OHLCV bars for any contract |
10
+ | `get_ibkr_positions` | Current portfolio positions and P&L |
11
+ | `get_ibkr_account` | Account summary (balances, margin, NAV) |
12
+ | `get_ibkr_contract` | Contract lookup and details |
13
+ | `get_ibkr_option_prices` | Option chain pricing |
14
+ | `get_ibkr_snapshot` | Real-time quote snapshot |
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install ibkr-mcp
20
+ ```
21
+
22
+ ## Prerequisites
23
+
24
+ - [IB Gateway](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) or TWS running
25
+ - API access enabled in Gateway/TWS settings
26
+ - Host/port/client ID matching your environment variables
27
+
28
+ ## Environment Variables
29
+
30
+ | Variable | Default | Description |
31
+ |----------|---------|-------------|
32
+ | `IBKR_GATEWAY_HOST` | `127.0.0.1` | Gateway hostname |
33
+ | `IBKR_GATEWAY_PORT` | `7496` | Gateway port |
34
+ | `IBKR_CLIENT_ID` | `1` | API client ID |
35
+ | `IBKR_TIMEOUT` | `10` | Connection timeout (seconds) |
36
+ | `IBKR_READONLY` | `false` | Read-only mode |
37
+ | `IBKR_AUTHORIZED_ACCOUNTS` | | Comma-separated account whitelist |
38
+ | `IBKR_CACHE_DIR` | | Optional cache directory override |
39
+
40
+ The package auto-loads `.env` from the package directory and parent.
41
+
42
+ ## Usage
43
+
44
+ ### Claude Code
45
+
46
+ ```bash
47
+ claude mcp add ibkr-mcp -- ibkr-mcp
48
+ ```
49
+
50
+ Or in `~/.claude.json`:
51
+
52
+ ```json
53
+ {
54
+ "mcpServers": {
55
+ "ibkr-mcp": {
56
+ "type": "stdio",
57
+ "command": "ibkr-mcp"
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ ### Standalone
64
+
65
+ ```bash
66
+ ibkr-mcp # via installed entry point
67
+ python -m ibkr.server # via module
68
+ ```
69
+
70
+ ## License
71
+
72
+ MIT
@@ -0,0 +1,55 @@
1
+ """IBKR provider package.
2
+
3
+ Agent orientation:
4
+ Public package entrypoint for IBKR integration.
5
+ For market data/account operations start with ``ibkr.client.IBKRClient``;
6
+ for compatibility wrappers used by other modules start with ``ibkr.compat``.
7
+ """
8
+
9
+ from .client import IBKRClient
10
+ from .market_data import IBKRMarketDataClient
11
+ from .compat import (
12
+ fetch_ibkr_bond_monthly_close,
13
+ fetch_ibkr_daily_close_futures,
14
+ fetch_ibkr_flex_trades,
15
+ fetch_ibkr_fx_monthly_close,
16
+ fetch_ibkr_monthly_close,
17
+ fetch_ibkr_option_monthly_mark,
18
+ get_futures_currency,
19
+ get_ibkr_futures_exchanges,
20
+ get_ibkr_futures_fmp_map,
21
+ )
22
+ from .exceptions import (
23
+ IBKRConnectionError,
24
+ IBKRContractError,
25
+ IBKRDataError,
26
+ IBKREntitlementError,
27
+ IBKRAccountError,
28
+ IBKRNoDataError,
29
+ IBKRTimeoutError,
30
+ )
31
+ from .profiles import InstrumentProfile, get_profile, get_profiles
32
+
33
+ __all__ = [
34
+ "IBKRClient",
35
+ "IBKRMarketDataClient",
36
+ "fetch_ibkr_monthly_close",
37
+ "fetch_ibkr_daily_close_futures",
38
+ "fetch_ibkr_fx_monthly_close",
39
+ "fetch_ibkr_bond_monthly_close",
40
+ "fetch_ibkr_option_monthly_mark",
41
+ "fetch_ibkr_flex_trades",
42
+ "get_ibkr_futures_fmp_map",
43
+ "get_ibkr_futures_exchanges",
44
+ "get_futures_currency",
45
+ "InstrumentProfile",
46
+ "get_profile",
47
+ "get_profiles",
48
+ "IBKRDataError",
49
+ "IBKRConnectionError",
50
+ "IBKRContractError",
51
+ "IBKRNoDataError",
52
+ "IBKREntitlementError",
53
+ "IBKRAccountError",
54
+ "IBKRTimeoutError",
55
+ ]
@@ -0,0 +1,23 @@
1
+ """IBKR package-local logging shims with monorepo fallback behavior."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sys
7
+
8
+
9
+ def _make_fallback_logger(name: str) -> logging.Logger:
10
+ logger = logging.getLogger(f"ibkr.{name}")
11
+ if not logger.handlers:
12
+ handler = logging.StreamHandler(sys.stderr)
13
+ handler.setFormatter(logging.Formatter("%(asctime)s [%(name)s] %(levelname)s: %(message)s"))
14
+ logger.addHandler(handler)
15
+ logger.setLevel(logging.INFO)
16
+ return logger
17
+
18
+
19
+ try:
20
+ from utils.logging import portfolio_logger, trading_logger
21
+ except Exception:
22
+ portfolio_logger = _make_fallback_logger("portfolio")
23
+ trading_logger = _make_fallback_logger("trading")
@@ -0,0 +1,25 @@
1
+ """Shared instrument metadata types vendored for ibkr package portability."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ InstrumentType = Literal["equity", "option", "futures", "fx", "fx_artifact", "bond", "unknown"]
8
+
9
+ _VALID_INSTRUMENT_TYPES = {
10
+ "equity",
11
+ "option",
12
+ "futures",
13
+ "fx",
14
+ "fx_artifact",
15
+ "bond",
16
+ "unknown",
17
+ }
18
+
19
+
20
+ def coerce_instrument_type(value: Any, default: InstrumentType = "equity") -> InstrumentType:
21
+ """Normalize external instrument strings to the supported instrument type enum."""
22
+ normalized = str(value or "").strip().lower()
23
+ if normalized in _VALID_INSTRUMENT_TYPES:
24
+ return normalized # type: ignore[return-value]
25
+ return default
@@ -0,0 +1,23 @@
1
+ """Lightweight helpers vendored from trading_analysis for ibkr portability."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ def safe_float(value: Any, default: float = 0.0) -> float:
9
+ """Safely convert value to float."""
10
+ if value is None:
11
+ return default
12
+ try:
13
+ return float(value)
14
+ except (ValueError, TypeError):
15
+ return default
16
+
17
+
18
+ def normalize_strike(strike: Any) -> str:
19
+ """Canonical strike string: 30.0->"30", 2.5->"2p5", 2.50->"2p5"."""
20
+ val = float(strike)
21
+ if val == int(val):
22
+ return str(int(val))
23
+ return f"{val:g}".replace(".", "p")
@@ -0,0 +1,186 @@
1
+ """Account-level IBKR data helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import time
7
+ from typing import Any
8
+
9
+ import pandas as pd
10
+
11
+ from .exceptions import IBKRTimeoutError
12
+
13
+
14
+ _POSITION_COLUMNS = [
15
+ "account",
16
+ "symbol",
17
+ "sec_type",
18
+ "currency",
19
+ "exchange",
20
+ "con_id",
21
+ "position",
22
+ "avg_cost",
23
+ ]
24
+
25
+ _SUMMARY_TAGS = {
26
+ "NetLiquidation": "net_liquidation",
27
+ "TotalCashValue": "total_cash_value",
28
+ "BuyingPower": "buying_power",
29
+ "GrossPositionValue": "gross_position_value",
30
+ "MaintMarginReq": "maint_margin_req",
31
+ "AvailableFunds": "available_funds",
32
+ "ExcessLiquidity": "excess_liquidity",
33
+ "SMA": "sma",
34
+ }
35
+
36
+
37
+ def _safe_float(value: Any) -> float | None:
38
+ try:
39
+ if value is None:
40
+ return None
41
+ return float(value)
42
+ except (TypeError, ValueError):
43
+ return None
44
+
45
+
46
+ def _is_not_nan(value: Any) -> bool:
47
+ as_float = _safe_float(value)
48
+ if as_float is None:
49
+ return False
50
+ return not math.isnan(as_float)
51
+
52
+
53
+ def _ib_sleep(ib, seconds: float) -> None:
54
+ try:
55
+ sleep_fn = getattr(ib, "sleep", None)
56
+ if callable(sleep_fn):
57
+ sleep_fn(seconds)
58
+ else:
59
+ time.sleep(seconds)
60
+ except Exception:
61
+ time.sleep(seconds)
62
+
63
+
64
+ def _wait_for_pnl_ready(ib, pnl_obj, *, timeout_seconds: float, poll_interval: float) -> None:
65
+ deadline = time.monotonic() + timeout_seconds
66
+ while time.monotonic() < deadline:
67
+ if _is_not_nan(getattr(pnl_obj, "dailyPnL", None)):
68
+ return
69
+ _ib_sleep(ib, poll_interval)
70
+ raise IBKRTimeoutError("Timed out waiting for IBKR PnL update")
71
+
72
+
73
+ def fetch_positions(ib, account_id: str | None = None) -> pd.DataFrame:
74
+ """Fetch IBKR positions and normalize to DataFrame."""
75
+ ib.reqPositions()
76
+ positions = list(ib.positions() or [])
77
+
78
+ rows: list[dict[str, Any]] = []
79
+ for pos in positions:
80
+ acct = getattr(pos, "account", None)
81
+ if account_id and acct != account_id:
82
+ continue
83
+ contract = getattr(pos, "contract", None)
84
+ rows.append(
85
+ {
86
+ "account": acct,
87
+ "symbol": getattr(contract, "symbol", None) if contract else None,
88
+ "sec_type": getattr(contract, "secType", None) if contract else None,
89
+ "currency": getattr(contract, "currency", None) if contract else None,
90
+ "exchange": getattr(contract, "exchange", None) if contract else None,
91
+ "con_id": getattr(contract, "conId", None) if contract else None,
92
+ "position": _safe_float(getattr(pos, "position", None)),
93
+ "avg_cost": _safe_float(getattr(pos, "avgCost", None)),
94
+ }
95
+ )
96
+
97
+ if not rows:
98
+ return pd.DataFrame(columns=_POSITION_COLUMNS)
99
+ frame = pd.DataFrame(rows, columns=_POSITION_COLUMNS)
100
+ return frame.sort_values(["account", "symbol"], na_position="last").reset_index(drop=True)
101
+
102
+
103
+ def fetch_account_summary(ib, account_id: str | None = None) -> dict[str, float]:
104
+ """Fetch account summary values with USD-only tag normalization."""
105
+ account_values = list(ib.accountValues(account=account_id) or [])
106
+ if not account_values:
107
+ ib.reqAccountUpdates(account=account_id)
108
+ account_values = list(ib.accountValues(account=account_id) or [])
109
+
110
+ summary: dict[str, float] = {}
111
+ for av in account_values:
112
+ if account_id and getattr(av, "account", None) not in (None, "", account_id):
113
+ continue
114
+ if getattr(av, "currency", None) != "USD":
115
+ continue
116
+ key = _SUMMARY_TAGS.get(getattr(av, "tag", None))
117
+ if key is None:
118
+ continue
119
+ val = _safe_float(getattr(av, "value", None))
120
+ if val is None:
121
+ continue
122
+ summary[key] = val
123
+
124
+ return summary
125
+
126
+
127
+ def fetch_pnl(
128
+ ib,
129
+ account_id: str,
130
+ *,
131
+ timeout_seconds: float = 5.0,
132
+ poll_interval: float = 0.1,
133
+ ) -> dict[str, float | str | None]:
134
+ """Fetch account-level PnL via streaming subscription with timeout polling."""
135
+ pnl_obj = ib.reqPnL(account_id, modelCode="")
136
+ try:
137
+ _wait_for_pnl_ready(
138
+ ib,
139
+ pnl_obj,
140
+ timeout_seconds=timeout_seconds,
141
+ poll_interval=poll_interval,
142
+ )
143
+ return {
144
+ "account_id": account_id,
145
+ "daily_pnl": _safe_float(getattr(pnl_obj, "dailyPnL", None)),
146
+ "unrealized_pnl": _safe_float(getattr(pnl_obj, "unrealizedPnL", None)),
147
+ "realized_pnl": _safe_float(getattr(pnl_obj, "realizedPnL", None)),
148
+ }
149
+ finally:
150
+ try:
151
+ ib.cancelPnL(account_id, modelCode="")
152
+ except Exception:
153
+ pass
154
+
155
+
156
+ def fetch_pnl_single(
157
+ ib,
158
+ account_id: str,
159
+ con_id: int,
160
+ *,
161
+ timeout_seconds: float = 5.0,
162
+ poll_interval: float = 0.1,
163
+ ) -> dict[str, float | int | str | None]:
164
+ """Fetch contract-level PnL via streaming subscription with timeout polling."""
165
+ pnl_obj = ib.reqPnLSingle(account_id, modelCode="", conId=int(con_id))
166
+ try:
167
+ _wait_for_pnl_ready(
168
+ ib,
169
+ pnl_obj,
170
+ timeout_seconds=timeout_seconds,
171
+ poll_interval=poll_interval,
172
+ )
173
+ return {
174
+ "account_id": account_id,
175
+ "con_id": int(con_id),
176
+ "daily_pnl": _safe_float(getattr(pnl_obj, "dailyPnL", None)),
177
+ "unrealized_pnl": _safe_float(getattr(pnl_obj, "unrealizedPnL", None)),
178
+ "realized_pnl": _safe_float(getattr(pnl_obj, "realizedPnL", None)),
179
+ "position": _safe_float(getattr(pnl_obj, "position", None)),
180
+ "value": _safe_float(getattr(pnl_obj, "value", None)),
181
+ }
182
+ finally:
183
+ try:
184
+ ib.cancelPnLSingle(account_id, modelCode="", conId=int(con_id))
185
+ except Exception:
186
+ pass