Skip to content

ctp-api/ctp-pybind

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

79 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ctp-pybind

✨ One-Click Automated Compilation of CTP API C++ and Python Bindings ✨

English | 简体中文

Project Description

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.

1. Compilation Environment

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.

2. Project Structure

/
├── 📂 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)

3. Setting Up the Environment

3.1 Installing UV

3.1.1 On Windows

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 uv

3.1.2 On Linux

curl -LsSf https://astral.sh/uv/install.sh | sh

3.2 Installing Python

If you followed Method 1 in the previous step, you can now install the specific Python version you require:

uv python install 3.13

4. Usage

4.1 Method 1: Command-line Installation

uv add homalos-ctp
# or
pip install homalos-ctp

4.2 Method 2: Source Installation

Download the source code from the project's Releases page or use git clone.

4.2.1 Installing Dependencies

# 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

4.2.2 Generating CTP API Assembly Files

.venv\Scripts\activate
cd ctp\api\generator
# Generate all CTP API assembly files with a single command.
python generate_all.py

4.2.3 Generating CTP API Python Bindings

# Execute this command in the project root directory to generate the binding files.
python build.py

5. Demo Testing

5.1 Testing the Market Data Extension Module

After 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
...

5.2 Transaction Extension Module

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 | 状态: 全部成交
==================================================
...

6. Script Function Details

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.

6.1 generator_function_const.py

  • Purpose: Generates the base function constants file.
  • Functionality: Reads the CTP API C++ header files—specifically ThostFtdcMdApi.h and ThostFtdcTraderApi.h—parses the functions contained within them, and generates ctp_function_const.py (containing function constant definitions).

6.2 generate_data_type.py

  • Purpose: Generates data type definition files.
  • Functionality: Reads the CTP API C++ header file ThostFtdcUserApiDataType.h, parses the #define constants and typedef type definitions found therein, and generates ctp_typedef.py and ctp_constant.py (which are imported and used in the demo examples).

6.3 generate_struct.py

  • Purpose: Generates structure definition files.
  • Functionality: Reads the CTP API C++ header file ThostFtdcUserApiStruct.h. Relying on the type mappings defined in ctp_typedef.py, it parses the C++ structure definitions and generates ctp_struct.py, a file containing structure definitions in a Python dictionary format.

6.4 generate_api_functions.py

  • Purpose: Generates API function binding code.

  • Functionality: Reads the CTP API header files (e.g., ThostFtdcTraderApi.h, ThostFtdcMdApi.h). Relying on the structure definitions in ctp_struct.py and the helper script generate_helper.py, it generates a substantial amount of C++ source code files intended for use in the Python bindings. ### 6.5 generate_dll_entry.py

  • Purpose: Generates the C++ DLL entry point code files.

  • Functionality:

  • Generates three files—dllmain.cpp, stdafx.cpp, and stdafx.h—outputting them to the ctp/api/src/ctpmd and ctp/api/src/ctptd directories.

  • 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.

6.6 generate_cpp.py

  • Purpose: Generates the .cpp and .h source files.
  • Functionality:
  • Generates four specific files—ctpmd.cpp, ctpmd.h, ctptd.cpp, and ctptd.h—within the ctp/api/src/ctpmd and ctp/api/src/ctptd directories, respectively.
  • The header files (.h) contain complete class declarations and function prototypes.
  • The C++ source files (.cpp) contain all implementations and bindings.

6.7 generate_all.py

  • Purpose: Assembles all MD and TD header, source, and related files to generate the final .cpp and .h files.

  • 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, and ctptd.h. This script effectively serves as a "one-click" execution tool that runs the six scripts described above in their proper sequence. ### 6.8 build.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:

  1. generator_function_const.py → Generates ctp_function_const.py
  2. generate_data_type.py → Generates ctp_typedef.py and ctp_constant.py (used via import in the demo)
  3. generate_struct.py (Depends on ctp_typedef.py) → Generates ctp_struct.py
  4. generate_api_functions.py (Depends on ctp_struct.py, ctp_function_const.py, and generate_helper.py) → Generates multiple API header and source binding files for the MD (Market Data) and TD (Trading) modules
  5. generate_dll_entry.py → Generates dllmain.cpp, stdafx.cpp, and stdafx.h
  6. generate_cpp.py (Depends on the files generated by all the above scripts, as well as the header and source files) → Generates ctpmd.cpp, ctpmd.h, ctptd.cpp, and ctptd.h
  7. generate_all.py → Assembles the ctpmd.cpp, ctpmd.h, ctptd.cpp, and ctptd.h files (equivalent to executing the 6 scripts listed above in sequence with a single command)
  8. build.py (Depends on the ctpmd and ctptd modules located in ctp/api/src/) → Performs the one-click compilation ctpmd.cp313-win_amd64.pyd, ctptd.cp313-win_amd64.pyd, ctpmd.pyi, ctptd.pyi

7. Purpose of the Scripts

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

8. Advantages

  • 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 .lib files; 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.

9. Community Support

10. Disclaimer

👈Disclaimer Content

11. Replenish

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

About

Building C++-to-Python Bindings for the CTP API Using Pybind11

Topics

Resources

License

Stars

Watchers

Forks

Contributors