# API 参考文档
本文档详细说明 IBKR-MCP 提供的所有 MCP Tools 和 Resources 接口,按照服务类型进行分类。
---
## 1. Portfolio Service(投资组合服务)
提供账户摘要、投资组合持仓和 Greeks 分析功能。
### Tools
#### get_portfolio
获取投资组合持仓及盈亏信息。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ----------- | ------ | ---- | ------ | ------- |
| `account` | string | 否 | `""` | 账户 ID |
**返回类型**: `list[PortfolioItem]`
**返回字段**
| 字段 | 类型 | 描述 |
| ----------------- | ------ | ------------- |
| `account` | string | 账户 ID |
| `contract` | object | IBKR 合约对象 |
| `position` | float | 持仓数量 |
| `marketPrice` | float | 当前市场价格 |
| `marketValue` | float | 市场价值 |
| `averageCost` | float | 平均成本 |
| `unrealizedPNL` | float | 未实现盈亏 |
| `realizedPNL` | float | 已实现盈亏 |
**示例响应**
```json
[
{
"account": "U1234567",
"contract": {"symbol": "AAPL", "secType": "STK", "conId": 265598},
"position": 100,
"marketPrice": 175.50,
"marketValue": 17550.00,
"averageCost": 150.25,
"unrealizedPNL": 2525.00,
"realizedPNL": 0.0
}
]
```
---
#### get_greeks_summary
获取投资组合 Greeks 汇总(Delta、Gamma、Vega、Theta)。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ----------- | ------ | ---- | ------ | ------- |
| `account` | string | 否 | `""` | 账户 ID |
**返回类型**: `GreeksSummaryResponse`
```typescript
{
greek_summary: {
per_symbol: SymbolGreeks[],
totals: GreekTotals
},
concentration: {
per_symbol: ConcentrationRecord[],
series: Record<string, number>,
totals: { gross_total: number }
},
position_count: number
}
```
**SymbolGreeks 字段**
| 字段 | 类型 | 描述 |
| -------------- | ------ | ---------- |
| `underlying` | string | 标的代码 |
| `delta` | float | Delta 总和 |
| `gamma` | float | Gamma 总和 |
| `vega` | float | Vega 总和 |
| `theta` | float | Theta 总和 |
| `rho` | float | Rho 总和 |
**GreekTotals 字段**
| 字段 | 类型 | 描述 |
| --------- | ----- | --------------- |
| `delta` | float | 组合 Delta 总和 |
| `gamma` | float | 组合 Gamma 总和 |
| `vega` | float | 组合 Vega 总和 |
| `theta` | float | 组合 Theta 总和 |
| `rho` | float | 组合 Rho 总和 |
**ConcentrationRecord 字段**
| 字段 | 类型 | 描述 |
| ------------------ | ------ | ------------ |
| `underlying` | string | 标的代码 |
| `gross_exposure` | float | 绝对敞口金额 |
| `gross_pct` | float | 敞口占比 |
**示例响应**
```json
{
"greek_summary": {
"per_symbol": [
{"underlying": "AAPL", "delta": 150.5, "gamma": 2.3, "vega": 450.0, "theta": -25.0, "rho": 0.0},
{"underlying": "PLTR", "delta": 280.0, "gamma": 5.1, "vega": 890.0, "theta": -42.0, "rho": 0.0}
],
"totals": {"delta": 430.5, "gamma": 7.4, "vega": 1340.0, "theta": -67.0, "rho": 0.0}
},
"concentration": {
"per_symbol": [
{"underlying": "AAPL", "gross_exposure": 17550.0, "gross_pct": 0.35},
{"underlying": "PLTR", "gross_exposure": 32500.0, "gross_pct": 0.65}
],
"series": {"AAPL": 0.35, "PLTR": 0.65},
"totals": {"gross_total": 50050.0}
},
"position_count": 5
}
```
### Resources
#### ibkr://account_summary
获取账户概要信息(只读资源)。
**URI**: `ibkr://account_summary`
**返回类型**: `AccountSummaryResource`
```typescript
{
account_id: string,
currency: string,
net_liquidation: number | null,
equity_with_loan: number | null,
total_cash: number | null,
buying_power: number | null,
init_margin_req: number | null,
maint_margin_req: number | null,
available_funds: number | null,
excess_liquidity: number | null,
cushion: number | null,
leverage: number | null,
gross_position_value: number | null,
unrealized_pnl: number | null,
realized_pnl: number | null,
exchange_rate: number | null,
stock_market_value: number | null,
option_market_value: number | null,
sma: number | null
}
```
**示例响应**
```json
{
"account_id": "U1234567",
"currency": "USD",
"net_liquidation": 125000.50,
"equity_with_loan": 125000.50,
"total_cash": 50000.00,
"buying_power": 250000.00,
"init_margin_req": 15000.00,
"maint_margin_req": 12000.00,
"available_funds": 110000.50,
"excess_liquidity": 113000.50,
"cushion": 0.904,
"leverage": 0.6,
"gross_position_value": 75000.00,
"unrealized_pnl": 2525.00,
"realized_pnl": 0.0,
"exchange_rate": 1.0,
"stock_market_value": 50000.00,
"option_market_value": 25000.00,
"sma": 125000.50
}
```
---
#### ibkr://positions/{account}
获取实时持仓(含 Greeks)。
**URI**: `ibkr://positions/{account}`
**参数**
| 参数 | 类型 | 描述 |
| ----------- | ------ | ----------------------------- |
| `account` | string | 账户 ID(可选,默认所有账户) |
**返回类型**: `PositionsResource`
```typescript
{
positions: PositionRecord[],
count: number
}
```
**PositionRecord 字段**(实时缓存版本)
| 字段 | 类型 | 描述 |
| -------------------- | ----------- | ------------------------ |
| `con_id` | int | 合约 ID |
| `account` | string | 账户 ID |
| `symbol` | string | 合约代码 |
| `underlying` | string | 标的代码 |
| `sec_type` | string | 证券类型 |
| `expiry` | string | 到期日 |
| `strike` | float | 行权价 |
| `right` | string | 期权类型 |
| `multiplier` | float | 乘数 |
| `quantity` | float | 数量 |
| `avg_cost` | float | 平均成本 |
| `market_price` | float | 市场价格 |
| `market_value` | float | 市场价值 |
| `unrealized_pnl` | float | 未实现盈亏 |
| `realized_pnl` | float | 已实现盈亏 |
| `delta` | float\|null | Delta |
| `gamma` | float\|null | Gamma |
| `vega` | float\|null | Vega |
| `theta` | float\|null | Theta |
| `iv` | float\|null | 隐含波动率 |
| `underlying_price` | float\|null | 标的价格 |
| `last_update` | string | 最后更新时间(ISO 8601) |
---
#### ibkr://option_chains/{symbol}
从数据库获取期权链快照(按 CALL/PUT 和高于/低于现价分组)。
**URI**: `ibkr://option_chains/{symbol}`
**参数**
| 参数 | 类型 | 必填 | 描述 |
| --------- | ------ | ---- | ------------------------------- |
| `symbol` | string | 是 | 标的股票代码(如 NVDA, AAPL) |
**返回类型**: `OptionChainResourceResponse`
```typescript
{
symbol: string,
underlying_price: number | null,
timestamp: string,
chains: {
callAbove: OptionSnapshot[],
callBelow: OptionSnapshot[],
putAbove: OptionSnapshot[],
putBelow: OptionSnapshot[]
},
error?: string
}
```
**字段说明**
| 字段 | 类型 | 描述 |
| ------------------ | ------- | ----------------------------------------- |
| `symbol` | string | 标的股票代码 |
| `underlying_price` | number\|null | 标的当前价格 |
| `timestamp` | string | 快照时间(ISO 8601) |
| `chains` | object | 分组后的期权链 |
| `chains.callAbove` | array | CALL 期权,strike > underlying_price |
| `chains.callBelow` | array | CALL 期权,strike <= underlying_price |
| `chains.putAbove` | array | PUT 期权,strike > underlying_price |
| `chains.putBelow` | array | PUT 期权,strike <= underlying_price |
| `error` | string | 错误信息(可选) |
**OptionSnapshot 字段**
| 字段 | 类型 | 描述 |
| ---------------------- | ----------- | ---------------- |
| `id` | int | 数据库 ID |
| `symbol` | string | 标的代码 |
| `expiry` | string | 到期日 (ISO 8601) |
| `strike` | float | 行权价 |
| `option_type` | string | CALL 或 PUT |
| `bid` | float\|null | 买价 |
| `ask` | float\|null | 卖价 |
| `mark` | float\|null | 中间价 |
| `price` | float\|null | 最后成交价 |
| `delta` | float\|null | Delta |
| `gamma` | float\|null | Gamma |
| `vega` | float\|null | Vega |
| `theta` | float\|null | Theta |
| `rho` | float\|null | Rho |
| `implied_volatility` | float\|null | 隐含波动率 |
| `underlying_price` | float\|null | 标的价格 |
| `timestamp` | string | 快照时间 (ISO 8601) |
**示例响应**
```json
{
"symbol": "NVDA",
"underlying_price": 495.50,
"timestamp": "2025-12-24T15:45:00Z",
"chains": {
"callAbove": [
{
"id": 12345,
"symbol": "NVDA",
"expiry": "2025-01-17",
"strike": 500.0,
"option_type": "CALL",
"bid": 6.50,
"ask": 6.80,
"mark": 6.65,
"price": 6.60,
"delta": 0.52,
"gamma": 0.03,
"vega": 0.25,
"theta": -0.08,
"rho": 0.12,
"implied_volatility": 0.32,
"underlying_price": 495.50,
"timestamp": "2025-12-24T15:45:00Z"
}
],
"callBelow": [
{
"id": 12346,
"symbol": "NVDA",
"expiry": "2025-01-17",
"strike": 490.0,
"option_type": "CALL",
"bid": 10.50,
"ask": 10.80,
"mark": 10.65,
"price": 10.70,
"delta": 0.62,
"gamma": 0.04,
"vega": 0.28,
"theta": -0.10,
"rho": 0.15,
"implied_volatility": 0.30,
"underlying_price": 495.50,
"timestamp": "2025-12-24T15:45:00Z"
}
],
"putAbove": [],
"putBelow": [
{
"id": 12347,
"symbol": "NVDA",
"expiry": "2025-01-17",
"strike": 490.0,
"option_type": "PUT",
"bid": 4.20,
"ask": 4.50,
"mark": 4.35,
"price": 4.30,
"delta": -0.38,
"gamma": 0.04,
"vega": 0.28,
"theta": -0.06,
"rho": -0.10,
"implied_volatility": 0.30,
"underlying_price": 495.50,
"timestamp": "2025-12-24T15:45:00Z"
}
]
}
}
```
**错误响应**
```json
{
"symbol": "UNKNOWN",
"underlying_price": null,
"timestamp": null,
"chains": {
"callAbove": [],
"callBelow": [],
"putAbove": [],
"putBelow": []
},
"error": "No data found"
}
```
---
## 2. Option Data Service(期权数据服务)
提供期权链数据获取、策略信号扫描和自动调度功能。
> **系统设计与实现**: 详见 [Option Chain 系统文档](./option-chain-system.md)
### Core Tools
#### get_option_chains
获取期权链快照数据。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| -------------------- | ------------ | ---- | ---------- | ----------------------------------------------------------------------- |
| `symbols` | list[string] | 是 | - | 标的代码列表 |
| `mode` | string | 否 | `"live"` | 数据模式:`"live"` 或 `"local"` |
| `market_data_type` | string | 否 | `"LIVE"` | 行情类型:`"LIVE"`, `"FROZEN"`, `"DELAYED"`, `"DELAYED_FROZEN"` |
| `persist` | bool | 否 | `true` | 是否持久化到本地 |
**返回类型**: `OptionChainsResponse`
```typescript
{
ok: boolean,
mode: string,
market_data_type: string,
symbol_count: number,
snapshot_count: number,
snapshots: OptionChainSnapshot[],
missing_symbols: string[],
persisted: boolean,
data_dir: string
}
```
**OptionChainSnapshot 字段**
| 字段 | 类型 | 描述 |
| -------------------- | ------ | -------------------- |
| `symbol` | string | 标的代码 |
| `underlying_price` | float | 标的当前价格 |
| `timestamp` | string | 快照时间(ISO 8601) |
| `option_count` | int | 期权合约数量 |
| `options` | list | 期权合约列表 |
| `context` | object | 额外上下文信息 |
**Option 记录字段**
| 字段 | 类型 | 描述 |
| ---------------------- | ------ | ----------------------- |
| `symbol` | string | 期权合约代码 |
| `expiry` | string | 到期日 |
| `strike` | float | 行权价 |
| `option_type` | string | 类型("CALL" 或 "PUT") |
| `bid` | float | 买价 |
| `ask` | float | 卖价 |
| `mark` | float | 中间价 |
| `last` | float | 最新成交价 |
| `volume` | int | 成交量 |
| `open_interest` | int | 未平仓合约 |
| `delta` | float | Delta |
| `gamma` | float | Gamma |
| `vega` | float | Vega |
| `theta` | float | Theta |
| `implied_volatility` | float | 隐含波动率 |
**示例响应**
```json
{
"ok": true,
"mode": "live",
"market_data_type": "LIVE",
"symbol_count": 1,
"snapshot_count": 1,
"snapshots": [
{
"symbol": "AAPL",
"underlying_price": 175.50,
"timestamp": "2024-01-15T16:00:00Z",
"option_count": 250,
"options": [
{
"symbol": "AAPL240119C00175000",
"expiry": "2024-01-19",
"strike": 175.0,
"option_type": "CALL",
"bid": 2.50,
"ask": 2.55,
"mark": 2.525,
"delta": 0.52,
"gamma": 0.08,
"vega": 0.15,
"theta": -0.12,
"implied_volatility": 0.25
}
],
"context": {}
}
],
"missing_symbols": [],
"persisted": true,
"data_dir": "optiondata"
}
```
**错误响应**
```json
{
"ok": false,
"error_type": "NO_SYMBOLS",
"message": "At least one symbol is required"
}
```
---
#### scan_option_signals
扫描期权市场并生成策略交易信号。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| -------------------- | ------------ | ---- | ----------------- | ---------------- |
| `symbols` | list[string] | 否 | `null` | 要扫描的标的列表 |
| `strategies` | list[string] | 否 | `null` | 要执行的策略列表 |
| `run_mode` | string | 否 | `"live"` | 运行模式 |
| `market_data_type` | string | 否 | `"LIVE"` | 行情类型 |
| `config_path` | string | 否 | `"config.yaml"` | 配置文件路径 |
**返回类型**: `ScanSignalsResponse`
```typescript
{
ok: boolean,
signals: TradeSignal[],
signal_count: number,
symbols_scanned: string[],
strategies_used: string[]
}
```
**TradeSignal 字段**
| 字段 | 类型 | 描述 |
| --------------- | ------ | --------------------------- |
| `symbol` | string | 标的代码 |
| `expiry` | string | 到期日 |
| `strike` | float | 行权价 |
| `option_type` | string | 期权类型("CALL" 或 "PUT") |
| `direction` | string | 交易方向(见下表) |
| `rationale` | string | 信号理由说明 |
**Direction 取值**
| 值 | 描述 |
| -------------------------- | ---------------------- |
| `SHORT_CALL` | 卖出看涨期权(备兑) |
| `SHORT_CONDOR_CALL` | 铁鹰短看涨腿 |
| `LONG_CONDOR_CALL` | 铁鹰长看涨腿 |
| `SHORT_CONDOR_PUT` | 铁鹰短看跌腿 |
| `LONG_CONDOR_PUT` | 铁鹰长看跌腿 |
| `LONG_PMCC_LEAPS` | PMCC 长期看涨(LEAPS) |
| `SHORT_PMCC_CALL` | PMCC 短期看涨 |
| `BULL_CALL_DEBIT_SPREAD` | 牛市看涨借方价差 |
| `BEAR_PUT_DEBIT_SPREAD` | 熊市看跌借方价差 |
### Scheduler Tools
期权链自动调度器工具,用于定时自动获取期权链数据。
#### get_schedule_status
获取期权链调度器的当前状态和配置。
**返回类型**: `Dict[str, Any]`
**返回字段**
| 字段 | 类型 | 描述 |
| ----------------- | ------- | ----------------------------------- |
| `enabled` | bool | 调度器是否运行 |
| `status` | string | 状态("running" 或 "stopped") |
| `times` | list | 调度时间列表 |
| `timezone` | string | 时区名称 |
| `symbols` | list | 所有监控的标的 |
| `position_symbols` | list | 从持仓中自动检测的标的 |
| `config_symbols` | list | 手动配置的标的 |
| `mode` | string | 运行模式("live" 或 "local") |
| `market_data_type` | string | 行情数据类型 |
| `next_run` | string | 下次运行时间(ISO 8601) |
| `last_run` | string | 上次运行时间(ISO 8601) |
| `run_count` | int | 总运行次数 |
**示例响应**
```json
{
"enabled": true,
"status": "running",
"times": ["09:30", "11:00", "13:30", "15:45"],
"timezone": "America/New_York",
"symbols": ["AAPL", "TSLA", "PLTR"],
"position_symbols": ["AAPL", "TSLA"],
"config_symbols": ["PLTR"],
"mode": "live",
"market_data_type": "LIVE",
"next_run": "2024-12-18T15:45:00-05:00",
"last_run": "2024-12-18T13:30:00-05:00",
"run_count": 156
}
```
---
#### start_option_chain_scheduler
启动期权链调度器。
**返回类型**: `Dict[str, Any]`
**示例响应**
```json
{
"ok": true,
"message": "Option chain scheduler started",
"status": "running"
}
```
---
#### stop_option_chain_scheduler
停止期权链调度器。
**返回类型**: `Dict[str, Any]`
**示例响应**
```json
{
"ok": true,
"message": "Option chain scheduler stopped",
"status": "stopped"
}
```
---
#### restart_option_chain_scheduler
重启期权链调度器。
**返回类型**: `Dict[str, Any]`
**示例响应**
```json
{
"ok": true,
"message": "Option chain scheduler restarted",
"status": "running"
}
```
---
#### run_option_chain_fetch_now
手动触发一次期权链抓取(非阻塞)。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| --------- | ------------ | ---- | ------ | ---------------------------------------- |
| `symbols` | list[string] | 否 | null | 要抓取的标的列表(可选,默认使用所有标的) |
**返回类型**: `Dict[str, Any]`
**返回字段**
| 字段 | 类型 | 描述 |
| ------------ | ------ | ----------------------------- |
| `ok` | bool | 任务是否启动成功 |
| `message` | string | 描述信息 |
| `symbol_count` | int | 抓取的标的数量 |
| `symbols` | list | 抓取的标的列表 |
| `task_id` | int | 后台任务 ID |
| `mode` | string | 抓取模式("live" 或 "local") |
| `started_at` | string | 任务启动时间(ISO 8601) |
**示例响应**
```json
{
"ok": true,
"message": "Manual fetch started for 3 symbols (running in background)",
"symbol_count": 3,
"symbols": ["AAPL", "TSLA", "PLTR"],
"task_id": 12345,
"mode": "live",
"started_at": "2024-12-18T14:30:00-05:00"
}
```
---
#### update_schedule_times
更新调度时间。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| --------- | ------------ | ---- | ------ | ------------------------------------------------ |
| `times` | list[string] | 是 | - | 时间列表,格式为 HH:MM,如 ["09:30", "15:45"] |
| `persist` | bool | 否 | false | 是否同时保存到 config.yaml 文件 |
**返回类型**: `Dict[str, Any]`
**示例响应**
```json
{
"ok": true,
"message": "Schedule times updated from ['09:30', '11:00'] to ['09:30', '11:00', '13:30', '15:45']",
"times": ["09:30", "11:00", "13:30", "15:45"],
"persisted": true,
"restarted": true
}
```
---
#### add_schedule_symbol
添加监控标的到调度列表。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| --------- | ------ | ---- | ------ | ---------------------------------- |
| `symbol` | string | 是 | - | 要添加的标的代码,如 "AAPL" |
| `persist` | bool | 否 | false | 是否同时保存到 config.yaml 文件 |
**返回类型**: `Dict[str, Any]`
**示例响应**
```json
{
"ok": true,
"message": "Added symbol PLTR",
"symbol": "PLTR",
"symbols": ["AAPL", "TSLA", "PLTR"],
"persisted": true,
"restarted": true
}
```
---
#### remove_schedule_symbol
从调度列表移除监控标的。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| --------- | ------ | ---- | ------ | ---------------------------------- |
| `symbol` | string | 是 | - | 要移除的标的代码,如 "AAPL" |
| `persist` | bool | 否 | false | 是否同时保存到 config.yaml 文件 |
**返回类型**: `Dict[str, Any]`
**示例响应**
```json
{
"ok": true,
"message": "Removed symbol TSLA",
"symbol": "TSLA",
"symbols": ["AAPL", "PLTR"],
"persisted": true,
"restarted": true
}
```
---
#### set_schedule_timezone
设置调度时区。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------------ | ------ | ---- | ------ | ------------------------------------------------------------ |
| `timezone` | string | 是 | - | IANA 时区名称,如 "America/New_York", "America/Los_Angeles" |
| `persist` | bool | 否 | false | 是否同时保存到 config.yaml 文件 |
**返回类型**: `Dict[str, Any]`
**示例响应**
```json
{
"ok": true,
"message": "Timezone updated from America/New_York to America/Los_Angeles",
"timezone": "America/Los_Angeles",
"persisted": true,
"restarted": true
}
```
---
#### get_schedule_config
获取当前调度配置(安全可显示)。
**返回类型**: `Dict[str, Any]`
**返回字段**
| 字段 | 类型 | 描述 |
| ------------------ | ------ | ----------------------------- |
| `enabled` | bool | 是否启用 |
| `times` | list | 调度时间列表 |
| `timezone` | string | 时区名称 |
| `symbols` | list | 手动配置的标的列表 |
| `mode` | string | 运行模式 |
| `market_data_type` | string | 行情数据类型 |
**示例响应**
```json
{
"enabled": true,
"times": ["09:30", "11:00", "13:30", "15:45"],
"timezone": "America/New_York",
"symbols": ["PLTR"],
"mode": "live",
"market_data_type": "LIVE"
}
```
---
#### reset_schedule_config
重置调度配置为默认值。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| --------- | ------ | ---- | ------ | ---------------------------------- |
| `persist` | bool | 否 | false | 是否同时保存到 config.yaml 文件 |
**返回类型**: `Dict[str, Any]`
**默认配置**
```json
{
"enabled": true,
"times": ["09:30", "11:00", "13:30", "15:45"],
"timezone": "America/New_York",
"symbols": [],
"mode": "live",
"market_data_type": "LIVE"
}
```
**示例响应**
```json
{
"ok": true,
"message": "Schedule config reset to defaults",
"old_config": {
"enabled": true,
"times": ["09:30", "11:00", "13:30", "15:45"],
"timezone": "America/New_York",
"symbols": ["PLTR"],
"mode": "live",
"market_data_type": "LIVE"
},
"new_config": {
"enabled": true,
"times": ["09:30", "11:00", "13:30", "15:45"],
"timezone": "America/New_York",
"symbols": [],
"mode": "live",
"market_data_type": "LIVE"
},
"persisted": true,
"restarted": true
}
```
### Snapshot Status Tools
期权链快照状态管理工具。
#### list_option_snapshots
列出最近的期权链快照。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| -------- | ------ | ---- | ------ | ---------------------------------------- |
| `symbol` | string | 否 | null | 标的过滤器(可选,不提供则显示所有标的) |
| `limit` | int | 否 | 10 | 返回的最大快照数量 |
**返回类型**: `Dict[str, Any>`
**⚠️ 状态**: 此功能尚未实现
**返回字段**
| 字段 | 类型 | 描述 |
| ----------------- | ------ | ------------------------ |
| `ok` | bool | 固定为 false |
| `error_type` | string | 固定为 "NOT_IMPLEMENTED" |
| `message` | string | 错误描述信息 |
**示例响应**
```json
{
"ok": false,
"error_type": "NOT_IMPLEMENTED",
"message": "This feature is not yet implemented"
}
```
---
#### get_snapshot_status
获取特定快照的详细状态。
**参数**
| 参数 | 类型 | 必填 | 描述 |
| -------- | ------ | ---- | ---------------------- |
| `symbol` | string | 是 | 要检查的股票标的代码 |
**返回类型**: `Dict[str, Any>`
**⚠️ 状态**: 此功能尚未实现
**示例响应**
```json
{
"ok": false,
"error_type": "NOT_IMPLEMENTED",
"message": "This feature is not yet implemented"
}
```
---
#### check_snapshot_freshness
检查所有快照的新鲜度。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ----------------- | ---- | ---- | ------ | ---------------------------------------- |
| `max_age_minutes` | int | 否 | 60 | 超过此时间的快照被视为过期(默认 60 分钟) |
**返回类型**: `Dict[str, Any>`
**⚠️ 状态**: 此功能尚未实现
**示例响应**
```json
{
"ok": false,
"error_type": "NOT_IMPLEMENTED",
"message": "This feature is not yet implemented"
}
```
---
## 3. Risk Service(风险管理服务)
提供投资组合风险评估和调仓建议功能。
### Tools
#### evaluate_portfolio_risk
评估投资组合风险,检查是否突破风险限额。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| --------------- | ------ | ---- | --------------- | -------------------------------- |
| `account` | string | 否 | `""` | 账户 ID |
| `config` | object | 否 | `null` | 直接传入的风险配置(优先级最高) |
| `config_path` | string | 否 | `"risk.yaml"` | 风险配置文件路径 |
**返回类型**: `RiskEvaluationResponse`
```typescript
{
ok: boolean,
account: string | null,
config_path: string | null,
position_count: number,
limits: RiskLimits,
roll_rules: RollRules,
greeks: {
per_symbol: SymbolGreeks[],
totals: GreekTotals
},
concentration: {
per_symbol: ConcentrationRecord[],
series: Record<string, number>,
totals: { gross_total: number }
},
breaches: RiskBreach[]
}
```
**RiskBreach 字段**
| 字段 | 类型 | 描述 |
| ---------- | ------------ | ------------------------- |
| `metric` | string | 违规指标名称 |
| `symbol` | string\|null | 相关标的(组合级为 null) |
| `value` | float | 当前值 |
| `limit` | float | 限额值 |
| `detail` | string | 违规详情描述 |
**示例响应**
```json
{
"ok": true,
"account": "U1234567",
"config_path": "risk.yaml",
"position_count": 5,
"limits": {
"delta": {"per_symbol": 500, "total": 3000},
"gamma": {"per_symbol": 50, "total": 200},
"vega": {"per_symbol": 10000, "total": 30000},
"theta_min": 50,
"concentration": {"max_symbol_pct_gross": 0.2},
"liquidity": {"min_open_interest": 500, "max_bid_ask_spread_pct": 2.0}
},
"roll_rules": {
"pmcc": {"take_profit_pct": 0.65, "roll_up_if_short_delta_gt": 0.4, "roll_out_days": 21},
"condor": {"take_profit_pct": 0.6}
},
"greeks": {
"per_symbol": [{"underlying": "AAPL", "delta": 550.0, "gamma": 3.2, "vega": 800.0, "theta": -30.0, "rho": 0.0}],
"totals": {"delta": 550.0, "gamma": 3.2, "vega": 800.0, "theta": -30.0, "rho": 0.0}
},
"concentration": {
"per_symbol": [{"underlying": "AAPL", "gross_exposure": 17550.0, "gross_pct": 0.25}],
"series": {"AAPL": 0.25},
"totals": {"gross_total": 70200.0}
},
"breaches": [
{
"metric": "Delta per-symbol",
"symbol": "AAPL",
"value": 550.0,
"limit": 500.0,
"detail": "AAPL delta 550.00 exceeds 500"
}
]
}
```
---
#### generate_playbook_actions
基于当前持仓和风险规则生成调整建议。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| --------------- | ------ | ---- | --------------- | ------------------ |
| `account` | string | 否 | `""` | 账户 ID |
| `config` | object | 否 | `null` | 直接传入的风险配置 |
| `config_path` | string | 否 | `"risk.yaml"` | 风险配置文件路径 |
**返回类型**: `PlaybookActionsResponse`
```typescript
{
ok: boolean,
account: string | null,
config_path: string | null,
position_count: number,
limits: RiskLimits,
roll_rules: RollRules,
actions: string[],
breaches: RiskBreach[],
greeks: {
per_symbol: SymbolGreeks[],
totals: GreekTotals
}
}
```
**示例响应**
```json
{
"ok": true,
"account": "U1234567",
"config_path": "risk.yaml",
"position_count": 3,
"limits": {"delta": {"per_symbol": 500, "total": 3000}},
"roll_rules": {"pmcc": {"take_profit_pct": 0.65, "roll_up_if_short_delta_gt": 0.4, "roll_out_days": 21}},
"actions": [
"PMCC AAPL: close short AAPL 250321C00200000 (+65% credit), re-sell near-40Δ call 21DTE (65% credit captured; short delta 0.45)"
],
"breaches": [],
"greeks": {
"per_symbol": [{"underlying": "AAPL", "delta": 280.0, "gamma": 2.1, "vega": 500.0, "theta": -18.0, "rho": 0.0}],
"totals": {"delta": 280.0, "gamma": 2.1, "vega": 500.0, "theta": -18.0, "rho": 0.0}
}
}
```
---
## 4. News Service(新闻服务)
提供历史新闻获取功能。
### Tools
#### get_historical_news
获取标的的历史新闻。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| -------------- | ------ | ---- | ----------- | ---------------------- |
| `symbol` | string | 是 | - | 标的代码 |
| `start_date` | string | 否 | 30天前 | 开始日期(YYYY-MM-DD) |
| `end_date` | string | 否 | 今天 | 结束日期(YYYY-MM-DD) |
| `max_count` | int | 否 | `10` | 最大返回条数(1-100) |
| `exchange` | string | 否 | `"SMART"` | 交易所 |
| `currency` | string | 否 | `"USD"` | 货币 |
| `conid` | int | 否 | `null` | 直接指定合约 ID |
**返回类型**: `HistoricalNewsResponse`
```typescript
{
ok: boolean,
symbol: string,
conid: number,
period: { start: string, end: string },
articles: NewsArticle[],
total_count: number
}
```
**NewsArticle 字段**
| 字段 | 类型 | 描述 |
| -------------- | ------ | ------------ |
| `headline` | string | 新闻标题 |
| `timestamp` | string | 发布时间 |
| `provider` | string | 新闻来源代码 |
| `article_id` | string | 文章 ID |
**示例响应**
```json
{
"ok": true,
"symbol": "AAPL",
"conid": 265598,
"period": {"start": "2024-01-01", "end": "2024-01-15"},
"articles": [
{
"headline": "Apple Reports Record Q4 Revenue",
"timestamp": "2024-01-10T14:30:00",
"provider": "DJ-N",
"article_id": "DJ-N20240110143000"
}
],
"total_count": 1
}
```
**错误响应**
```json
{
"ok": false,
"error_type": "INVALID_DATE_RANGE",
"message": "Start date 2024-02-01 must be before end date 2024-01-01",
"symbol": "AAPL"
}
```
---
## 错误类型
所有返回 `ok: false` 的响应都包含以下字段:
| 字段 | 类型 | 描述 |
| -------------- | ------- | ---------------- |
| `ok` | boolean | 固定为 `false` |
| `error_type` | string | 错误类型代码 |
| `message` | string | 错误描述 |
**常见错误类型**
| error_type | 描述 |
| ----------------------- | ---------------- |
| `NO_SYMBOLS` | 未提供标的代码 |
| `INVALID_MODE` | 无效的运行模式 |
| `FETCH_FAILED` | 数据获取失败 |
| `NO_CONTRACT` | 找不到合约 |
| `INVALID_DATE_RANGE` | 无效的日期范围 |
| `INVALID_DATE_FORMAT` | 日期格式错误 |
| `IB_ERROR` | IBKR API 错误 |
| `NOT_CONNECTED` | 未连接到 IBKR |
| `NOT_IMPLEMENTED` | 功能未实现 |
| `INVALID_CONFIG` | 配置无效 |
| `UPDATE_FAILED` | 更新失败 |
| `INVALID_SYMBOL` | 无效的标的代码 |
| `SYMBOL_EXISTS` | 标的已存在 |
| `SYMBOL_NOT_FOUND` | 找不到标的 |
| `INVALID_TIMEZONE` | 无效的时区 |
| **授权验证错误** | |
| `QUOTA_EXCEEDED` | 每日调用配额已用尽 |
| `PRO_REQUIRED` | 需要 PRO 账户才能使用此功能 |
| `PREMIUM_REQUIRED` | 需要 PREMIUM 账户才能使用此功能 |
---
## 授权验证与配额
IBKR-MCP 采用分层授权系统,通过 API Key 管理用户权限层级。
### 配额模型
| 层级 | API Key | 每月配额 | 同步方式 |
|------|---------|----------|----------|
| **无 Key** | 无 | 50 次 | 本地缓存 |
| **Free Key** | `AM` + 29字符 | 500 次 | 云端追踪(未来) |
| **Pro Key** | `AM` + 29字符 | 2000 次 | 云端追踪(未来) |
| **Premium Key** | `AM` + 29字符 | 5000 次 | 云端追踪(未来) |
### 权限层级
所有 MCP Tools 和 Resources(除 `ibkr://auth_status` 外)均需通过授权验证:
| 装饰器 | 无 Key | Free Key | Pro Key | Premium Key |
|--------|--------|----------|---------|-------------|
| `@require_tier()` | ✅ 配额 50 | ✅ 配额 500 | ✅ 配额 2000 | ✅ 配额 5000 |
| `@require_tier(PRO)` | ❌ | ❌ | ✅ 配额 2000 | ✅ 配额 5000 |
| `@require_tier(PREMIUM)` | ❌ | ❌ | ❌ | ✅ 配额 5000 |
### 错误响应格式
```json
// Quota exceeded
{
"error": "QUOTA_EXCEEDED",
"message": "Monthly quota exceeded (50/50), upgrade: https://alphameta.app"
}
// PRO permission required
{
"error": "PRO_REQUIRED",
"message": "PRO account required, upgrade: https://alphameta.app"
}
// PREMIUM permission required
{
"error": "PREMIUM_REQUIRED",
"message": "PREMIUM account required, upgrade: https://alphameta.app"
}
```
### Resources
#### ibkr://auth_status
获取当前授权状态和配额使用情况。此资源**不消耗配额**。
**URI**: `ibkr://auth_status`
**返回类型**: `AuthStatus`
```typescript
{
tier: string, // 当前权限层级 (free/pro/premium)
used: number, // 已使用次数
quota: number, // 每月配额
remaining: number, // 剩余次数
api_key_configured: boolean // 是否已配置 API Key
}
```
**示例响应**
```json
{
"tier": "free",
"used": 5,
"quota": 50,
"remaining": 45,
"api_key_configured": false
}
```
---
## 使用示例
### AlphaMeta Desktop 中的自然语言查询
```
用户: 我的账户余额是多少?
→ 读取 ibkr://account_summary
用户: 显示我所有持仓的 Greeks
→ 调用 get_greeks_summary
用户: AAPL 下个月到期的期权链
→ 调用 get_option_chains(symbols=["AAPL"])
用户: 评估我的组合风险,有没有超限?
→ 调用 evaluate_portfolio_risk
用户: 给我一些调仓建议
→ 调用 generate_playbook_actions
用户: 启动期权链自动抓取
→ 调用 start_option_chain_scheduler
用户: 查看调度器状态
→ 调用 get_schedule_status
用户: 添加 TSLA 到自动抓取列表
→ 调用 add_schedule_symbol(symbol="TSLA", persist=True)
用户: 手动抓取一次期权链
→ 调用 run_option_chain_fetch_now(symbols=["AAPL", "TSLA"])
用户: 获取 AAPL 最近一周的新闻
→ 调用 get_historical_news(symbol="AAPL", start_date="2024-12-11", end_date="2024-12-18")
```
---
## 下一步实现计划
以下工具计划在后续版本中实现,以提供更完整的市场数据和基本面分析能力。
### get_historical_data(计划中)
获取历史 OHLCV(开高低收量)数据。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
|------|------|------|--------|------|
| `symbol` | string | 是 | - | 标的代码 |
| `duration` | string | 否 | `"1 M"` | 数据时长(如 `"5 D"`, `"1 M"`, `"1 Y"`) |
| `bar_size` | string | 否 | `"1 day"` | K 线周期 |
| `data_type` | string | 否 | `"TRADES"` | 数据类型 |
| `max_bars` | int | 否 | `20` | 返回最大条数(上限 500) |
| `exchange` | string | 否 | `"SMART"` | 交易所 |
| `currency` | string | 否 | `"USD"` | 货币 |
**数据时长 (duration) 格式**
| 格式 | 描述 | 示例 |
|------|------|------|
| `S` | 秒 | `30 S` |
| `D` | 天 | `5 D` |
| `W` | 周 | `2 W` |
| `M` | 月 | `1 M` |
| `Y` | 年 | `1 Y` |
**K 线周期 (bar_size) 选项**
- 秒级: `1 secs`, `5 secs`, `10 secs`, `15 secs`, `30 secs`
- 分钟级: `1 min`, `2 mins`, `3 mins`, `5 mins`, `10 mins`, `15 mins`, `20 mins`, `30 mins`
- 小时级: `1 hour`, `2 hours`, `3 hours`, `4 hours`, `8 hours`
- 日/周/月: `1 day`, `1 week`, `1 month`
**数据类型 (data_type) 选项**
| 类型 | 描述 |
|------|------|
| `TRADES` | 成交价 |
| `MIDPOINT` | 中间价 |
| `BID` | 买价 |
| `ASK` | 卖价 |
| `BID_ASK` | 买卖价 |
| `HISTORICAL_VOLATILITY` | 历史波动率 |
| `OPTION_IMPLIED_VOLATILITY` | 期权隐含波动率 |
**预期返回类型**: `HistoricalDataResponse`
```typescript
{
ok: boolean,
symbol: string,
conid: number,
bar_size: string,
duration: string,
data_type: string,
bars: BarData[],
bar_count: number
}
```
**BarData 字段**
| 字段 | 类型 | 描述 |
|------|------|------|
| `date` | string | 日期时间 |
| `open` | float | 开盘价 |
| `high` | float | 最高价 |
| `low` | float | 最低价 |
| `close` | float | 收盘价 |
| `volume` | int | 成交量 |
| `average` | float | 均价(可选) |
| `bar_count` | int | 成交笔数(可选) |
**预期示例响应**
```json
{
"ok": true,
"symbol": "AAPL",
"conid": 265598,
"bar_size": "1 day",
"duration": "1 M",
"data_type": "TRADES",
"bars": [
{
"date": "2024-12-06",
"open": 230.50,
"high": 231.25,
"low": 230.10,
"close": 230.75,
"volume": 45000000,
"average": 230.65,
"bar_count": 125000
}
],
"bar_count": 22
}
```
---
### get_fundamental_data(计划中)
获取公司基本面财务数据。
**参数**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
|------|------|------|--------|------|
| `symbol` | string | 是 | - | 标的代码 |
| `report_type` | string | 否 | `"ReportsFinSummary"` | 报告类型 |
| `exchange` | string | 否 | `"SMART"` | 交易所 |
| `currency` | string | 否 | `"USD"` | 货币 |
**报告类型 (report_type) 选项**
| 类型 | 描述 |
|------|------|
| `ReportsFinSummary` | 财务摘要(收益、估值、盈利能力指标) |
| `ReportsOwnership` | 股权结构(机构持股、内部人持股) |
| `ReportsFinStatements` | 财务报表(资产负债表、损益表、现金流量表) |
| `RESC` | 研究报告(分析师评级、目标价) |
| `CalendarReport` | 财务日历(财报日期、分红日期) |
**预期返回类型**: `FundamentalDataResponse`
```typescript
{
ok: boolean,
symbol: string,
conid: number,
report_type: string,
data: FundamentalReport
}
```
**FundamentalReport 字段(ReportsFinSummary 类型)**
| 字段 | 类型 | 描述 |
|------|------|------|
| `eps` | float | 每股收益 |
| `pe_ratio` | float | 市盈率 |
| `book_value_per_share` | float | 每股账面价值 |
| `gross_margin` | float | 毛利率 |
| `operating_margin` | float | 营业利润率 |
| `net_margin` | float | 净利润率 |
| `revenue_growth` | float | 收入增长率 |
| `eps_growth` | float | EPS 增长率 |
| `market_cap` | float | 市值 |
| `enterprise_value` | float | 企业价值 |
| `ev_ebitda` | float | EV/EBITDA |
| `dividend_yield` | float | 股息收益率 |
| `payout_ratio` | float | 派息率 |
**预期示例响应**
```json
{
"ok": true,
"symbol": "AAPL",
"conid": 265598,
"report_type": "ReportsFinSummary",
"data": {
"eps": 6.42,
"pe_ratio": 35.8,
"book_value_per_share": 4.25,
"gross_margin": 0.4596,
"operating_margin": 0.3074,
"net_margin": 0.2631,
"revenue_growth": 0.085,
"eps_growth": 0.123,
"market_cap": 2890000000000,
"enterprise_value": 2950000000000,
"ev_ebitda": 24.5,
"dividend_yield": 0.0044,
"payout_ratio": 0.156
}
}
```
**数据订阅要求**
> ⚠️ 注意:基本面数据需要订阅 IBKR 的 "Fundamentals for IBKR" 数据包。
---
### 实现优先级
| 优先级 | 服务类型 | 工具 | 理由 |
|--------|----------|------|------|
| 🔴 高 | Option Data | `get_historical_data` | 历史数据是技术分析和回测的基础 |
| 🟡 中 | Option Data | `get_fundamental_data` | 基本面分析对价值投资和期权定价有帮助 |
| 🟢 低 | Option Data | 完善快照状态工具 | 需要先实现底层存储机制 |