futu-mcp-guide

A practical pitfall-avoidance guide for developers with Python and MCP experience to implement Futu MCP services using futu-api, covering core code and hands-on tips from establishing OpenD connections to registering the first MCP tool. Applicable to building Agent-callable Futu MCP services and related market/trading logic, holdings queries, and code standardization scenarios.

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "futu-mcp-guide" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-bd4803119e8db1ab4e7583413df6d3b979fd8357f53ab233bce9d1a4e94dcd2d. Verify the upstream source and version against https://skillhub.cn/skills/user_b785198a/futu-mcp-guide before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

skillhub.cn

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

A practical pitfall-avoidance guide for developers with Python and MCP experience to implement Futu MCP services using futu-api, covering core code and hands-on tips from establishing OpenD connections to registering the first MCP tool. Applicable to building Agent-callable Futu MCP services and related market/trading logic, holdings queries, and code standardization scenarios.

0 Downloads

Introduction source: third_party · user_b785198a · 1.0.0 Reference

SkillPi interpretation

Tasks
Translation pending; see source documentation.
Software, accounts and paid services
Translation pending; see source documentation.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: futu-mcp-guide
description: >
  用 futu-api 实现富途 MCP 服务的关键避坑指南。面向有 Python / MCP 经验的开发者,
  提供从打通 OpenD 连接到注册第一个 MCP 工具的关键代码和踩坑经验。
  富途官方尚未提供 MCP 服务,本 Skill 帮你通过 futu-api 自行实现一个可被 Agent 调用的 futu MCP。
  触发场景:开发富途 MCP 工具、调用 futu-api 编写行情/交易代码、调试 OpenD 连接、
  处理综合账户持仓查询、标准化股票代码、任何涉及港股/美股/A股数据开发的场景。

用 futu-api 实现富途 MCP 服务

目标:你是一个有技术能力的开发者,拿到这个 Skill 就能用 futu-api 实现一个可被 Agent 调用的富途 MCP 服务。本文只管"关键避坑代码",MCP 框架选型和工程架构由你自行决定。

使用方式:直接告诉 Agent "请你用 futu-mcp-guide Skill,帮我实现一个富途 MCP 的 xxx 功能",Agent 会自动按本文的避坑代码和模式生成正确实现。遇到具体问题时,可以让 Agent 查阅 references/ 下的三份详细文档获取更多上下文。

总览:从 0 到 1 的关键路径

flowchart TD
    A["① 环境与安全<br/>配置 .env,敏感信息不入库"] --> B["② 打通 futu-api 连接<br/>OpenSecTradeContext + FUTUSECURITIES<br/>OpenD ≥ 10.x"]
    B --> C["③ 实现第一个工具函数<br/>get_real_positions()"]
    C --> D["④ 注册为 MCP 工具<br/>在你的 MCP 框架中挂载"]
    D --> E["⑤ 扩展更多能力<br/>行情 / 下单 / 撤单 / 成交<br/>按避坑清单复用模式"]

① 环境与安全

所有凭证必须通过 .env 或 os.getenv() 读取,绝不硬编码:

敏感项 说明
FUTU_HOST / FUTU_PORT OpenD 连接地址
login_account / login_pwd_md5 富途账号与密码
TRADE_PASSWORD 交易解锁密码
acc_id 真实值 账户 ID
RSA 私钥 / WebSocket 鉴权密钥 加密凭证

示例代码中一律使用占位符(your_account、your_password)。

运维提示:OpenD 和 MCP 服务都推荐通过 bash start.sh start|stop|restart 管理生命周期,禁止手动 nohup/systemd 起进程。


② 打通 futu-api 连接

这一步有 3 个必踩的坑,全部踩过才总结出来的:

坑 1:必须用 OpenSecTradeContext + SecurityFirm.FUTUSECURITIES

富途 2022 年升级了"综合账户"体系,旧的 OpenHKTradeContext / OpenUSTradeContext 拿不到真实账户数据。

# ❌ 错误:用旧上下文,综合账户下查不到数据
from futu import OpenHKTradeContext
ctx = OpenHKTradeContext(host=FUTU_HOST, port=FUTU_PORT)

# ✅ 正确:必须用 OpenSecTradeContext
from futu import OpenSecTradeContext, SecurityFirm, TrdMarket

