首页 > 其他分享 >Rust: CTP的rust版本如何手工封装

Rust: CTP的rust版本如何手工封装

时间:2023-04-29 17:44:29浏览次数:37  
标签:CTP lib pub static Rust str 封装 rust

https://blog.csdn.net/wowotuo/article/details/86669758

这里指的手工封装,是指不用外部类似swig专用的库。

一、库、配置
1、DLL 交互的库
(1)libloading
https://github.com/nagisa/rust_libloading
(2)libc
Raw FFI bindings to platform libraries like libc.
https://github.com/rust-lang/libc

2、类型转换库
Rust封装CTP,涉及两个方面类型,一个是rust转c++; 另一个是c++转rust.

cbindgen: 可以根据此库,把rust的rs文件生成相应的头文件,提高效率,减少手工封装过程。
https://crates.io/crates/cbindgen

rust-bindgen: 可以根据此库将C/C++的头文件,自动生成Rust 的C绑定文件。
https://github.com/rust-lang/rust-bindgen

二、CTP DLL资料
http://www.sfit.com.cn/5_2_DocumentDown.htm

Api有3种通讯模式:
• 对话通讯模式:由客户端主动发起请求。Thost收到请求、处理请求后,返回1条或者多条响应纪录。例如登入、各项查询、报单、撤单等操作。
• 私有通讯模式:由Thost主动向客户端发出的相关信息。例如委托回报、成交回报、错单回报等
• 广播通讯模式:由Thost主动向所有客户端发出的公共信息,例如行情等。

文件名 文件描述
FtdcTraderApi.h 交易接口头文件
ThostFtdcMdApi.h 行情接口头文件
FtdcUserApiStruct.h 定义了一系列业务相关的数据结构头文件
FtdcUserApiDataType.h 定义了 API 所需的一系列数据类型头文件
thosttraderapi.dll,thostmduserapi.dll 动态链接库二进制文件
thostraderapi.lib,thostmduserapi.lib 导入库文件

CTP相关知识、封装具体的介绍可以参考:

https://zhuanlan.zhihu.com/p/20031646
Python量化交易平台开发教程系列1-类CTP交易API的工作原理
https://zhuanlan.zhihu.com/p/20031660
Python量化交易平台开发教程系列2-类CTP交易API的Python封装设计

关于测试环境SIMNOW:

CTP开发中使用的模拟账号密码,要到SIMNOW上注册。BrokerID为9999,账号即investorId,密码为SIMNOW的登陆密码。

三、CTP中 C++ .h文件的改写

在ctp文件中,有一类是数据结构.h;一类是类和虚方法接口的.h文件;量大,需要写一个自动转换的程序。

1、ThostFtdcUserApiDataType.h和ThostFtdcUserApiStruct.h

(1)ThostFtdcUserApiDataType.h头文件中的类型

比如:

/
///TFtdcTraderIDType是一个交易所交易员代码类型
/
typedef char TThostFtdcTraderIDType[21];

/
///TFtdcInvestorIDType是一个投资者代码类型
/
typedef char TThostFtdcInvestorIDType[13];

/
///TFtdcBrokerIDType是一个经纪公司代码类型
/
typedef char TThostFtdcBrokerIDType[11];

/
///TFtdcBrokerAbbrType是一个经纪公司简称类型
/
typedef char TThostFtdcBrokerAbbrType[9];

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(2)ThostFtdcUserApiStruct.h中结构体

struct CThostFtdcDisseminationField
{
    TThostFtdcSequenceSeriesType    SequenceSeries;
    TThostFtdcSequenceNoType    SequenceNo;
};
1
2
3
4
5
要转换成rust 中的结构体:[名字和类型可以沿用原来的,只是换个方式],比如:

