Skip to main content
Glama
tohsaka888

trading-mcp

by tohsaka888

trading-mcp

An MCP service for trading data and technical indicators, built with uv + pydantic + akshare + TA-Lib.

Project Content

  • Provides stock market data queries and basic technical indicator calculations (K-line, RSI, MA, MACD).

  • Provides medium-to-long-term fundamental data queries (A-share key indicators, US stock three major financial statements, US stock key indicators).

  • Unified market data access layer, supporting A-shares and US stocks (e.g., AAPL.US).

  • MCP tool-based interface, supporting Markdown or JSON output.

Project Architecture

  • data/: Market data access layer. MarketDataClient interface + AkshareMarketDataClient implementation.

  • services/: Business service layer. Converts raw market data into standard structures and drives indicator calculations.

  • indicators/: Indicator engine encapsulation. Unified calls based on TA-Lib.

  • models/: Tool request and response models (Pydantic).

  • utils/: MCP output formatting (Markdown tables, etc.).

  • mcp_app.py / main.py: MCP service entry point and tool registration.

Directory Structure

  • config/: Configuration definitions (Pydantic Settings).

  • data/: Market data client implementation.

  • indicators/: Indicator calculation engine.

  • models/: Request/response models.

  • services/: Business service layer.

  • tests/: Unit tests.

  • utils/: Output formatting and helper tools.

  • mcp_app.py: MCP tool registration.

  • main.py: Service startup entry point.

Installation and Dependencies

  1. Install dependencies:

uv sync --extra dev
  1. Install TA-Lib system library:

  • macOS: brew install ta-lib

  • Debian/Ubuntu: sudo apt-get install libta-lib0 libta-lib0-dev

  • Windows: Use the pre-compiled wheel for your Python version

Configuration Configuration is overridden via environment variables with the TRADING_MCP_ prefix:

export TRADING_MCP_ENVIRONMENT=dev
export TRADING_MCP_DATA_DIR=./data
export TRADING_MCP_DEFAULT_SYMBOL=000001
export TRADING_MCP_HOST=0.0.0.0
export TRADING_MCP_PORT=8000
export TRADING_MCP_AKSHARE_PROXY_ENABLED=true
export TRADING_MCP_AKSHARE_PROXY_AUTH_IP=***
export TRADING_MCP_AKSHARE_PROXY_AUTH_TOKEN=*** TRADING_MCP_AKSHARE_PROXY_RETRY=30

Field meanings:

  • TRADING_MCP_ENVIRONMENT: Runtime environment identifier (e.g., dev / test / prod).

  • TRADING_MCP_DATA_DIR: Local data directory.

  • TRADING_MCP_DEFAULT_SYMBOL: Default market ticker.

  • TRADING_MCP_HOST: MCP service listening address.

  • TRADING_MCP_PORT: MCP service port.

  • TRADING_MCP_AKSHARE_PROXY_ENABLED: Whether to enable akshare-proxy-patch.

  • TRADING_MCP_AKSHARE_PROXY_AUTH_IP: akshare-proxy-patch authorization gateway IP; patch will not be installed if not configured.

  • TRADING_MCP_AKSHARE_PROXY_AUTH_TOKEN: Optional authorization token.

  • TRADING_MCP_AKSHARE_PROXY_RETRY: Internal retry count for the patch.

East Money Anti-Scraping Proxy Notes:

  • The project includes akshare-proxy-patch, which automatically attempts to install when importing data/akshare_client.py.

  • It is only enabled when TRADING_MCP_AKSHARE_PROXY_AUTH_IP is configured and TRADING_MCP_AKSHARE_PROXY_ENABLED=true.

  • The patch only hooks requests to East Money-related domains and does not affect other non-target sites.

Python Usage

from trading_mcp.config import Settings
from trading_mcp.data import AkshareMarketDataClient
from trading_mcp.indicators import IndicatorEngine

settings = Settings(environment="dev", data_dir="./data", default_symbol="000001")
client = AkshareMarketDataClient()
frame = client.fetch(settings.default_symbol, "2024-01-01", "2024-02-01")