ctx = OpenSecTradeContext(
    filter_trdmarket=TrdMarket.HK,
    host=FUTU_HOST,
    port=FUTU_PORT,
    security_firm=SecurityFirm.FUTUSECURITIES  # 支持综合账户的关键参数
)

坑 2:OpenD 版本必须 ≥ 10.0

7.x ~ 8.2 版本的 OpenD 不支持综合账户协议(needGeneralSecAccount),即使代码写对了也拿不到真实数据。项目从 7.1.3308 升级到 10.0.6018 后才解决。

坑 3:持仓查询必须先获取 acc_id

直接调 position_list_query() 不传 acc_id 会返回空数据。正确流程是三步走:

get_acc_list() → 遍历找 TrdEnv.REAL 的 acc_id → 传入 acc_id 查询

③ 实现第一个工具函数:获取真实持仓

下面是一个可直接复制使用的完整示例,已包含上面所有避坑点。你只需改成自己的配置即可运行:

核心函数:创建交易上下文

import os
from futu import (
    OpenSecTradeContext, OpenQuoteContext, SecurityFirm,
    TrdMarket, TrdEnv, RET_OK
)

FUTU_HOST = os.getenv("FUTU_HOST", "127.0.0.1")
FUTU_PORT = int(os.getenv("FUTU_PORT", "11111"))

# 市场 → TrdMarket 映射
MARKET_MAP = {
    "HK": TrdMarket.HK,
    "US": TrdMarket.US,
    "CN": TrdMarket.CN,
}

# 全局单例,避免反复创建连接
_trade_ctx_cache = {}
_quote_ctx = None


def get_trade_ctx(market: str = "HK") -> OpenSecTradeContext:
    """获取指定市场的交易上下文(单例 + 懒加载)。

    Args:
        market: 市场代码,支持 "HK" / "US" / "CN"

    Returns:
        OpenSecTradeContext 实例
    """
    global _trade_ctx_cache
    if market not in _trade_ctx_cache:
        _trade_ctx_cache[market] = OpenSecTradeContext(
            filter_trdmarket=MARKET_MAP.get(market, TrdMarket.HK),
            host=FUTU_HOST,
            port=FUTU_PORT,
            security_firm=SecurityFirm.FUTUSECURITIES,
        )
    return _trade_ctx_cache[market]


def get_quote_ctx() -> OpenQuoteContext:
    """获取行情上下文(单例)。

    Returns:
        OpenQuoteContext 实例
    """
    global _quote_ctx
    if _quote_ctx is None:
        _quote_ctx = OpenQuoteContext(host=FUTU_HOST, port=FUTU_PORT)
    return _quote_ctx

核心函数:获取真实账户 ID

def get_real_acc_id(ctx: OpenSecTradeContext) -> int:
    """从账户列表中找到真实交易账户的 acc_id(三步法的前两步)。

    Args:
        ctx: OpenSecTradeContext 实例

    Returns:
        真实账户的 acc_id

    Raises:
        RuntimeError: 获取失败或未找到真实账户
    """
    ret, acc_data = ctx.get_acc_list()
    if ret != RET_OK:
        raise RuntimeError(f"获取账户列表失败: {acc_data}")

    for _, row in acc_data.iterrows():
        if row.get("trd_env") == TrdEnv.REAL:
            return row.get("acc_id")

    raise RuntimeError("未找到真实交易账户")

核心函数:股票代码标准化

def normalize_code(code: str) -> str:
    """将用户输入的各种格式统一为富途标准格式。

    Args:
        code: 用户输入的股票代码,如 "00700"、"AAPL"、"HK.00700"

    Returns:
        标准化后的代码,如 "HK.00700"、"US.AAPL"
    """
    code = code.strip().upper()
    if "." in code:
        return code
    if code.isdigit() and len(code) <= 5:
        return f"HK.{code.zfill(5)}"
    if code.isdigit() and len(code) == 6:
        prefix = "SH" if code.startswith("6") else "SZ"
        return f"{prefix}.{code}"
    return f"US.{code}"

完整 Handler:获取真实持仓

这就是你注册到 MCP 框架的工具函数,复制进去改个工具名就能用:

