English | 简体中文
This project automatically generates Python APIs based on the CTP C++ API, making it easier for CTP Python developers to maintain the latest CTP interfaces and quickly upgrade CTP versions.
Note: This project has only been tested under CTP v6.7.11. Other versions have not been tested. The project CTP version number is configured in the ctp/__init__.py file.
This project is compiled using the following environment. If you use other tool versions, please make appropriate adjustments.
-
Windows 11 + MSVC 2022
-
Python 3.13.6 virtual environment, installed by UV.
-
CTP v6.7.11: CTP official download link
-
Meson + Ninja: A modern C++ extension build system.
-
Pybind11: Python C++ bindings
-
UV: A modern Python package manager with faster installation and smarter dependency resolution.
ctp/
├── 📂 ctp/ # CTP interface module
│ ├── 📂 api/ # CTP API module
│ │ ├── 📂 generator/ # C++ and Python binding generation script
│ │ ├── 📂 include/ # CTP API header files
│ │ ├── 📂 libs/ # CTP API static library files
│ │ ├── 📂 src/ # CTP and Python binding code files
│ │ ├── 📁 __init__.py # MdApi and TdApi initialization imports
│ │ ├── 📁 ctp_constant.py # CTP API Constants
│ │ ├── 📁 ctpmd.cp313-win_amd64.pyd # Market extension module compiled from C++ to Python
│ │ ├── 📁 ctpmd.pyi # Stub file for the market extension module
│ │ ├── 📁 ctptd.cp313-win_amd64.pyd # Trading extension module compiled from C++ to Python
│ │ ├── 📁 ctptd.pyi # Stub file for the trading extension module
│ │ ├── 📁 custom_constant.py # User-defined constant class
│ │ ├── 📁 thostmduserapi_se.dll # Windows CTP market API dynamic link library
│ │ ├── 📁 thostmduserapi_se.so # Linux CTP market API dynamic link library
│ │ ├── 📁 thosttraderapi_se.dll # Windows CTP trading API dynamic link library
│ │ ├── 📁 thosttraderapi_se.so # Linux CTP trading API dynamic link library
│ ├── 📁 __init__.py # CTP version configuration file
│ ├── 📁 __version__.py # Project version configuration file
│ ├── 📁 ctp.h # Task processing and encoding conversion
├── 📂 docs/ # Project documentation
├── 📁 .gitignore # Git commit ignore files, automatically generated by UV
├── 📁 .python-version # Project Python version file, automatically generated by UV
├── 📁 LICENSE # Project license file
├── 📁 README.md # Project description file in Chinese
├── 📁 README_CN.md # Project description file in English
├── 📁 build.py # Extension module automated compilation script, assembling Meson commands
├── 📁 hatch_build.py # Hatch hook, set the platform identifier when packaging with hatch
├── 📁 md_demo.py # Example of using the market extension module
├── 📁 meson.build # Meson build configuration file
├── 📁 pyproject.toml # Python project management configuration file, automatically generated by uv
├── 📁 td_demo.py # Example of using the transaction extension module
├── 📁 util.py # Public Tools
└── 📁 uv.lock # uv lock file, automatically generated by uv- Install UV
On Windows
Method 1: Global Installation (Recommended, choose one)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Method 2: Install in a Single Python Environment (Choose one)
pip install uvOn Linux
curl -LsSf https://astral.sh/uv/install.sh | sh- Install Python (Perform this step with Method 1, skip this with Method 2). I use 3.13.6; you can install your preferred version.
uv python install 3.13Download the Release source code of this project or install it using the command:
pip install homalos-ctp- Install a Python virtual environment and dependencies (execute from the root directory)
# Use uv to create a Python virtual environment with a specified version in the current project.
uv venv --python 3.13 .venv
# Install dependent libraries
uv add meson-python
uv add pybind11
uv add pybind11-stubgen
- Execute the one-click build script in the
generatordirectory (to generate Python bindings for the CTP C++ API)
# Activate the Python virtual environment and enter the generator.
.venv\Scripts\activate
cd homalos-ctp\api\generator# Generate binding files with one click.
python generate_onekey.py- Execute the following build script in the root directory to generate the CTP C++ API and encapsulate it into a Python-callable interface.
# Compile the CTP Python API with one click.
python build.py- Testing the Market Extension Module
In the project root directory, fill in the CTP environment information in md_demo.py and run it. 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
...- Testing the transaction extension module
Fill in the CTP environment information in td_demo.py in the project root directory and run it. The result is 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 | 状态: 全部成交
==================================================
...The generator script is located in ctp/api/generator/
generator_function_const.py
- Purpose: Generates basic function constant files
- Function:
- Reads the CTP header files
ThostFtdcMdApi.handThostFtdcTraderApi.h.h - Parses the functions therein and generates
ctp_function_const.py(function constant definitions)
generate_data_type.py
- Purpose: Generates data type definition files
- Function:
- Reads the CTP header file
ThostFtdcUserApiDataType.h - Parses the
#defineconstant definitions andtypedeftype definitions therein - Generates
ctp_function_const.py
generate_struct.py
- Purpose: Generates structure definition files
- Function:
- Reads the CTP header file
ThostFtdcUserApiStruct.h - Relies on the type mappings in
ctp_typedef.py - Parses the C++ structure definition and generates the Python dictionary-formatted structure definition file
ctp_struct.py
generate_api_functions.py
- Purpose: Generates API function binding code
- Function:
- Reads the CTP API header files (such as
ThostFtdcTraderApi.handThostFtdcMdApi.h) - Relies on the structure definitions in
ctp_struct.py - Generates a large number of C++ source code files for Python bindings
generate_dll_entry.py
-
Purpose: Generates the C++ DLL entry point code file
-
Function:
-
Generates three files:
dllmain.cpp,stdafx.cpp, andstdafx.h. -
dllmain.cpp: Contains the standard DLL entry point function, handling process and thread loading/unloading.
-
stdafx.cpp: A simple precompiled header include file.
-
stdafx.h: Contains the Windows API header files and common definitions.
generate_cpp.py
- Purpose: Generates
cppandhfiles - Function: **Generates
ctpmd.cpp,ctpmd.h, andctptd.cpp,ctptd.h, forctp.api.src.ctpmdandctp.api.src.ctptd, respectively. - The header file contains complete class declarations and function prototypes.
- The
cppfile contains all implementation and bindings.
generate_onekey.py
- Purpose: One-click assembles all md and td header, source, and other files to generate cpp and h files
- Function:
- One-click assembles the files generated by the above files, as well as header, source, and other files, to generate four files:
ctpmd.cpp,ctpmd.h, andctptd.cpp,ctptd.h.
build.py
- Purpose: One-click compiles the CTP C++ API into a Python API
- Function:
- One-click compiles the Python-callable CTP API files, located in
ctp/api/. These files include: ctpmd.cp313-win_amd64.pydctptd.cp313-win_amd64.pydctpmd.pyictptd.pyi
File Dependencies:
generator_function_const.py→ Generatectp_function_const.pygenerate_data_type.py→ Generatectp_typedef.pyandctp_constant.pygenerate_struct.py(depends onctp_typedef.py) → Generatectp_struct.pygenerate_api_functions.py(depends onctp_struct.pyandctp_function_const.py) → Generate multiple API header and source binding files formdandtdgenerate_dll_entry.py→ Generatedllmain.cpp,stdafx.cpp, andstdafx.hgenerate_cpp.py(depends on all the above files, as well as the generated header and source files) → Generatesctpmd.cpp,ctpmd.h, andctptd.cppandctptd.hgenerate_onekey.py→ Assemblesctpmd.cpp,ctpmd.h, andctptd.cppandctptd.hfiles with one click (equivalent to executing the above process with one click)build.py(depends on thectpmdandctptdmodules inctp/api/src/) → Compilesctpmd.cp313-win_amd64.pyd,ctptd.cp313-win_amd64.pyd,ctpmd.pyi, andctptd.pyiwith one click
The code generated by these scripts is used to:
- Encapsulate the CTP C++ API into a Python-callable interface
- Automatically handle data type conversion
- Generate Python bindings for callback functions
- Generate Python bindings for request functions
- Use pybind to bind C++ to the Python CTP API, offering superior performance compared to SWIG conversion.
- Automatic synchronization: When the CTP official header files are updated, the latest h, dll, so, and lib files are replaced. After executing the generated script, the script will automatically reflect the latest virtual functions.
- Easy maintenance: No need to manually update a large number of hard-coded function declarations.
- Reduced errors: Avoid omissions or errors that may result from manual maintenance.
- Improved efficiency: Developers only need to focus on business logic, without worrying about changes to the underlying interfaces.
Summary: This is a complete code generation toolchain that automatically generates Python bindings for the CTP API, eliminating the need to manually write repetitive binding code and improving maintainability and robustness.
- Technical Exchange (QQ Group):
446042777 - pypi.org
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.
homalos-ctp Last Updated: 2025-09-05