engine = IndicatorEngine()
close_series = frame["close"] if "close" in frame.columns else frame.iloc[:, 0]
result = engine.compute("sma", close_series, timeperiod=5)
print(result.tail())

MCP Service Start the MCP service (streamable HTTP):

python main.py

Start the MCP Inspector (adapted for WSL, accessible from the host machine):

./dev.sh

By default, the following Inspector configuration is used:

  • MCP_INSPECTOR_HOST=0.0.0.0

  • MCP_INSPECTOR_CLIENT_PORT=6274

  • MCP_INSPECTOR_SERVER_PORT=6277

  • MCP_INSPECTOR_AUTO_OPEN=false

Access primarily from the Windows host browser:

http://localhost:6274

If WSL localhost forwarding is not enabled on your machine, you can run hostname -I inside WSL to find the IP, then access http://<wsl-ip>:6274 from the host.

If you only want to access it from the local Linux environment, you can override it to:

MCP_INSPECTOR_HOST=127.0.0.1 ./dev.sh

Note: The Inspector proxy has the capability to start local processes. 0.0.0.0 should only be used in trusted network environments.

Available Tools:

  • trading_kline(symbol, limit=30, offset=0, period_type="1d", start_date=None, end_date=None, response_format="markdown")

  • trading_macd(symbol, limit=30, fast_period=12, slow_period=26, signal_period=9, offset=0, period_type="1d", start_date=None, end_date=None, response_format="markdown")

  • trading_rsi(symbol, limit=30, period=14, offset=0, period_type="1d", start_date=None, end_date=None, response_format="markdown")

  • trading_ma(symbol, limit=30, period=20, ma_type="sma", offset=0, period_type="1d", start_date=None, end_date=None, response_format="markdown")

  • trading_volume(symbol, limit=30, offset=0, period_type="1d", start_date=None, end_date=None, response_format="markdown")

  • trading_fund_flow_individual_em(symbol, limit=30, offset=0, start_date=None, end_date=None, response_format="markdown")

  • trading_fund_flow_individual_rank_em(indicator="5日", limit=30, offset=0, response_format="markdown")

  • trading_fund_flow_sector_rank_em(indicator="今日", sector_type="行业资金流", sort_by="主力净流入", limit=30, offset=0, response_format="markdown")

  • trading_fund_flow_sector_summary_em(symbol, indicator="今日", limit=30, offset=0, response_format="markdown")

  • trading_fundamental_cn_indicators(symbol, indicator="按报告期", limit=30, offset=0, start_date=None, end_date=None, response_format="markdown")

  • trading_fundamental_us_report(stock, symbol="资产负债表", indicator="年报", limit=30, offset=0, start_date=None, end_date=None, response_format="markdown")

  • trading_fundamental_us_indicators(symbol, indicator="年报", limit=30, offset=0, start_date=None, end_date=None, response_format="markdown")

  • trading_industry_summary_ths(limit=30, offset=0, response_format="markdown")

  • trading_industry_index_ths(symbol, limit=30, offset=0, start_date=None, end_date=None, response_format="markdown")

  • trading_industry_name_em(limit=30, offset=0, response_format="markdown")

  • trading_board_change_em(limit=30, offset=0, response_format="markdown")

  • trading_industry_spot_em(symbol, limit=30, offset=0, response_format="markdown")

  • trading_industry_cons_em(symbol, limit=30, offset=0, response_format="markdown")

  • trading_industry_hist_em(symbol, period="日k", adjust="none", limit=30, offset=0, start_date=None, end_date=None, response_format="markdown")

  • trading_industry_hist_min_em(symbol, period="5", limit=30, offset=0, response_format="markdown")

  • trading_info_global_em(limit=30, offset=0, response_format="markdown")

trading_fundamental_cn_indicators Parameter Notes:

  • indicator enum: 按报告期, 按单季度

  • symbol compatible inputs: 000001, 000001.SZ, 600519.SH (auto-completion or normalized suffix)

  • Fundamental results returned in raw row format: columns + items

