ctbcsec-api-mcp-server
Enables LLMs to interact with CTBC Securities CTS Trading API for stock, futures, and options trading operations, including order placement, account management, and position queries.
README
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
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.0pywin32 >= 306pydantic >= 2.0
Installation
-
Clone or download the repository
-
Install CTS Trading API (from CTBC Securities)
- Ensure the
DJTRADEOBJLibCTS.TradeAppCOM object is registered
- Ensure the
-
Install Python dependencies
# Using uv (recommended) uv pip install -e . # Or using pip pip install -e . -
Configure the server
Edit
appsetting.jsonwith 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 configurationlogin: Authenticate user with trading systemconnect: Connect to the trading serverdisconnect: Disconnect from trading serverlogout: Logout from trading systemget_accounts: Retrieve all available trading accountsget_connection_status: Get current connection statusset_lot_size: Set lot size data for specific stocks
Stock Trading
stock_new_order: Place a new stock orderstock_modify_order: Modify an existing stock orderstock_cancel_order: Cancel an existing stock orderstock_query_order: Query stock ordersstock_query_match: Query stock trade matchesstock_query_position: Query stock positions
Futures/Options Trading
futopt_new_order: Place a new futures/options orderfutopt_modify_order: Modify an existing futures/options orderfutopt_cancel_order: Cancel an existing futures/options orderfutopt_query_order: Query futures/options ordersfutopt_query_match: Query futures/options matchesfutopt_query_oi: Query futures/options open interestfutopt_query_equity: Query futures/options account equity
Resources
config://appsetting: Current server configurationstatus://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 tradingAFTER_HOURS_ODD_LOT = 1: After-hours odd lotAFTER_HOURS = 2: After-hoursEMERGING = 5: Emerging stockINTRADAY_ODD_LOT = 7: Intraday odd lot
OrderType (Stock)
CASH = 0: Cash orderMARGIN = 1: Margin tradingSHORT = 2: Short sellingDAY_TRADING_SELL_FIRST = 16: Day trading sell first
BuySell
BUY = 1: Buy orderSELL = 2: Sell order
PriceType
LIMIT = 0: Limit priceLIMIT_UP = 1: Limit upLIMIT_DOWN = 2: Limit downFLAT = 3: FlatMARKET = 4: Market price
OrderCondition
ROD = 0: Rest of DayIOC = 1: Immediate or CancelFOK = 2: Fill or Kill
ProductType (Futures/Options)
FUTURES = 0: FuturesOPTIONS = 1: OptionsCOMPLEX_OPTIONS = 2: Complex optionsCOMPLEX_FUTURES = 3: Complex futures
Architecture
Components
server.py: FastMCP server with tool definitions and lifespan managementmodels.py: Pydantic models for type-safe structured datawrapper.py: COM object wrapper with event handling and thread safety__init__.py: Package initialization
Data Flow
- MCP tool receives request with typed parameters
- Server validates input using Pydantic models
- Wrapper executes COM object method with thread safety
- Event handler queues async responses
- 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
OnDataResponsecallback - 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:
- Verify
appsetting.jsonhas correct server URL - Call
initialize()beforelogin() - Call
login()beforeconnect() - 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
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.