综合交易平台(Comprehensive Transaction Platform)是上海期货信息技术有限公司为期货公司开发的一套期货经纪业务管理系统,提供了完全公开的交易接口CTP_API。
在CTP_API中所有的数据结构由ThostFtdcUserApiStruct.h文件提供,在开发过程中,我们需要把结构体内容格式化输出来校验及保存内容,但CTP_API中并没有提供这些结构体的C++标准输出的扩展,需要自己为每个结构体编写标准输出,非常麻烦。
由于
ThostFtdcUserApiStruct.h文件格式良好且非常有规律,考虑使用awk脚本来生成所有结构体的标准输出,k脚本genostream.awk内容如下
BEGIN {
#输出编译指令
printf("#pragma once\n");
#输出包含文件
printf("#include <iostream>\n");
printf("#include \"ThostFtdcUserApiStruct.h\"\n");
printf("\n\n");
}
#结构体定义起始
$1 == "struct" {
#输出函数声明部分
printf("inline std::ostream& operator << (std::ostream &os, const %s &field)\n", $2);
next
}
#结构体定义起始的大括号
$0 == "{" {
#输出函数起始的大括号
printf("{\n");
#输出函数返回的标准输出
printf("\treturn os\n");
next
}
#结构体的字段定义
NF == 2 && $0 ~ /.*;$/ {
#除去字段名结尾的分隔符
gsub(";", "", $2);
#输出格式 字段名字:字段内容,
printf("\t\t<< \"%s:\" << field.%s << \",\"\n", $2, $2);
next
}
#结构体的结束标志
$0 == "};" {
#输出函数定义的结束大括号
printf("\t;\n");
printf("}\n\n");
next
}
执行
awk -f genostream.awk ThostFtdcUserApiStruct.h > ctpapi_ostream.hpp,生成CTP_API结构体的标准输出文件ctpapi_ostream.hpp,下面展示部分文件内容
#pragma once
#include <iostream>
#include "ThostFtdcUserApiStruct.h"
inline std::ostream& operator << (std::ostream &os, const CThostFtdcDisseminationField &field)
{
return os
<< "SequenceSeries:" << field.SequenceSeries << ","
<< "SequenceNo:" << field.SequenceNo << ","
;
}
inline std::ostream& operator << (std::ostream &os, const CThostFtdcReqUserLoginField &field)
{
return os
<< "TradingDay:" << field.TradingDay << ","
<< "BrokerID:" << field.BrokerID << ","
<< "UserID:" << field.UserID << ","
<< "Password:" << field.Password << ","
<< "UserProductInfo:" << field.UserProductInfo << ","
<< "InterfaceProductInfo:" << field.InterfaceProductInfo << ","
<< "ProtocolInfo:" << field.ProtocolInfo << ","
<< "MacAddress:" << field.MacAddress << ","
<< "OneTimePassword:" << field.OneTimePassword << ","
<< "ClientIPAddress:" << field.ClientIPAddress << ","
<< "LoginRemark:" << field.LoginRemark << ","
;
}
inline std::ostream& operator << (std::ostream &os, const CThostFtdcRspUserLoginField &field)
{
return os
<< "TradingDay:" << field.TradingDay << ","
<< "LoginTime:" << field.LoginTime << ","
<< "BrokerID:" << field.BrokerID << ","
<< "UserID:" << field.UserID << ","
<< "SystemName:" << field.SystemName << ","
<< "FrontID:" << field.FrontID << ","
<< "SessionID:" << field.SessionID << ","
<< "MaxOrderRef:" << field.MaxOrderRef << ","
<< "SHFETime:" << field.SHFETime << ","
<< "DCETime:" << field.DCETime << ","
<< "CZCETime:" << field.CZCETime << ","
<< "FFEXTime:" << field.FFEXTime << ","
<< "INETime:" << field.INETime << ","
;
}
inline std::ostream& operator << (std::ostream &os, const CThostFtdcUserLogoutField &field)
{
return os
<< "BrokerID:" << field.BrokerID << ","
<< "UserID:" << field.UserID << ","
;
}