Futu Stock MCP Server

Futu Stock MCP Server

富途牛牛股票的 MCP 服务器 (Fùtú Niúniú gǔpiào de MCP fúwùqì) This translates to: "MCP server for Futu Niuniu stock"

shuizhengqi1

研究与数据
访问服务器

README

富途证券 MCP 服务器

Python 版本 许可证 OpenAPI

基于模型上下文协议(MCP)的富途证券行情交易接口服务器。将富途OpenAPI功能以标准化的MCP协议提供给AI模型使用,支持行情订阅、数据查询等功能。

🌟 特性

  • 🔌 完全兼容 MCP 2.0 协议标准
  • 📊 支持港股、美股、A股等市场的实时行情
  • 🔄 支持实时数据订阅和推送
  • 📈 支持K线、逐笔、买卖盘等多维度数据
  • 🔒 安全的API调用和数据访问机制
  • 🛠 提供完整的开发工具和示例代码

⚠️ 前置要求

在使用本项目之前,您需要:

  1. 拥有富途证券账户并开通OpenAPI权限
  2. 安装并运行富途的OpenD网关程序(官方文档
  3. 根据您的需求订阅相应的行情权限

🔒 安全提示

  • 请勿在代码中硬编码任何账号密码信息
  • 确保.env文件已添加到.gitignore
  • 妥善保管您的API访问凭证
  • 遵守富途OpenAPI的使用条款和限制

📝 免责声明

本项目是一个开源工具,旨在简化富途OpenAPI的接入流程。使用本项目时请注意:

  1. 遵守相关法律法规和富途OpenAPI的使用条款
  2. 自行承担使用本项目进行交易的风险
  3. 本项目不提供任何投资建议
  4. 使用本项目前请确保您已获得所需的行情权限

Features

  • Standard MCP 2.0 protocol compliance
  • Comprehensive Futu API coverage
  • Real-time data subscription support
  • Market data access
  • Derivatives information
  • Account query capabilities
  • Resource-based data access
  • Interactive prompts for analysis

Prerequisites

  • Python 3.10+
  • Futu OpenAPI SDK
  • Model Context Protocol SDK
  • uv (recommended)

Installation

  1. Clone the repository:
git clone https://github.com/yourusername/futu-stock-mcp-server.git
cd futu-stock-mcp-server
  1. Install uv:
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# Windows (PowerShell)
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
  1. Create and activate a virtual environment:
# Create virtual environment
uv venv

# Activate virtual environment
# On macOS/Linux:
source .venv/bin/activate
# On Windows:
.venv\Scripts\activate
  1. Install dependencies:
# Install in editable mode
uv pip install -e .
  1. Copy the environment file and configure:
cp .env.example .env

Edit the .env file with your server settings:

HOST=0.0.0.0
PORT=8000
FUTU_HOST=127.0.0.1
FUTU_PORT=11111

Development

Managing Dependencies

Add new dependencies to pyproject.toml:

[project]
dependencies = [
    # ... existing dependencies ...
    "new-package>=1.0.0",
]

Then update your environment:

uv pip install -e .

Code Style

This project uses Ruff for code linting and formatting. The configuration is in pyproject.toml:

[tool.ruff]
line-length = 100
target-version = "py38"

[tool.ruff.lint]
select = ["E", "F", "I", "N", "W", "B", "UP"]

Run linting:

uv pip install ruff
ruff check .

Run formatting:

ruff format .

Usage

  1. Start the server:
python -m futu_stock_mcp_server.server
  1. Connect to the server using an MCP client:
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    server_params = StdioServerParameters(
        command="python",
        args=["src/server.py"]
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the connection
            await session.initialize()
            
            # List available tools
            tools = await session.list_tools()
            
            # Call a tool
            result = await session.call_tool(
                "get_stock_quote",
                arguments={"symbols": ["HK.00700"]}
            )
            
            # Access a resource
            content, mime_type = await session.read_resource(
                "market://HK.00700"
            )
            
            # Get a prompt
            prompt = await session.get_prompt(
                "market_analysis",
                arguments={"symbol": "HK.00700"}
            )

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Available API Methods

Market Data Tools

  • get_stock_quote: Get stock quote data
  • get_market_snapshot: Get market snapshot
  • get_cur_kline: Get current K-line data
  • get_history_kline: Get historical K-line data
  • get_rt_data: Get real-time data
  • get_ticker: Get ticker data
  • get_order_book: Get order book data
  • get_broker_queue: Get broker queue data

Subscription Tools

  • subscribe: Subscribe to real-time data
  • unsubscribe: Unsubscribe from real-time data

Derivatives Tools

  • get_option_chain: Get option chain data
  • get_option_expiration_date: Get option expiration dates
  • get_option_condor: Get option condor strategy data
  • get_option_butterfly: Get option butterfly strategy data

Account Query Tools

  • get_account_list: Get account list
  • get_asset_info: Get asset information
  • get_asset_allocation: Get asset allocation information

Market Information Tools

  • get_market_state: Get market state
  • get_security_info: Get security information
  • get_security_list: Get security list

Stock Filter Commands

get_stock_filter

Filter stocks based on various conditions.

Parameters:

  • base_filters (optional): List of basic stock filters
    {
        "field_name": int,  # StockField enum value
        "filter_min": float,  # Optional minimum value
        "filter_max": float,  # Optional maximum value
        "is_no_filter": bool,  # Optional, whether to skip filtering
        "sort_dir": int  # Optional, sort direction
    }
    
  • accumulate_filters (optional): List of accumulate filters
    {
        "field_name": int,  # AccumulateField enum value
        "filter_min": float,
        "filter_max": float,
        "is_no_filter": bool,
        "sort_dir": int,
        "days": int  # Required, number of days to accumulate
    }
    
  • financial_filters (optional): List of financial filters
    {
        "field_name": int,  # FinancialField enum value
        "filter_min": float,
        "filter_max": float,
        "is_no_filter": bool,
        "sort_dir": int,
        "quarter": int  # Required, financial quarter
    }
    
  • market (optional): Market code (e.g. "HK.Motherboard", "US.NASDAQ")
  • page (optional): Page number, starting from 1 (default: 1)
  • page_size (optional): Number of results per page, max 200 (default: 200)

Supported Market Codes:

  • HK.Motherboard: Hong Kong Main Board
  • HK.GEM: Hong Kong GEM
  • HK.BK1911: H-Share Main Board
  • HK.BK1912: H-Share GEM
  • US.NYSE: NYSE
  • US.AMEX: AMEX
  • US.NASDAQ: NASDAQ
  • SH.3000000: Shanghai Main Board
  • SZ.3000001: Shenzhen Main Board
  • SZ.3000004: Shenzhen ChiNext

Example:

# Get stocks with price between 10 and 50 HKD in Hong Kong Main Board
filters = {
    "base_filters": [{
        "field_name": 5,  # Current price
        "filter_min": 10.0,
        "filter_max": 50.0
    }],
    "market": "HK.Motherboard"
}
result = await client.get_stock_filter(**filters)

Notes:

  • Limited to 10 requests per 30 seconds
  • Each page returns maximum 200 results
  • Recommended to use no more than 250 filter conditions
  • Maximum 10 accumulate conditions of the same type
  • Dynamic data sorting (like current price) may change between pages
  • Cannot compare different types of indicators (e.g. MA5 vs EMA10)

Resources

Market Data

  • market://{symbol}: Get market data for a symbol
  • kline://{symbol}/{ktype}: Get K-line data for a symbol

Prompts

Analysis

  • market_analysis: Create a market analysis prompt
  • option_strategy: Create an option strategy analysis prompt

Error Handling

The server follows the MCP 2.0 error response format:

{
    "jsonrpc": "2.0",
    "id": "request_id",
    "error": {
        "code": -32000,
        "message": "Error message",
        "data": null
    }
}

Security

  • The server uses secure WebSocket connections
  • All API calls are authenticated through the Futu OpenAPI
  • Environment variables are used for sensitive configuration

Development

Adding New Tools

To add a new tool, use the @mcp.tool() decorator:

@mcp.tool()
async def new_tool(param1: str, param2: int) -> Dict[str, Any]:
    """Tool description"""
    # Implementation
    return result

Adding New Resources

To add a new resource, use the @mcp.resource() decorator:

@mcp.resource("resource://{param1}/{param2}")
async def new_resource(param1: str, param2: str) -> Dict[str, Any]:
    """Resource description"""
    # Implementation
    return result

Adding New Prompts

To add a new prompt, use the @mcp.prompt() decorator:

@mcp.prompt()
async def new_prompt(param1: str) -> str:
    """Prompt description"""
    return f"Prompt template with {param1}"

License

MIT License

Available MCP Functions

Market Data Functions

get_stock_quote

Get stock quote data for given symbols.

symbols = ["HK.00700", "US.AAPL", "SH.600519"]
result = await session.call_tool("get_stock_quote", {"symbols": symbols})

Returns quote data including price, volume, turnover, etc.

get_market_snapshot

Get market snapshot for given symbols.

symbols = ["HK.00700", "US.AAPL", "SH.600519"]
result = await session.call_tool("get_market_snapshot", {"symbols": symbols})

Returns comprehensive market data including price, volume, bid/ask prices, etc.

get_cur_kline

Get current K-line data.

result = await session.call_tool("get_cur_kline", {
    "symbol": "HK.00700",
    "ktype": "K_1M",  # K_1M, K_5M, K_15M, K_30M, K_60M, K_DAY, K_WEEK, K_MON
    "count": 100
})

get_history_kline

Get historical K-line data.

result = await session.call_tool("get_history_kline", {
    "symbol": "HK.00700",
    "ktype": "K_DAY",
    "start": "2024-01-01",
    "end": "2024-03-31"
})

get_rt_data

Get real-time trading data.

result = await session.call_tool("get_rt_data", {"symbol": "HK.00700"})

get_ticker

Get ticker data (detailed trades).

result = await session.call_tool("get_ticker", {"symbol": "HK.00700"})

get_order_book

Get order book data.

result = await session.call_tool("get_order_book", {"symbol": "HK.00700"})

get_broker_queue

Get broker queue data.

result = await session.call_tool("get_broker_queue", {"symbol": "HK.00700"})

Subscription Functions

subscribe

Subscribe to real-time data.

result = await session.call_tool("subscribe", {
    "symbols": ["HK.00700", "US.AAPL"],
    "sub_types": ["QUOTE", "TICKER", "K_1M"]
})

Subscription types:

  • "QUOTE": Basic quote
  • "ORDER_BOOK": Order book
  • "TICKER": Trades
  • "RT_DATA": Real-time data
  • "BROKER": Broker queue
  • "K_1M" to "K_MON": K-line data

unsubscribe

Unsubscribe from real-time data.

result = await session.call_tool("unsubscribe", {
    "symbols": ["HK.00700", "US.AAPL"],
    "sub_types": ["QUOTE", "TICKER"]
})

Options Functions

get_option_chain

Get option chain data.

result = await session.call_tool("get_option_chain", {
    "symbol": "HK.00700",
    "start": "2024-04-01",
    "end": "2024-06-30"
})

get_option_expiration_date

Get option expiration dates.

result = await session.call_tool("get_option_expiration_date", {
    "symbol": "HK.00700"
})

get_option_condor

Get option condor strategy data.

result = await session.call_tool("get_option_condor", {
    "symbol": "HK.00700",
    "expiry": "2024-06-30",
    "strike_price": 350.0
})

get_option_butterfly

Get option butterfly strategy data.

result = await session.call_tool("get_option_butterfly", {
    "symbol": "HK.00700",
    "expiry": "2024-06-30",
    "strike_price": 350.0
})

Account Functions

get_account_list

Get account list.

result = await session.call_tool("get_account_list", {"random_string": "dummy"})

get_funds

Get account funds information.

result = await session.call_tool("get_funds", {"random_string": "dummy"})

get_positions

Get account positions.

result = await session.call_tool("get_positions", {"random_string": "dummy"})

get_max_power

Get maximum trading power.

result = await session.call_tool("get_max_power", {"random_string": "dummy"})

get_margin_ratio

Get margin ratio for a security.

result = await session.call_tool("get_margin_ratio", {"symbol": "HK.00700"})

Market Information Functions

get_market_state

Get market state.

result = await session.call_tool("get_market_state", {"market": "HK"})

Available markets: "HK", "US", "SH", "SZ"

get_security_info

Get security information.

result = await session.call_tool("get_security_info", {
    "market": "HK",
    "code": "00700"
})

get_security_list

Get security list for a market.

result = await session.call_tool("get_security_list", {"market": "HK"})

get_stock_filter

Get filtered stock list based on conditions.

result = await session.call_tool("get_stock_filter", {
    "market": "HK.Motherboard",
    "base_filters": [{
        "field_name": 1,  # Price
        "filter_min": 10.0,
        "filter_max": 50.0,
        "sort_dir": 1  # Ascending
    }],
    "page": 1,
    "page_size": 50
})

Time Function

get_current_time

Get current server time.

result = await session.call_tool("get_current_time", {"random_string": "dummy"})

Returns timestamp, formatted datetime, date, time and timezone.

推荐服务器

Crypto Price & Market Analysis MCP Server

Crypto Price & Market Analysis MCP Server

一个模型上下文协议 (MCP) 服务器,它使用 CoinCap API 提供全面的加密货币分析。该服务器通过一个易于使用的界面提供实时价格数据、市场分析和历史趋势。 (Alternative, slightly more formal and technical translation): 一个模型上下文协议 (MCP) 服务器,利用 CoinCap API 提供全面的加密货币分析服务。该服务器通过用户友好的界面,提供实时价格数据、市场分析以及历史趋势数据。

精选
TypeScript
MCP PubMed Search

MCP PubMed Search

用于搜索 PubMed 的服务器(PubMed 是一个免费的在线数据库,用户可以在其中搜索生物医学和生命科学文献)。 我是在 MCP 发布当天创建的,但当时正在度假。 我看到有人在您的数据库中发布了类似的服务器,但还是决定发布我的服务器。

精选
Python
mixpanel

mixpanel

连接到您的 Mixpanel 数据。 从 Mixpanel 分析查询事件、留存和漏斗数据。

精选
TypeScript
Sequential Thinking MCP Server

Sequential Thinking MCP Server

这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。

精选
Python
Nefino MCP Server

Nefino MCP Server

为大型语言模型提供访问德国可再生能源项目新闻和信息的能力,允许按地点、主题(太阳能、风能、氢能)和日期范围进行筛选。

官方
Python
Vectorize

Vectorize

将 MCP 服务器向量化以实现高级检索、私有深度研究、Anything-to-Markdown 文件提取和文本分块。

官方
JavaScript
Mathematica Documentation MCP server

Mathematica Documentation MCP server

一个服务器,通过 FastMCP 提供对 Mathematica 文档的访问,使用户能够从 Wolfram Mathematica 检索函数文档和列出软件包符号。

本地
Python
kb-mcp-server

kb-mcp-server

一个 MCP 服务器,旨在实现便携性、本地化、简易性和便利性,以支持对 txtai “all in one” 嵌入数据库进行基于语义/图的检索。任何 tar.gz 格式的 txtai 嵌入数据库都可以被加载。

本地
Python
Research MCP Server

Research MCP Server

这个服务器用作 MCP 服务器,与 Notion 交互以检索和创建调查数据,并与 Claude Desktop Client 集成以进行和审查调查。

本地
Python
Cryo MCP Server

Cryo MCP Server

一个API服务器,实现了模型补全协议(MCP),用于Cryo区块链数据提取,允许用户通过任何兼容MCP的客户端查询以太坊区块链数据。

本地
Python