Skip to main content
Glama
ctbcsec-api-mcp-server

ctbcsec-api-mcp-server

by Mofesto

CTS Trading API MCP Server

A Model Context Protocol (MCP) server providing comprehensive access to CTBC Securities CTS Trading API. Enables LLMs like Claude to interact with the trading platform for stock, futures, and options trading operations.

Features

  • Stock Trading: Place, modify, and cancel stock orders

  • Futures/Options Trading: Full support for derivatives trading

  • Account Management: Query accounts, positions, orders, and matches

  • Type-Safe: Comprehensive Pydantic models for all operations

  • Event-Driven: Async response handling for query operations

  • MCP Resources: Access to configuration and connection status

Related MCP server: KIS MCP Server

Requirements

  • Operating System: Windows (COM object dependency)

  • Python: 3.10 or higher

  • CTS Trading API: Must be installed and registered on the system

  • Dependencies:

    • mcp >= 1.1.0

    • pywin32 >= 306

    • pydantic >= 2.0

Installation

  1. Clone or download the repository

  2. Install CTS Trading API (from CTBC Securities)

    • Ensure the DJTRADEOBJLibCTS.TradeApp COM object is registered

  3. Install Python dependencies

    # Using uv (recommended)
    uv pip install -e .
    
    # Or using pip
    pip install -e .
  4. Configure the server

    Edit appsetting.json with your trading server endpoint:

    {
      "TradeDas": "your.trading.server.com/tradedas"
    }

Usage

Testing with MCP Inspector

Test the server using the MCP development tools:

uv run mcp dev d:\ctbcsec-api-mcp-server\ctbcsec_mcp\server.py

This launches the MCP Inspector where you can:

  • View all available tools

  • Test tool schemas

  • Execute tools interactively

  • Monitor responses

Integration with Claude Desktop

Install the server to Claude Desktop:

uv run mcp install d:\ctbcsec-api-mcp-server\ctbcsec_mcp\server.py

Or manually add to Claude Desktop configuration (%APPDATA%\Claude\claude_desktop_config.json):

{
  "mcpServers": {
    "ctbcsec-trading": {
      "command": "uv",
      "args": [
        "--directory",
        "d:\\ctbcsec-api-mcp-server",
        "run",
        "ctbcsec-mcp"
      ]
    }
  }
}

Available Tools

Authentication & Connection

  • initialize: Initialize the CTS Trading API with server configuration

  • login: Authenticate user with trading system

  • connect: Connect to the trading server

  • disconnect: Disconnect from trading server

  • logout: Logout from trading system

  • get_accounts: Retrieve all available trading accounts

  • get_connection_status: Get current connection status

  • set_lot_size: Set lot size data for specific stocks

Stock Trading

  • stock_new_order: Place a new stock order

  • stock_modify_order: Modify an existing stock order

  • stock_cancel_order: Cancel an existing stock order

  • stock_query_order: Query stock orders

  • stock_query_match: Query stock trade matches

  • stock_query_position: Query stock positions

Futures/Options Trading

  • futopt_new_order: Place a new futures/options order

  • futopt_modify_order: Modify an existing futures/options order

  • futopt_cancel_order: Cancel an existing futures/options order

  • futopt_query_order: Query futures/options orders

  • futopt_query_match: Query futures/options matches

  • futopt_query_oi: Query futures/options open interest

  • futopt_query_equity: Query futures/options account equity

Resources

  • config://appsetting: Current server configuration

  • status://connection: Current connection and authentication status

Example Usage Flow

# 1. Initialize the trading API
initialize(trade_das_url="apsit.ectest.ctbcsec.com/tradedas")

# 2. Login
login(user_id="your_user_id", password="your_password")

# 3. Connect to trading server
connect()

# 4. Get available accounts
accounts = get_accounts()

# 5. Place a stock order
stock_new_order(
    account_id="1234567",
    stock_id="2330",
    quantity="1000",
    price="500",
    buy_sell=BuySell.BUY,
    price_type=PriceType.LIMIT
)

# 6. Query positions
stock_query_position(account_id="1234567")