trading_fundamental_us_report Parameter Notes:

  • symbol (report type) enum: 资产负债表, 综合损益表, 现金流量表

  • indicator (report period) enum: 年报, 单季报, 累计季报

  • stock compatible inputs: TSLA, AAPL.US, 105.AAPL, BRK.B (internally normalized to AkShare-recognizable ticker)

trading_fundamental_us_indicators Parameter Notes:

  • indicator enum: 年报, 单季报, 累计季报

  • symbol compatible inputs: TSLA, AAPL.US, 105.AAPL, BRK.B

  • Fundamental results returned in raw row format: columns + items

trading_volume Field Notes:

  • Returned fields: timestamp, volume, amount, turnover_rate

  • Unit strategy: Retain original data source units and return units via response fields

    • A-shares: volume_unit=lot, amount_unit=CNY

    • US stocks: volume_unit=share, amount_unit=USD

    • turnover_rate_unit=percent

  • When weekly/monthly data is aggregated from daily lines, turnover_rate may be null

Fund Flow Tool Notes:

  • trading_fund_flow_individual_em: East Money individual stock fund flow, symbol supports 000001, 600519.SH, 830799.BJ

  • trading_fund_flow_individual_rank_em: East Money individual stock fund flow ranking

    • indicator enum: 今日, 3日, 5日, 10日

  • trading_fund_flow_sector_rank_em: East Money sector fund flow ranking

    • indicator enum: 今日, 5日, 10日

    • sector_type enum: 行业资金流, 概念资金流, 地域资金流

    • sort_by enum: 涨跌幅, 主力净流入; defaults to descending order by 主力净流入

  • When East Money ranking interface is unavailable:

    • Individual stock ranking falls back to Tonghuashun individual stock fund flow ranking

    • Industry/Concept sector ranking falls back to corresponding Tonghuashun ranking

    • Returned columns after fallback may differ from original East Money columns; 地域资金流 does not fall back

  • trading_fund_flow_sector_summary_em: Fund flow for constituent stocks of a specified sector

    • Defaults to East Money, falls back to Tonghuashun on failure

    • symbol is the sector name, e.g., 电源设备, 风电设备

    • indicator enum: 今日, 5日, 10日

    • Returned columns after fallback may differ from original East Money columns

  • Fund flow results are uniformly returned as raw tables: columns + items

Symbol Notes:

  • A-share examples: 000001, 300308.SZ

  • US stock examples: AAPL.US, AAPL, 105.AAPL, BRK.B

Industry Sector Tool Notes:

  • trading_industry_summary_ths: Tonghuashun industry overview table, returns original sector summary fields

  • trading_industry_index_ths: Tonghuashun industry index, symbol is sector name, supports start_date / end_date

  • trading_industry_name_em: East Money industry sector name list

  • trading_board_change_em: East Money daily sector movement details

  • trading_industry_spot_em: East Money industry sector real-time quotes, symbol is sector name

  • trading_industry_cons_em: East Money industry sector constituent stocks, symbol is sector name

  • trading_industry_hist_em: East Money industry sector historical quotes

    • period enum: 日k, 周k, 月k

    • adjust enum: none, qfq, hfq; where none means no adjustment

  • trading_industry_hist_min_em: East Money industry sector historical intraday quotes

    • period enum: 1, 5, 15, 30, 60

  • Industry sector results are uniformly returned as raw tables: columns + items

News Tool Notes:

  • trading_info_global_em: East Money global financial news flash

  • News results are uniformly returned as raw tables: columns + items

Response Structure (structuredContent)

{
  "stock": "TSLA",
  "symbol": "资产负债表",
  "indicator": "年报",
  "columns": ["REPORT_DATE", "ITEM_NAME", "AMOUNT"],
  "items": [],
  "count": 0,
  "total": 0,
  "limit": 30,
  "offset": 0,
  "has_more": false,
  "next_offset": null,
  "start_date": null,
  "end_date": null
}

