✨ One-Click Automated Compilation of CTP API C++ and Python Bindings ✨
English | 简体中文
This project automatically wraps the native CTP C++ API into a Python API, facilitating CTP Python developers in maintaining up-to-date CTP interfaces and enabling rapid version upgrades.
Note: This project has been successfully tested only with CTP version v6.7.11; other versions have not been tested, so please perform your own testing. The configured CTP version number for this project is located in the ctp/__init__.py file.
This project was compiled using the following environment; if you choose to use different versions, please make the necessary adjustments.
- Windows 11 + MSVC (provided by Visual Studio 2022)
- Python 3.13.6, installed via UV.
- CTP v6.7.11: Official CTP Download Link
- Meson + Ninja: A modern build system for C++ extensions.
- Pybind11: Used to create seamless bindings between C++ and Python, enabling Python to easily call high-performance C++ code.
- UV: A modern Python package manager offering faster installation speeds and more intelligent dependency resolution.
/
├── 📂 ctp/ # CTP Interface-related Files
│ ├── 📂 api/ # CTP API Module
│ │ ├── 📂 generator/ # Files for the C++ to Python binding process
│ │ ├── 📂 include/ # Stores native CTP API C++ header files
│ │ ├── 📂 libs/ # Stores native CTP API static library files
│ │ ├── 📂 src/ # Stores C++ and Python binding process files
│ │ ├── 📁 ctp_constant.py # CTP API constants (referenced in demos)
│ │ ├── 📁 ctpmd.cp313-win_amd64.pyd # C++-compiled Python extension module for Market Data (MD)
│ │ ├── 📁 ctpmd.pyi # Stub file corresponding to the MD extension module
│ │ ├── 📁 ctptd.cp313-win_amd64.pyd # C++-compiled Python extension module for Trading (TD)
│ │ ├── 📁 ctptd.pyi # Stub file corresponding to the TD extension module
│ │ ├── 📁 custom_constant.py # User-defined constant class (referenced in demos)
│ │ ├── 📁 thostmduserapi_se.dll # Windows CTP Market Data API Dynamic Link Library (DLL)
│ │ ├── 📁 thostmduserapi_se.so # Linux CTP Market Data API Dynamic Link Library (SO)
│ │ ├── 📁 thosttraderapi_se.dll # Windows CTP Trading API Dynamic Link Library (DLL)
│ │ └── 📁 thosttraderapi_se.so # Linux CTP Trading API Dynamic Link Library (SO)
│ ├── 📁 __init__.py # CTP version configuration file
│ └── 📁 ctp.h # Task processing and encoding conversion
├── 📂 demo/ # Project-related documentation and examples
│ ├── 📁 md_demo.py # Usage example for the Market Data (MD) extension module
│ ├── 📁 td_demo.py # Usage example for the Trading (TD) extension module
│ └── 📁 util.py # Demo utility functions
├── 📂 docs/ # Project documentation
├── 📂 script/ # Automation scripts
├── 📁 .gitignore # Git ignore file (auto-generated by uv)
├── 📁 .python-version # Project Python version file (auto-generated by uv)
├── 📁 LICENSE # Project license file
├── 📁 README.md # Project README (Chinese)
├── 📁 README_CN.md # Project README (English)
├── 📁 build.py # Automation script for compiling extension modules (assembles meson commands)
├── 📁 meson.build # Meson build configuration file
├── 📁 pyproject.toml # Python project configuration file (auto-generated by uv)
├── 📁 util.py # General utilities
└── 📁 uv.lock # uv lock file (auto-generated by uv)Method 1: Global Installation (Recommended)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Method 2: Install within a Specific Python Environment
pip install uvcurl -LsSf https://astral.sh/uv/install.sh | shIf you followed Method 1 in the previous step, you can now install the specific Python version you require:
uv python install 3.13uv add homalos-ctp
# or
pip install homalos-ctpDownload the source code from the project's Releases page or use git clone.
# Execute this command in the project root directory to synchronize the environment with the project's dependencies (synchronizing both the Python version and third-party packages).
uv sync.venv\Scripts\activate
cd ctp\api\generator
# Generate all CTP API assembly files with a single command.
python generate_all.py# Execute this command in the project root directory to generate the binding files.
python build.pyAfter filling in the CTP environment and simonow account details in md_demo.py (located under the demo/ directory) and running the script, the results are as follows:
Start connecting to CTP market server...
CtpMdApi:Trying to create an API with path D:\Project\PycharmProjects\homalos-ctp\con/md
CtpMdApi:createFtdcMdApi call succeeded.
CtpMdApi:Try initializing the API using the address:tcp://182.254.243.31:40011...
CtpMdApi:init call succeeded.
Connecting to tcp://182.254.243.31:40011...
Waiting for connection and login to complete...
ctp md api callback: onFrontConnected - The market data server is connected successfully
Start the login process
CtpMdApi:reqUserLogin call succeeded.
ctp md api callback: onRspUserLogin - The market server login is successful
Starting to subscribe to 2 contracts...
Subscription contract: SA601
Prepare subscription contract: SA601
Send subscription request SA601
Subscription request sent SA601
ctp md api callback: onRspSubMarketData - Subscription feedback, Contract=SA601, ErrorID=0
symbol: SA601
ctp md api callback: onRtnDepthMarketData
CTP Market data reception: SA601 @ 17:00:34 LastPrice=1276.0
Subscription contract: FG601
Prepare subscription contract: FG601
Send subscription request FG601
Subscription request sent FG601
ctp md api callback: onRtnDepthMarketData
CTP Market data reception: SA601 @ 17:00:35 LastPrice=1276.0
...After filling in the CTP environment and simonow account details in td_demo.py (located under the demo/ directory) and running the script, the results are as follows:
CtpTdApi: Attempting to create an API with path D:\Project\PycharmProjects\homalos-ctp\con/td
CtpTdApi: createFtdcTraderApi call succeeded.
CtpTdApi:尝试使用地址初始化 API:tcp://182.254.243.31:30001...
CtpTdApi:init 调用成功。
Waiting for connection and login to complete...
ctp td api callback: onFrontConnected - Trading server connection successful
开始认证,auth_status: False
发送认证请求,req_id: 1
Transaction server authorization verification successful
开始登录,login_status: False
发送登录请求,req_id: 2
ctp td api callback: onRspUserLogin - Login Response, ErrorID=0
Trading server login successful
Settlement information confirmed successfully
🚀 开始下单测试...
正在委托下单...
symbol: SA601
direction: BUY_OPEN
price: 1286
volume: 1
委托请求发送成功
委托下单成功,委托号:1_-394894342_1
下单完成,订单号: 1_-394894342_1
⏰ 等待5秒观察订单状态...
ctp td api callback: onRtnOrder
订单状态更新 - 订单 ID:1_-394894342_1,状态:未知 (a)
状态变化: 新订单 -> 未知
ctp td api callback: onRtnOrder
订单状态更新 - 订单 ID:1_-394894342_1,状态:未知 (a)
状态变化: a -> 未知
ctp td api callback: onRtnOrder
订单状态更新 - 订单 ID:1_-394894342_1,状态:全部成交 (0)
订单全部成交 - 订单号: 1_-394894342_1, 合约: SA601
状态变化: a -> 全部成交
ctp td api callback: onRtnTrade
onRtnTrade trade_id: 2025090800029227, order_id: 48977, price: 1286.0, volume: 1, trade_date: 20250905, trade_time: 21:41:12
==================================================
📋 订单状态汇总
==================================================
订单号: 1_-394894342_1 | 状态: 全部成交
==================================================
...This section is intended solely for researchers interested in the binding generation process itself. If you simply need to generate the binding files, reading this content is unnecessary; the generator scripts are located in the ctp/api/generator/ directory.
- Purpose: Generates the base function constants file.
- Functionality: Reads the CTP API C++ header files—specifically
ThostFtdcMdApi.handThostFtdcTraderApi.h—parses the functions contained within them, and generatesctp_function_const.py(containing function constant definitions).
- Purpose: Generates data type definition files.
- Functionality: Reads the CTP API C++ header file
ThostFtdcUserApiDataType.h, parses the#defineconstants andtypedeftype definitions found therein, and generatesctp_typedef.pyandctp_constant.py(which are imported and used in the demo examples).
- Purpose: Generates structure definition files.
- Functionality: Reads the CTP API C++ header file
ThostFtdcUserApiStruct.h. Relying on the type mappings defined inctp_typedef.py, it parses the C++ structure definitions and generatesctp_struct.py, a file containing structure definitions in a Python dictionary format.
-
Purpose: Generates API function binding code.
-
Functionality: Reads the CTP API header files (e.g.,
ThostFtdcTraderApi.h,ThostFtdcMdApi.h). Relying on the structure definitions inctp_struct.pyand the helper scriptgenerate_helper.py, it generates a substantial amount of C++ source code files intended for use in the Python bindings. ### 6.5generate_dll_entry.py -
Purpose: Generates the C++ DLL entry point code files.
-
Functionality:
-
Generates three files—
dllmain.cpp,stdafx.cpp, andstdafx.h—outputting them to thectp/api/src/ctpmdandctp/api/src/ctptddirectories. -
dllmain.cpp: Contains the standard DLL entry point function, handling process and thread loading/unloading events. -
stdafx.cpp: A simple file for including precompiled headers. -
stdafx.h: Includes Windows API header files and common definitions.
- Purpose: Generates the
.cppand.hsource files. - Functionality:
- Generates four specific files—
ctpmd.cpp,ctpmd.h,ctptd.cpp, andctptd.h—within thectp/api/src/ctpmdandctp/api/src/ctptddirectories, respectively. - The header files (
.h) contain complete class declarations and function prototypes. - The C++ source files (
.cpp) contain all implementations and bindings.
-
Purpose: Assembles all MD and TD header, source, and related files to generate the final
.cppand.hfiles. -
Functionality: Assembles the files generated by the aforementioned scripts—along with the original header and source files—to produce the four final files:
ctpmd.cpp,ctpmd.h,ctptd.cpp, andctptd.h. This script effectively serves as a "one-click" execution tool that runs the six scripts described above in their proper sequence. ### 6.8build.py -
Purpose: One-click compilation of the binding files between C++ and Python
-
Functionality: Compiles the binding files connecting C++ and Python. These files are located in
ctp/api/and include: -
ctpmd.cp313-win_amd64.pyd -
ctptd.cp313-win_amd64.pyd -
ctpmd.pyi -
ctptd.pyi
File Dependencies:
generator_function_const.py→ Generatesctp_function_const.pygenerate_data_type.py→ Generatesctp_typedef.pyandctp_constant.py(used viaimportin the demo)generate_struct.py(Depends onctp_typedef.py) → Generatesctp_struct.pygenerate_api_functions.py(Depends onctp_struct.py,ctp_function_const.py, andgenerate_helper.py) → Generates multiple API header and source binding files for the MD (Market Data) and TD (Trading) modulesgenerate_dll_entry.py→ Generatesdllmain.cpp,stdafx.cpp, andstdafx.hgenerate_cpp.py(Depends on the files generated by all the above scripts, as well as the header and source files) → Generatesctpmd.cpp,ctpmd.h,ctptd.cpp, andctptd.hgenerate_all.py→ Assembles thectpmd.cpp,ctpmd.h,ctptd.cpp, andctptd.hfiles (equivalent to executing the 6 scripts listed above in sequence with a single command)build.py(Depends on thectpmdandctptdmodules located inctp/api/src/) → Performs the one-click compilationctpmd.cp313-win_amd64.pyd,ctptd.cp313-win_amd64.pyd,ctpmd.pyi,ctptd.pyi
The code ultimately generated by these scripts is used to:
- Automatically handle data type conversions
- Generate Python bindings for callback functions
- Generate Python bindings for request functions
- Generate binding files that create a seamless interface between C++ and Python, enabling Python to easily invoke high-performance C++ code
- Uses Pybind to bind C++ with Python, offering superior performance compared to the Swig-based conversion method.
- Automatic Synchronization: When CTP officially updates its header files, simply replace the existing native
.h,.dll,.so, and.libfiles; upon executing the generation script, the script will automatically reflect the latest virtual functions. - Ease of Maintenance: Eliminates the need to manually update a large volume of hard-coded function declarations.
- Reduced Errors: Avoids omissions or mistakes that can arise from manual maintenance.
- Increased Efficiency: Developers can focus solely on business logic without having to worry about changes to the underlying interfaces.
Meson: Similar to Make and CMake, its main task is to configure the compilation environment, generate compilation instructions (for example, for Ninja), and manage the entire compilation process. It does not directly compile code, but rather drives tools like Ninja to do so.
Pybind11: A lightweight C++ library for exposing (binding) C++ code to the Python interpreter. It allows Python code to seamlessly call C++ functions and classes, just like calling regular Python modules. Its core goal is to provide an extremely simple, nearly boilerplate-free interface that easily combines the high-performance computing capabilities of C++ with the ease of use and vast Python ecosystem.
Reference: vnpy_ctp
ctp-pybind Last Updated: 2026-05-11