# 7. Cleanup
disconnect()
logout(user_id="your_user_id")

Enumerations

TradeType (Stock)

  • REGULAR = 0: Regular trading

  • AFTER_HOURS_ODD_LOT = 1: After-hours odd lot

  • AFTER_HOURS = 2: After-hours

  • EMERGING = 5: Emerging stock

  • INTRADAY_ODD_LOT = 7: Intraday odd lot

OrderType (Stock)

  • CASH = 0: Cash order

  • MARGIN = 1: Margin trading

  • SHORT = 2: Short selling

  • DAY_TRADING_SELL_FIRST = 16: Day trading sell first

BuySell

  • BUY = 1: Buy order

  • SELL = 2: Sell order

PriceType

  • LIMIT = 0: Limit price

  • LIMIT_UP = 1: Limit up

  • LIMIT_DOWN = 2: Limit down

  • FLAT = 3: Flat

  • MARKET = 4: Market price

OrderCondition

  • ROD = 0: Rest of Day

  • IOC = 1: Immediate or Cancel

  • FOK = 2: Fill or Kill

ProductType (Futures/Options)

  • FUTURES = 0: Futures

  • OPTIONS = 1: Options

  • COMPLEX_OPTIONS = 2: Complex options

  • COMPLEX_FUTURES = 3: Complex futures

Architecture

Components

  • server.py: FastMCP server with tool definitions and lifespan management

  • models.py: Pydantic models for type-safe structured data

  • wrapper.py: COM object wrapper with event handling and thread safety

  • __init__.py: Package initialization

Data Flow

  1. MCP tool receives request with typed parameters

  2. Server validates input using Pydantic models

  3. Wrapper executes COM object method with thread safety

  4. Event handler queues async responses

  5. Structured response returned to LLM

Thread Safety

The wrapper uses locks to ensure thread-safe access to the COM object, which is critical for concurrent operations.

Event Handling

Query operations use an event-driven architecture:

  • Responses arrive via OnDataResponse callback

  • Events are queued for async processing

  • Tools wait for responses with configurable timeout

Troubleshooting

COM Object Not Found

Error: "Failed to create COM object"

Solution: Ensure CTS Trading API is installed and the COM object is registered. Run the CTS Trading client once to verify installation.

Connection Failures

Error: "Not connected to trading server"

Solution:

  1. Verify appsetting.json has correct server URL

  2. Call initialize() before login()

  3. Call login() before connect()

  4. Check network connectivity

Query Timeout

Note: Query operations may timeout if the server is slow to respond. The default timeout is 5 seconds. This is normal for some operations.

Permission Errors

Ensure you have proper trading permissions and account authorization from CTBC Securities.

Development

Running Automated Tests

The project includes a comprehensive suite of automated tests using pytest and mock.

# Install dev dependencies
uv pip install -e ".[dev]"

# Run all tests
pytest

The tests cover:

  • Models: Validation and serialization of all data structures.

  • Wrapper: Logic for COM object interaction (using mocks).

  • Server: Tool registration and high-level logic.

Manual Testing with Scripts

Logging

The server uses Python's logging module. Set log level via environment variable:

# Windows PowerShell
$env:LOG_LEVEL="DEBUG"
uv run ctbcsec-mcp

# Windows CMD
set LOG_LEVEL=DEBUG
uv run ctbcsec-mcp

Security Considerations

  • Credentials: Never commit credentials to version control

  • Production Use: Use appropriate authentication and authorization

  • Network Security: Ensure secure connection to trading server

  • Access Control: Restrict access to the MCP server appropriately

License

This MCP server is provided for reference and development purposes. Please refer to your CTBC Securities API license agreement for terms of use.

Support

For technical support and API questions, contact CTBC Securities technical support team.

References


Version: 0.1.0
Last Updated: January 21, 2026

Available Tools

21 tools
connectB

Connect to the trading server.

Returns: Connection status

Inputs: no named parameters. Returns: Order operation response

disconnectA

Disconnect from the trading server.

Returns: Status confirmation

Inputs: no named parameters. Returns: Order operation response

futopt_cancel_orderB