pub struct CThostFtdcDisseminationField
{
    pub SequenceSeries : i16 ,
    pub SequenceNo : i32 ,
}
pub struct CThostFtdcReqUserLoginField
{
    pub TradingDay : & 'static str ,
    pub BrokerID : & 'static str ,
    pub UserID : & 'static str ,
    pub Password : & 'static str ,
    pub UserProductInfo : & 'static str ,
    pub InterfaceProductInfo : & 'static str ,
    pub ProtocolInfo : & 'static str ,
    pub MacAddress : & 'static str ,
    pub OneTimePassword : & 'static str ,
    pub ClientIPAddress : & 'static str ,
    pub LoginRemark : & 'static str ,
}
pub struct CThostFtdcRspUserLoginField
{
    pub TradingDay : & 'static str ,
    pub LoginTime : & 'static str ,
    pub BrokerID : & 'static str ,
    pub UserID : & 'static str ,
    pub SystemName : & 'static str ,
    pub FrontID : i32 ,
    pub SessionID : i32 ,
    pub MaxOrderRef : & 'static str ,
    pub SHFETime : & 'static str ,
    pub DCETime : & 'static str ,
    pub CZCETime : & 'static str ,
    pub FFEXTime : & 'static str ,
    pub INETime : & 'static str ,
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
转换成rust中这个类型后,rust才能使用。
细节:这里暂时没有考虑int->c_int之类。只是提供一个方法。

2、tradeApi.h 和mdApi.h的改写

(1)主要是把类改成struct;

tradeapi中:

class CThostFtdcTraderSpi
class TRADER_API_EXPORT CThostFtdcTraderApi
1
2
mdapi中:

class CThostFtdcMdSpi
class MD_API_EXPORT CThostFtdcMdApi
1
2
(2)还有虚方法改成接口 trait;比如:

virtual void OnFrontConnected(){};

///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
///@param nReason 错误原因
///        0x1001 网络读失败
///        0x1002 网络写失败
///        0x2001 接收心跳超时
///        0x2002 发送心跳失败
///        0x2003 收到错误报文
virtual void OnFrontDisconnected(int nReason){};
1
2
3
4
5
6
7
8
9
10
四、封装:Rust与C++交互的核心技术

封装的目标是什么,简单地说,需要根据http://www.sfit.com.cn/5_2_DocumentDown.htm提供的4个头文件,两个C++原生的dll,以及lib文件,生成一个(或两个)封装的dll:
使之,

能够接受原生dll回调信息,与c++交互;
能够接受rust中参数,与原生dll交互;

(一)关于相关库
相关的库还是不少的,下面只是一些例子。

cc-rs:
https://github.com/alexcrichton/cc-rs
A library to compile C/C++/assembly into a Rust library/application.

libloading
https://github.com/nagisa/rust_libloading
A memory-safer wrapper around system dynamic library loading primitives. The most important safety guarantee by this library is prevention of dangling-Symbols that may occur after a Library is unloaded.

bindgen
bindgen automatically generates Rust FFI bindings to C (and some C++) libraries.
https://github.com/rust-lang/rust-bindgen

(二)关于封装

1、封装Rust 调用原生dll部分
比如Req开头的:

extern crate libloading as lib;
//const 
#[cfg(target_arch = "x86")]
fn load_ordinal_lib() -> Library {
    Library::new("D:\\ctp-api\\tradeapi\\thostmduserapi.dll").expect("thostmduserapi.dll")
}

#[cfg(target_arch = "x86")]
//virtual void RegisterFront(char *pszFrontAddress) = 0;
fn RegisterFront(pszFrontAddress: String) -> lib::Result<()> {
    let lib = load_ordinal_lib();
    unsafe {
        let func: lib::Symbol<unsafe extern "C" fn(String) -> ()> = lib.get(b"RegisterFront")?;
        Ok(func(pszFrontAddress))
    }
}
//virtual void RegisterNameServer(char *pszNsAddress) = 0;
//#[cfg(target_arch = "x86")]
fn RegisterNameServer(pszNsAddress: String) -> lib::Result<()> {
    let lib = lib::Library::new("D:\\ctp-api\\tradeapi\\thostmduserapi.dll")?;
    unsafe {
        let func: lib::Symbol<unsafe extern "C" fn(String) -> ()> =
            lib.get(b"RegisterNameServer")?;
        Ok(func(pszNsAddress))
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2、封装原生dll回传给rust的部分
比如:On打开头的。
这个应是在C++中写的。方向与上面是相反的。

// Rust: 供c++中调用

pub extern "C" fn onRspUserLogin(
    pRspUserLogin: CThostFtdcRspUserLoginField,
    pRspInfo: CThostFtdcRspInfoField,
    nRequestID: i32,
    bIsLast: bool,
) {
}
1
2
3
4
5
6
7
C++中:(大致的写法,相当于伪代码吧)

virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {
      this->onRspUserLogin(pRspUserLogin, pRspInfo, nRequestID, bIsLast) //调用rust中的函数
}

1
2
3
4
这样,就把c++中的代码和rust函数之间的消息传递建立起来了。

下面文章值得参考一下:
https://blog.csdn.net/guiqulaxi920/article/details/78653054
Rust与C交互(FFI)中复杂类型的处理

五、与CTP 相关的一些具体技术问题

建议可以参考一下:
https://github.com/tashaxing/CTPtest

其中的难点在于:

int main()
{
    // 账号密码
    cout << "请输入账号: ";
    scanf("%s", gInvesterID);
    cout << "请输入密码: ";
    scanf("%s", gInvesterPassword);

    // 初始化行情线程
    cout << "初始化行情..." << endl;
    g_pMdUserApi = CThostFtdcMdApi::CreateFtdcMdApi();   // 创建行情实例
    CThostFtdcMdSpi *pMdUserSpi = new CustomMdSpi;       // 创建行情回调实例
    g_pMdUserApi->RegisterSpi(pMdUserSpi);               // 注册事件类
    g_pMdUserApi->RegisterFront(gMdFrontAddr);           // 设置行情前置地址
    g_pMdUserApi->Init();                                // 连接运行
    
    // 初始化交易线程
    cout << "初始化交易..." << endl;
    g_pTradeUserApi = CThostFtdcTraderApi::CreateFtdcTraderApi(); // 创建交易实例
    //CThostFtdcTraderSpi *pTradeSpi = new CustomTradeSpi;
    CustomTradeSpi *pTradeSpi = new CustomTradeSpi;               // 创建交易回调实例
    g_pTradeUserApi->RegisterSpi(pTradeSpi);                            // 注册事件类
    g_pTradeUserApi->SubscribePublicTopic(THOST_TERT_RESTART);    // 订阅公共流
    g_pTradeUserApi->SubscribePrivateTopic(THOST_TERT_RESTART);   // 订阅私有流
    g_pTradeUserApi->RegisterFront(gTradeFrontAddr);              // 设置交易前置地址
    g_pTradeUserApi->Init();                                      // 连接运行
        

    // 等到线程退出
    g_pMdUserApi->Join();
    delete pMdUserSpi;
    g_pMdUserApi->Release();

    g_pTradeUserApi->Join();
    delete pTradeSpi;
    g_pTradeUserApi->Release();

    // 转换本地k线数据
    //TickToKlineHelper tickToKlineHelper;
    //tickToKlineHelper.KLineFromLocalData("market_data.csv", "K_line_data.csv");
    
    getchar();
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
其中,
(1) 初始化行情线程和初始化交易线程中难点;
(2) 这里c++的类在rust中只能用struct对应;
(3) 注册、回调和订阅在rust 中如何实现?

待续…
————————————————
版权声明:本文为CSDN博主「songroom」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wowotuo/article/details/86669758

标签:CTP,lib,pub,static,Rust,str,封装,rust
From: https://www.cnblogs.com/dhcn/p/17364299.html

相关文章

  • rust完全限定语法
    <TypeasTrait>::function(receiver_if_method,next_arg,...);上面定义中,第一个参数是方法接收器receiver(三种self),只有方法才拥有,例如关联函数就没有receiver。一般情况下,rust的编译器能够自动推导。只有当存在多个同名函数或方法,且Rust无法区分出你想调用的目标函数时,......
  • Vulhub 漏洞学习之:Strust2
    Vulhub漏洞学习之:Strust2目录Vulhub漏洞学习之:Strust21S2-001远程代码执行漏洞1.1环境安装1.2漏洞利用过程1.3GetShell2S2-005远程代码执行漏洞环境2.1环境安装2.2漏洞利用过程2.3GetShell3S2-007远程代码执行漏洞3.1环境安装3.2漏洞利用过程3.3GetShell4S2-0......
  • rust中的self与Self
    selfself是一个代表类型实例(或者是类型的引用或者是值)的关键字,在Rust的方法中使用self可以引用当前类型的实例或者类型本身。具体来说,当我们定义一个方法时,使用self关键字作为方法的第一个参数可以让我们在调用该方法时直接访问类型实例本身structPoint{x:f32,......
  • Rust -- 模式与匹配
    1.模式用来匹配类型中的结构(数据的形状),结合模式和match表达式提供程序控制流的支配权模式组成内容字面量解构的数组、枚举、结构体、元祖变量通配符占位符流程:匹配值-->是否拥有正确的数据-->运行特定的代码2.使用模式的位置match分支:由match关键字、......
  • Rust编程语言入门之最后的项目:多线程 Web 服务器
    最后的项目:多线程Web服务器构建多线程Web服务器在socket上监听TCP连接解析少量的HTTP请求创建一个合适的HTTP响应使用线程池改进服务器的吞吐量优雅的停机和清理注意:并不是最佳实践创建项目~/rust➜cargonewhelloCreatedbinary(application)`......
  • worker-rust
    添加target:wasm32-unknown-unknownrustuptargetaddwasm32-unknown-unknowninfo:downloadingcomponent'rust-std'for'wasm32-unknown-unknown'info:installingcomponent'rust-std'for'wasm32-unknown-unknown'19.0M......
  • rust交叉编译配置:windows上编译linux可执行程序
    rust交叉编译配置:windows上编译linux可执行程序简述交叉编译大概指在在一种计算机环境中运行的编译程序,能编译出在另外一种环境下运行的代码.本次,我们配置的是在windows上编译出在linux上运行的rust可执行程序.我们在安装rust之后,默认会安装跟机器环境搭配的编译相关工具.......
  • Rust编程语言入门之高级特性
    高级特性主要内容不安全Rust高级Trait高级类型高级函数和闭包宏一、不安全Rust匹配命名变量隐藏着第二个语言,它没有强制内存安全保证:UnsafeRust(不安全的Rust)和普通的Rust一样,但提供了额外的“超能力”UnsafeRust存在的原因:静态分析是保守的。使用......
  • Rust语言 学习17 模式匹配
    一、模式基本概念二、模式可辩驳性三、模式语法......
  • Rust、Go 和 Swift 在性能和并发性方面有何差异?
    Rust是一种系统编程语言,旨在快速、安全和并发。其性能令人印象深刻,可以生成快速高效的机器代码。Rust 的编译器使用 LLVM 基础架构,它针对目标架构优化了代码。此外,Rust 的所有权和借用系统确保内存得到有效管理,没有任何运行时开销。Rust的并发模型是基于actor模型的,也就是说并......