MCP Data Interaction Flow (Architecture and Sequence Diagram)

Below is a Mermaid diagram of the current MCP's main data interaction architecture and sequence, helping to understand the flow of requests within the system.

Architecture (Flowchart)

flowchart LR
  Client[Client / User] -->|HTTP/Stream 请求| MCP[MCP Server]
  MCP -->|调用工具接口| API[Tool Dispatcher / Handlers]
  API --> Market[MarketDataClient (Akshare / Providers)]
  Market -->|行情数据| Storage[Local Cache / Data Dir]
  API --> Indicator[IndicatorEngine (TA-Lib)]
  Indicator -->|指标结果| Formatter[Response Formatter (Markdown / JSON)]
  Formatter -->|返回| Client
  Market -.->|必要时| Proxy[akshare-proxy-patch]
  MCP -->|注册 & 管理| Inspector[MCP Inspector]

Notes:

  • MCP Server: Receives external requests (HTTP/stream), responsible for parsing requests and calling internal tools.

  • Tool Dispatcher: Routes requests to specific tools (e.g., trading_kline, trading_macd).

  • MarketDataClient: Unified market data access layer, currently implemented mainly via Akshare, supports proxy patch.

  • IndicatorEngine: Calls TA-Lib or built-in algorithms to calculate technical indicators.

  • Response Formatter: Converts structured data into Markdown or JSON MCP response formats.

  • Local Cache/Storage: Used for short-term caching and historical data storage to reduce API calls.

Sequence Diagram

sequenceDiagram
  participant U as Client/User
  participant M as MCP Server
  participant D as Tool Dispatcher
  participant MD as MarketDataClient
  participant I as IndicatorEngine
  participant F as Formatter

  U->>M: 发起 trading_macd 请求 (symbol, start, end, params)
  M->>D: 解析并转发请求
  D->>MD: 请求历史 K 线 (symbol, start, end)
  MD-->>D: 返回原始行情数据 (OHLCV)
  D->>I: 传入行情数据与参数, 调用指标计算
  I-->>D: 返回指标结果 (MACD lines, histogram)
  D->>F: 格式化为 Markdown / JSON 的 MCP 响应
  F-->>M: 返回格式化结果
  M-->>U: 通过 HTTP Stream 返回响应 (chunked / 完整)

  alt 缓存命中
    D->>Storage: 读取缓存
    Storage-->>D: 返回缓存数据
  end

  alt 第三方被阻断/需要代理
    MD->>Proxy: 走 akshare-proxy-patch
    Proxy-->>MD: 返回代理后的数据
  end

The two diagrams above are abstract views of the current system; if you would like to refine the diagrams with more components (e.g., authentication, rate limiting, queues, asynchronous tasks, monitoring metrics), let me know which parts you need to add, and I can expand and update the Mermaid diagrams in the README.


If you confirm that this update is acceptable, I will commit the changes to a new branch and push it, then create a Pull Request for your review.

Related MCP Connectors

Related MCP Servers

  • A
    license
    C
    quality
    D
    maintenance
    Provides technical analysis indicators like SMA, EMA, RSI, MACD, Bollinger Bands, and Stochastic through MCP, enabling AI assistants to perform financial market analysis and calculations on price data.
    18
    7
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Provides stock market data and computes technical indicators like EMA, MACD, and RSI across multiple timeframes using the LongPort API and TA-Lib. It enables users to perform detailed financial analysis and multi-timeframe market reviews through standard MCP tools.
    -
  • F
    license
    Not graded
    quality
    F
    maintenance
    Provides AI clients access to TdxQuant/通达信 financial data and trading capabilities through MCP. Enables retrieval of market data, financial reports, sector information, and trading operations via stdio or HTTP/SSE connections.
    29
    -
  • A
    license
    B
    quality
    C
    maintenance
    MCP server that wraps AKShare's 1000+ financial data functions, enabling LLMs to query Chinese stock, macro, futures, fund, bond, option, forex, and alternative data through standardized tools.
    14
    3
    Apache 2.0