Cancel an existing futures/options order.

Args: account_id: Account ID order_id: Original order ID order_number: Order number contract_id: Contract ID quantity: Order quantity current_quantity: Current remaining quantity matched_quantity: Matched quantity product_type: Product type trade_date: Trading date (defaults to today) contract_id2: Second leg contract ID pre_order: Pre-order flag

Returns: Cancellation confirmation

Inputs: order_id (required), quantity (required), account_id (required), contract_id (required), +7 more. Returns: Order operation response

futopt_modify_orderA

Modify an existing futures/options order.

Args: account_id: Account ID order_id: Original order ID order_number: Order number contract_id: Contract ID new_quantity: New quantity current_quantity: Current remaining quantity matched_quantity: Matched quantity new_price: New price product_type: Product type trade_date: Trading date (defaults to today) modify_type: Modification type price_type: Price type condition: Order condition contract_id2: Second leg contract ID pre_order: Pre-order flag

Returns: Modification result

Inputs: order_id (required), new_price (required), account_id (required), contract_id (required), +11 more. Returns: Order operation response

futopt_new_orderA

Place a new futures or options order.

Args: account_id: Account ID contract_id: Contract ID (e.g., "TXFJ4") quantity: Number of contracts price: Order price ("0" for market orders) buy_sell: Buy (1) or Sell (2) product_type: Product type (0=Futures, 1=Options) trade_date: Trading date (defaults to today) price_type: Price type (default: LIMIT) offset: Offset flag (0=Open, 1=Close) condition: Order condition (default: ROD) contract_id2: Second leg contract ID for complex orders buy_sell2: Second leg buy/sell pre_order: Pre-order flag

Returns: Order confirmation

Inputs: price (required), buy_sell (required), quantity (required), account_id (required), +9 more. Returns: Order operation response

futopt_query_equityB

Query futures/options account equity.

Args: account_id: Account ID trade_date: Trading date (empty string for current, defaults to today)

Returns: Account equity details

Inputs: account_id (required), trade_date. Returns: Query operation response

futopt_query_matchA

Query futures/options trade matches.

Args: account_id: Account ID force_query: True to force refresh, False to use cache

Returns: List of matched trades

Inputs: account_id (required), force_query. Returns: Query operation response

futopt_query_oiA

Query futures/options open interest.

Args: account_id: Account ID trade_date: Trading date (defaults to today) force_query: True to force refresh, False to use cache

Returns: Open interest positions

Inputs: account_id (required), trade_date, force_query. Returns: Query operation response

futopt_query_orderA

Query futures/options orders.

Args: account_id: Account ID product_type: Product type (0=Futures, 1=Options) force_query: True to force refresh, False to use cache

Returns: List of orders

Inputs: account_id (required), force_query, product_type. Returns: Query operation response

get_accountsA

Retrieve all available trading accounts.

Returns: List of account information objects

Inputs: no named parameters. Returns: result

get_connection_statusB

Get current connection and authentication status.

Returns: Current connection status

Inputs: no named parameters. Returns: Current connection and authentication status

initializeB

Initialize the CTS Trading API with server configuration.

Args: trade_das_url: Trading DAS server endpoint (e.g., "apsit.ectest.ctbcsec.com/tradedas")

Returns: Initialization result with success status and error details

Inputs: trade_das_url (required). Returns: Initialization response

loginB

Authenticate user with the trading system.

Args: user_id: User account ID password: User password

Returns: Login result with account information

Inputs: user_id (required), password (required). Returns: Login response

logoutC

Logout from the trading system.

Args: user_id: User account ID

Returns: Logout confirmation

Inputs: user_id (required). Returns: Order operation response

set_lot_sizeA

Set lot size data for specific stocks.

Args: lot_size_data: Lot size configuration (e.g., "0050=1000|0028=1000")

Returns: Operation result

Inputs: lot_size_data (required). Returns: Order operation response

stock_cancel_orderB

Cancel an existing stock order.