def get_real_positions(market: str = "HK") -> dict:
    """获取指定市场的真实账户持仓列表。

    Args:
        market: 市场代码,"HK"(港股)/ "US"(美股)/ "CN"(A股)

    Returns:
        成功时返回 {"success": True, "data": [...], "acc_id": xxx}
        失败时返回 {"success": False, "error": "错误描述"}
    """
    try:
        ctx = get_trade_ctx(market)
        acc_id = get_real_acc_id(ctx)

        ret, data = ctx.position_list_query(
            code="",
            trd_env=TrdEnv.REAL,
            acc_id=acc_id,
        )

        if ret == RET_OK:
            return {
                "success": True,
                "data": data.to_dict(orient="records"),  # ← DataFrame 必须转 dict
                "acc_id": acc_id,
            }
        return {"success": False, "error": str(data)}

    except Exception as e:
        return {"success": False, "error": str(e)}

在你的 MCP 框架中注册

不管你用什么 MCP 框架(FastMCP、自研、mcp-server-sdk 等),只需把上面的 get_real_positions 挂载为一个 tool:

# 示例:FastMCP 风格
@mcp.tool()
def get_position(market: str = "HK") -> dict:
    """获取真实账户持仓"""
    return get_real_positions(market)

# 示例:原生 MCP SDK 风格
server.add_tool("get_position", get_real_positions, description="获取真实账户持仓")

到这里,你的第一个 futu MCP 工具就能工作了。


④ 扩展更多能力时的通用避坑清单

新增任何工具时,对照这张表检查一遍即可:

# 避坑点 关键代码 / 做法
1 交易上下文必须用 OpenSecTradeContext security_firm=SecurityFirm.FUTUSECURITIES
2 OpenD 版本 ≥ 10.0 低版本不支持综合账户协议
3 持仓/订单/成交查询必须传 acc_id 用 get_real_acc_id() 获取
4 DataFrame 返回值必须转换 data.to_dict(orient='records')
5 下单前必须解锁交易 ctx.unlock_trade(password=os.getenv("TRADE_PASSWORD"))
6 测试与现网代码逻辑一致 禁止 if env == "test" 分支,差异仅通过 .env 配置区分
7 股票代码需要标准化 用 normalize_code() 统一处理
8 敏感信息不入库 账号/密码/密钥一律 os.getenv()

⑤ 支持的市场与代码格式

市场 代码前缀 TrdMarket 示例
港股 HK TrdMarket.HK HK.00700
美股 US TrdMarket.US US.AAPL
沪股 SH TrdMarket.CN SH.600000
深股 SZ TrdMarket.CN SZ.000001

交易环境默认为 TrdEnv.REAL(真实账户),如需模拟交易必须显式传入 trd_env="SIMULATE"。


参考资料

本 Skill 的 references/ 目录下提供三份详细文档,覆盖从 0 到 1 的完整路径:

文档 覆盖内容 什么时候看
references/opend-setup.md OpenD 安装、版本选择、首次登录、部署架构、常见问题排查 搭环境时
references/api-cookbook.md 全部 futu-api 调用示例(行情 7 个 + 交易 6 个)、HTTP curl 示例 写工具函数时
references/mcp-integration.md MCP 协议对接(FastMCP / 手动 SSE)、客户端配置、工具注册模式 接 MCP 协议时

外部文档:

Current listing version

1.0.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value82/100

Highlights

  • 面向开发者提供futu-api实现MCP服务的关键避坑指南,解决实际开发痛点
  • 覆盖从OpenD连接到注册MCP工具的完整路径,实用性强
Trigger Precision88/100

Highlights

  • 触发场景描述清晰,涵盖开发、调试、查询、标准化等关键使用场景
  • 边界明确,不易与其他Skill混淆
Structure and Standards92/100

Highlights

  • 文档结构清晰,分步骤引导,配有流程图、代码示例和避坑清单
  • frontmatter完整,示例丰富,易于理解和执行
Execution Reliability85/100

Highlights

  • 提供完整可运行的Python代码示例,包含错误处理和异常捕获
  • 敏感信息通过环境变量管理,下单前解锁交易,DataFrame正确转换
Evidence Verifiability (mean of the first four)87/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

  • Invoke commands or scripts

    Read the script and arguments first. Use ordinary privileges and a scoped directory; confirm installation or execution in your host tool.

    Mentioned in main document · lines 43
  • Accounts, secrets or authorization

    Use a dedicated least-privilege account. Keep secrets out of public content and command logs; verify the receiving service and tenant.

    Mentioned in main document · lines 39, 263
Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • modelcontextprotocol.io
  • openapi.futunn.com

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Translation pending; see source documentation.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.