Metadata-Version: 2.4
Name: homalos-ctp
Version: 6.7.11.5
Summary: CTP Python API extension module construction.
Project-URL: Homepage, https://github.com/Homalos/ctp
Project-URL: Repository, https://github.com/Homalos/ctp
Project-URL: Documentation, https://github.com/Homalos/ctp/blob/main/README.md
Project-URL: Issues, https://github.com/Homalos/ctp/issues
Project-URL: Documentation (中文), https://github.com/Homalos/ctp/blob/main/README_CN.md
Author-email: Lumosylva <donnymoving@gmail.com>
License: MIT License
        
        Copyright (c) 2025 Homalos
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: ctp,investment,quantitative,trading
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: Chinese (Simplified)
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.13
Requires-Dist: hatch>=1.14.1
Requires-Dist: meson-python>=0.18.0
Requires-Dist: pybind11-stubgen>=2.5.5
Requires-Dist: pybind11>=3.0.1
Requires-Dist: twine>=6.1.0
Description-Content-Type: text/markdown

<p align="center">
  English |
  <a href="https://github.com/Homalos/ctp/blob/main/README_CN.md">简体中文</a>
</p>

# 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](https://www.simnow.com.cn/static/apiDownload.action)
- **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

```reStructuredText
/
├── 📂 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)
├── 📁 hatch_build.py		# Hatch build hook (sets platform tags during packaging via `hatch build`)
├── 📁 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)**

```bash
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
```

**Method 2: Install within a Specific Python Environment**

```bash
pip install uv
```

#### 3.1.2 On Linux

```bash
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:

```bash
uv python install 3.13
```

## 4. Usage

### 4.1 Installation via Command

```bash
pip install homalos-ctp
```

### 4.2 Installation from Source

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

#### 4.2.1 Installing Dependencies

```bash
# 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

```bash
.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

```bash
# 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:

```reStructuredText
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:

```reStructuredText
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

- **Technical Exchange (QQ Group)**: `446042777`
- [pypi.org](https://pypi.org/project/homalos-ctp)

## 10. Disclaimer

**[Disclaimer Content](docs/Disclaimer.md)**

## 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](https://github.com/vnpy/vnpy_ctp)

---

*homalos-ctp*
*Last Updated: 2026-05-08*