Args: account_id: Account ID order_id: Original order ID order_number: Order number stock_id: Stock symbol buy_sell: Buy (1) or Sell (2) quantity: Order quantity current_quantity: Current remaining quantity matched_quantity: Matched quantity price: Order price trade_date: Trading date (defaults to today) trade_type: Trade type order_type: Order type price_type: Price type condition: Order condition pre_order: Pre-order flag

Returns: Cancellation confirmation

Inputs: price (required), buy_sell (required), order_id (required), quantity (required), +11 more. Returns: Order operation response

stock_modify_orderB

Modify an existing stock order.

Args: account_id: Account ID order_id: Original order ID order_number: Order number stock_id: Stock symbol buy_sell: Buy (1) or Sell (2) current_quantity: Current remaining quantity matched_quantity: Matched quantity new_price: New price trade_date: Trading date (defaults to today) new_quantity: New quantity (0 to keep unchanged) trade_type: Trade type order_type: Order type price_type: Price type condition: Order condition modify_type: Modification type (0=Quantity, 2=Price) pre_order: Pre-order flag

Returns: Modification result

Inputs: buy_sell (required), order_id (required), stock_id (required), new_price (required), +12 more. Returns: Order operation response

stock_new_orderB

Place a new stock order.

Args: account_id: Account ID stock_id: Stock symbol (e.g., "2330") quantity: Number of shares price: Order price ("0" for market orders) buy_sell: Buy (1) or Sell (2) trade_date: Trading date in YYYYMMDD format (defaults to today) trade_type: Trade type (default: REGULAR) order_type: Order type (default: CASH) price_type: Price type (default: LIMIT) condition: Order condition (default: ROD) broker: Broker code (default: empty) pay_type: Payment type (default: 0)

Returns: Order confirmation or error message

Inputs: price (required), buy_sell (required), quantity (required), stock_id (required), +8 more. Returns: Order operation response

stock_query_matchB

Query stock trade matches.

Args: account_id: Account ID force_query: True to force refresh from server, False to use cache

Returns: List of matched trades

Inputs: account_id (required), force_query. Returns: Query operation response

stock_query_orderA

Query stock orders.

Args: account_id: Account ID force_query: True to force refresh from server, False to use cache

Returns: List of current orders

Inputs: account_id (required), force_query. Returns: Query operation response

stock_query_positionA

Query stock positions.

Args: account_id: Account ID trade_date: Trading date in YYYYMMDD format (defaults to today) force_query: True to force refresh from server, False to use cache

Returns: Current positions with P&L data

Inputs: account_id (required), trade_date, force_query. Returns: Query operation response

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 21 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose, grouped by asset class (stocks vs. futures/options) and action (new, modify, cancel, query). Connection/login/logout and account tools are separate from trading operations. No two tools appear to do the same thing.

    Naming Consistency5/5

    Tool names follow a consistent pattern: connection verbs (connect, login, disconnect) and asset-specific prefixes (stock_, futopt_) with action verbs (new, modify, cancel, query). Underscore-separated and lowercase throughout, making it easy to infer functionality.

    Tool Count5/5

    21 tools is well-scoped for a trading API covering connection lifecycle, account management, and full order lifecycle for both stocks and futures/options. Each tool adds distinct value and the count is appropriate for the breadth of functionality.

    Completeness5/5

    The tool surface covers the full trading workflow: connect, authenticate, manage orders (new/modify/cancel/query), view matches, and check positions/equity for both asset classes. No obvious dead ends or missing core operations that would impede an agent.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables LLM clients to interact with Interactive Brokers Trader Workstation for automated trading workflows. Supports market data retrieval, portfolio management, and order execution through the TWS API.
      5
      -
    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables interaction with the Korea Investment & Securities (KIS) Open API for domestic and overseas stock trading, real-time market data, and automated strategy execution. It provides a structured interface for LLMs to perform trading operations, manage portfolios, and conduct backtesting.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to access real-time market data, manage Moomoo trading accounts, and execute trades via the Moomoo platform.
      28 PyPI
      42
      Apache 2.0
    • F
      license
      Not graded
      quality
      D
      maintenance
      Wraps the miniQMT interface to enable AI assistants to query A-share market data, account information, and place/cancel orders.
      1
      -