Skip to content

feat: Integrate TWSE (Taiwan Stock Exchange) market data tools #109

@JasonWang1124

Description

@JasonWang1124

Summary

Add native Taiwan Stock Exchange (TWSE) market data tools to OpenAlice, enabling the AI agent to query real-time and historical Taiwan stock market information directly.

Motivation

OpenAlice currently supports US equities, crypto, and currencies via OpenBB. However, there is no built-in support for the Taiwan stock market (TWSE). Since OpenAlice is developed with a focus on multi-market trading, adding TWSE data coverage fills a significant gap — especially for users trading in the Taiwanese market.

A mature TWSE MCP server already exists (twjackysu/TWSEMCPServer), built on FastMCP and backed by the official TWSE OpenAPI. This integration bridges that MCP server into OpenAlice's tool system.

Proposed Implementation

Architecture

AI Agent → OpenAlice ToolCenter → TwstockMcpClient → Local MCP Server → TWSE OpenAPI
  • src/domain/twstock/client.ts — MCP client wrapper with lazy-connect (connects on first tool call, so OpenAlice starts even if the server is unavailable)
  • src/domain/twstock/config.ts — Reads data/config/twstock.json for enabled flag and mcpUrl (no hardcoded URLs in source)
  • src/tool/twstock.ts — 29 tool definitions following existing factory pattern (Zod schemas, thin execute functions)
  • src/main.ts — Conditional registration gated by config

Tools (29 total)

Company Information (6 tools)

Tool Description
twstockGetCompanyProfile Basic company info (name, industry, capital, chairman)
twstockGetCompanyBalanceSheet Balance sheet with auto industry format detection
twstockGetCompanyIncomeStatement Comprehensive income statement
twstockGetCompanyMonthlyRevenue Monthly revenue data
twstockGetCompanyDividend Dividend distribution history
twstockGetCompanyMajorNews Material announcements and disclosures

ESG & Governance (5 tools)

Tool Description
twstockGetCompanyGovernanceInfo Corporate governance data
twstockGetCompanyClimateManagement Climate-related management info
twstockGetCompanyRiskManagement Risk management policies
twstockGetCompanyInfoSecurity Information security data
twstockGetCompanySupplyChainManagement Supply chain management info

Trading Data (6 tools)

Tool Description
twstockGetStockDailyTrading Daily OHLCV trading data
twstockGetStockMonthlyTrading Monthly trading summary
twstockGetStockYearlyTrading Yearly trading summary
twstockGetStockMonthlyAverage Daily close + monthly average price
twstockGetStockValuationRatios P/E ratio, dividend yield, P/B ratio
twstockGetRealTimeTradingStats Real-time 5-second market statistics

Market Indices (2 tools)

Tool Description
twstockGetMarketIndexInfo Daily index data with category filtering (major/sector/ESG/thematic)
twstockGetMarketHistoricalIndex Historical TAIEX data for trend analysis

Foreign & Institutional Investment (2 tools)

Tool Description
twstockGetTopForeignHoldings Top 20 companies by foreign holdings
twstockGetForeignInvestmentByIndustry Foreign holding ratios by industry

Margin Trading (1 tool)

Tool Description
twstockGetMarginTradingInfo Margin trading and short selling balances

Dividends & ETF (2 tools)

Tool Description
twstockGetDividendRightsSchedule Ex-dividend/rights schedule
twstockGetEtfRegularInvestmentRanking Top 10 securities by regular investment accounts

TWSE News & Events (2 tools)

Tool Description
twstockGetTwseNews Official TWSE news with date filtering
twstockGetTwseEvents TWSE event announcements and seminars

Warrants (3 tools)

Tool Description
twstockGetWarrantBasicInfo Warrant specifications and exercise periods
twstockGetWarrantDailyTrading Warrant daily trading volume/value
twstockGetWarrantTraderCount Daily warrant trader count

Configuration

Users configure via data/config/twstock.json (gitignored):

{
  "enabled": true,
  "mcpUrl": "http://localhost:3010/mcp"
}
  • If the file is missing or mcpUrl is empty, no tools are registered (zero impact on existing functionality)
  • The MCP server (TWSEMCPServer) can be run locally via uv run fastmcp run server.py --transport streamable-http --port 3010

Design Decisions

  • Opt-in: Gated behind config — disabled by default if no config file exists
  • No hardcoded URLs: MCP endpoint is read from gitignored config file
  • Lazy connection: MCP client connects on first tool call, not at startup — OpenAlice starts normally even if the TWSE server is down
  • Follows existing patterns: Factory function, Zod schemas, error handling — identical to equity.ts, market.ts, etc.
  • Minimal changes to existing code: Only src/main.ts is modified (import + conditional registration + shutdown hook)

Alternatives Considered

  1. Direct TWSE API calls from TypeScript — Would eliminate the MCP dependency but requires reimplementing all 29 endpoints, data parsing, and error handling already done in TWSEMCPServer
  2. stdio transport instead of HTTP — Slightly lower latency but requires Python/uv in the environment and complicates process management
  3. Hardcode remote FastMCP URL — Simpler but exposes the endpoint in source code and adds latency (~5-7x slower than local)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions