diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 1efe90fff0360b17fd1dfdad3aa20a58f4c5a9e4..67ae46e1616d6f37c2b9ede371931e9532d2a573 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -5,16 +5,6 @@ cmake_minimum_required (VERSION 3.8) project ("gallop") -SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} - "C:/Boost/include/boost-1_80" - "${PROJECT_SOURCE_DIR}/share" - "${PROJECT_SOURCE_DIR}/include" -) -SET(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} - "C:/Boost/lib" - "${PROJECT_SOURCE_DIR}/../bin" -) - set(CMAKE_CXX_STANDARD 17) SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/../bin) @@ -22,12 +12,36 @@ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/../bin) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/../bin) #SET(CMAKE_DEBUG_POSTFIX "_d") -FIND_PACKAGE(Boost) +# set(Boost_NO_SYSTEM_PATHS ON) +set(BOOST_ROOT "/home/ubuntu/boost_1_80_0/install") +set(BOOST_INCLUDE_DIRS "${BOOST_ROOT}/include") +set(BOOST_LIBRARY_DIRS "${BOOST_ROOT}/lib") + +FIND_PACKAGE(Boost REQUIRED) IF (Boost_FOUND) INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR}) ADD_DEFINITIONS( "-DHAS_BOOST" ) + ADD_DEFINITIONS( "-DBOOST_ALL_DYN_LINK" ) ENDIF() +IF (UNIX) +ADD_DEFINITIONS( "-fPIC" ) +set(SYS_LIBS pthread rt) +set(BOOST_LIBS boost_thread boost_log boost_log_setup boost_system boost_filesystem) +set(CTP_LIBS thostmduserapi_se thosttraderapi_se) +ENDIF() + +SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} + "${PROJECT_SOURCE_DIR}/share" + "${PROJECT_SOURCE_DIR}/include" + ${Boost_INCLUDE_DIRS} +) +SET(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} + ${BOOST_LIBRARY_DIRS} + ${PROJECT_SOURCE_DIR}/api/ctp_6.6.9 + "${PROJECT_SOURCE_DIR}/../bin" +) + # 包含子项目。 add_subdirectory ("gallop") diff --git a/src/api/ctp_6.6.9/libthostmduserapi_se.so b/src/api/ctp_6.6.9/libthostmduserapi_se.so new file mode 120000 index 0000000000000000000000000000000000000000..c304fc4709ec7c4fde4a5ee73bcbd0fa472652fe --- /dev/null +++ b/src/api/ctp_6.6.9/libthostmduserapi_se.so @@ -0,0 +1 @@ +thostmduserapi_se.so \ No newline at end of file diff --git a/src/api/ctp_6.6.9/libthosttraderapi_se.so b/src/api/ctp_6.6.9/libthosttraderapi_se.so new file mode 120000 index 0000000000000000000000000000000000000000..cca8b5794d0a60c4fc23762f9df55692eafbb7e0 --- /dev/null +++ b/src/api/ctp_6.6.9/libthosttraderapi_se.so @@ -0,0 +1 @@ +thosttraderapi_se.so \ No newline at end of file diff --git a/src/api/ctp_6.6.9/thostmduserapi_se.so b/src/api/ctp_6.6.9/thostmduserapi_se.so new file mode 100755 index 0000000000000000000000000000000000000000..928c96854bc8816fbbe2d3855e6168ff0fe038d1 Binary files /dev/null and b/src/api/ctp_6.6.9/thostmduserapi_se.so differ diff --git a/src/api/ctp_6.6.9/thosttraderapi_se.so b/src/api/ctp_6.6.9/thosttraderapi_se.so new file mode 100755 index 0000000000000000000000000000000000000000..c2209a0dbdc202917361ab55941dc0a1bd1bbe73 Binary files /dev/null and b/src/api/ctp_6.6.9/thosttraderapi_se.so differ diff --git a/src/build/core/liblightning.so b/src/build/core/liblightning.so new file mode 100755 index 0000000000000000000000000000000000000000..976c1fdd4f08bbcd1891ee47c95e680fff929e47 Binary files /dev/null and b/src/build/core/liblightning.so differ diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index a30c52c0484934996b4683c10a132bdfdd7f2d8c..8db9ebd86cfe36f5dae23495e20559f8b5d06fe0 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -5,4 +5,4 @@ link_directories(${CMAKE_LIBRARY_PATH}) #target_sources(${target} PRIVATE ${A1_DIR_VAR}) add_library(lightning SHARED "runtime.cpp" "evaluate.cpp" "pod_chain.cpp" "context.cpp" "lightning.cpp" "log_wapper.cpp" "trading_section.cpp") -target_link_libraries(lightning "market" "simulator" "trader" "recorder") +target_link_libraries(lightning "market" "simulator" "trader" "recorder" ${SYS_LIBS} ${BOOST_LIBS} ${CTP_LIBS}) diff --git a/src/core/context.cpp b/src/core/context.cpp index f682e5264b194beef3bb1ff3f00083c162dc35f0..79b29378762a5d7c978d73b399bdb00e12cf580c 100644 --- a/src/core/context.cpp +++ b/src/core/context.cpp @@ -61,7 +61,7 @@ context::~context() bool context::init(boost::property_tree::ptree& ctrl, boost::property_tree::ptree& include_config, boost::property_tree::ptree& rcd_config,bool reset_trading_day) { - auto& localdb_name = ctrl.get("localdb_name"); + auto localdb_name = ctrl.get("localdb_name"); if(!localdb_name.empty()) { _userdata_size = ctrl.get("userdata_size", 4096 * MAX_UNITID); diff --git a/src/core/trading_section.cpp b/src/core/trading_section.cpp index 86e8ab8f544a3d83260921dbc1dc927c171a3f0a..47dcfcb946e80033d570201d28487295610888b0 100644 --- a/src/core/trading_section.cpp +++ b/src/core/trading_section.cpp @@ -2,7 +2,7 @@ #include #include -trading_section::trading_section(const std::string& config_path):_config_csv(config_path, rapidcsv::LabelParams::LabelParams(0, 0)) +trading_section::trading_section(const std::string &config_path) : _config_csv(config_path, rapidcsv::LabelParams(0, 0)) { } @@ -19,7 +19,7 @@ void trading_section::init(uint32_t trading_day, time_t last_time) time_t last_day_time = get_day_begin(last_time); if(trading_day_time != last_day_time) { - //trading_day_time != last_day_time ˵ǰϳʼ + // trading_day_time != last_day_time 说明是前天晚上初始化的 for (size_t i = 0; i < _config_csv.GetRowCount(); i++) { uint32_t is_day = _config_csv.GetCell("day_or_night", i); @@ -33,7 +33,7 @@ void trading_section::init(uint32_t trading_day, time_t last_time) } else { - //ҹõǰʱ + // 夜盘用当前时间计算 time_t begin_time = make_datetime(last_day_time, begin_time_str.c_str()); _trading_section[begin_time] = get_next_time(begin_time, end_time_str.c_str()); LOG_DEBUG("trading_section : %s %s", datetime_to_string(begin_time).c_str(), datetime_to_string(_trading_section[begin_time]).c_str()); @@ -42,7 +42,7 @@ void trading_section::init(uint32_t trading_day, time_t last_time) } else { - //ڶʼ ʼҹ̣ҹѾˣ + // 第二天白天初始化的 不初始化夜盘(夜盘已经错过了) for (size_t i = 0; i < _config_csv.GetRowCount(); i++) { uint32_t is_day = _config_csv.GetCell("day_or_night", i); diff --git a/src/gallop/CMakeLists.txt b/src/gallop/CMakeLists.txt index 120bfd9fe4a6bd5b98d01cfff3504b49512bc84a..4854426de5d548b6d4c9af7271372e3788b96059 100644 --- a/src/gallop/CMakeLists.txt +++ b/src/gallop/CMakeLists.txt @@ -9,10 +9,11 @@ link_directories(${CMAKE_LIBRARY_PATH}) AUX_SOURCE_DIRECTORY(strategy STRATEGY_DIR_VAR) + # 将源代码添加到此项目的可执行文件。 add_executable (gallop "gallop.cpp" "pugixml.cpp" ${STRATEGY_DIR_VAR} ) -target_link_libraries(gallop "libltpp") +target_link_libraries(gallop "libltpp" ${CTP_LIBS}) if (CMAKE_VERSION VERSION_GREATER 3.12) diff --git a/src/include/data_types.hpp b/src/include/data_types.hpp index df88028f9c0fd682b7f96eef668b532c287cca3a..40188367d4576d149478818e2c9ee9730c935d89 100644 --- a/src/include/data_types.hpp +++ b/src/include/data_types.hpp @@ -3,11 +3,11 @@ struct tick_info { - code_t id; //ԼID + code_t id; //合约ID - time_t time; //ʱ + time_t time; //时间 - uint32_t tick; // + uint32_t tick; //毫秒数 double_t price; //pDepthMarketData->LastPrice @@ -88,31 +88,31 @@ struct tick_info } }; -typedef enum deal_direction +typedef enum deal_direction ENUM_TYPE_INT { - DD_DOWN = -1, // - DD_FLAT = 0, //ƽ - DD_UP = 1, // -}deal_direction; + DD_DOWN = -1, //向下 + DD_FLAT = 0, //平 + DD_UP = 1, //向上 +} deal_direction; -typedef enum deal_status +typedef enum deal_status ENUM_TYPE_INT { DS_INVALID, - DS_DOUBLE_OPEN, //˫ - DS_OPEN, // - DS_CHANGE, // - DS_CLOSE, //ƽ - DS_DOUBLE_CLOSE,//˫ƽ + DS_DOUBLE_OPEN, //双开 + DS_OPEN, //开仓 + DS_CHANGE, //换手 + DS_CLOSE, //平仓 + DS_DOUBLE_CLOSE,//双平 }deal_status; struct deal_info { - // + //现手 uint32_t volume_delta; - // + //增仓 double_t interest_delta; - // + //方向 deal_direction direction; deal_info() : @@ -147,11 +147,11 @@ struct deal_info }; struct position_item { - //λ + //仓位 uint32_t postion; - //۸ + //价格 double_t price; - // + //冻结 uint32_t frozen; position_item() : @@ -180,14 +180,14 @@ struct position_item struct position_info { - code_t id; //ԼID + code_t id; //合约ID position_info(const code_t& code) :id(code) {} - // + //今仓 position_item today_long; position_item today_short; - // + //昨仓 position_item yestoday_long; position_item yestoday_short; @@ -241,31 +241,31 @@ const account_info default_account; /* - * ־ + * 订单标志 */ -typedef enum order_flag +typedef enum order_flag ENUM_TYPE_CHAR { - OF_NOR = '0', //ͨ - OF_FAK, //ȫȫȴԶ - OF_FOK, //ɲȴԶ + OF_NOR = '0', //普通订单 + OF_FAK, //全成全撤,不等待自动撤销 + OF_FOK, //部成部撤,不等待自动撤销 } order_flag; /* - * ƽ + * 开平方向 */ -typedef enum offset_type +typedef enum offset_type ENUM_TYPE_CHAR { - OT_OPEN = '0', // - OT_CLOSE //ƽ,Ϊƽ + OT_OPEN = '0', //开仓 + OT_CLOSE //平仓,上期为平昨 } offset_type; /* - * շ + * 多空方向 */ -typedef enum direction_type +typedef enum direction_type ENUM_TYPE_CHAR { - DT_LONG = '0', // - DT_SHORT // + DT_LONG = '0', // 做多 + DT_SHORT // 做空 } direction_type; struct order_info @@ -308,19 +308,18 @@ struct order_info }; const order_info default_order ; - -//ͳ +//订单统计数据 struct order_statistic { - //µ + //下单数量 uint32_t place_order_amount; - //ί + //委托数量 uint32_t entrust_amount; - //ɽ + //成交数量 uint32_t trade_amount; - // + //撤单数量 uint32_t cancel_amount; - // + //错误数量 uint32_t error_amount; order_statistic(): @@ -358,9 +357,9 @@ struct transfer_info }; const transfer_info default_transfer; -typedef enum error_type +typedef enum error_type ENUM_TYPE_INT { ET_PLACE_ORDER, ET_CANCEL_ORDER, ET_OTHER_ERROR -}error_type; \ No newline at end of file +} error_type; \ No newline at end of file diff --git a/src/include/define.h b/src/include/define.h index 512dac4dd45cc85ac622ea00cea7eb0a77f87191..23183f548ee93572e6053fdc529aa0cff89c14d7 100644 --- a/src/include/define.h +++ b/src/include/define.h @@ -8,6 +8,18 @@ #include #include #include +#include +#include +#include + +#ifndef WIN32 +#include "save_s.hpp" +#define ENUM_TYPE_INT : int +#define ENUM_TYPE_CHAR : char +#else +#define ENUM_TYPE_INT +#define ENUM_TYPE_CHAR +#endif #ifndef EXPORT_FLAG #ifdef _MSC_VER @@ -114,11 +126,11 @@ typedef uint8_t untid_t; typedef uint64_t estid_t; -#define INVALID_ESTID 0x0LLU +#define INVALID_ESTID 0x0LLU -#define EXCHANGE_ID_SHFE "SHFE" // -#define EXCHANGE_ID_DCE "DCE" // -#define EXCHANGE_ID_CZCE "CZCE" //֣ +#define EXCHANGE_ID_SHFE "SHFE" //上期所 +#define EXCHANGE_ID_DCE "DCE" //大商所 +#define EXCHANGE_ID_CZCE "CZCE" //郑商所 struct tick_info; @@ -128,21 +140,21 @@ struct position_info; struct account_info; -enum trading_optimal; +enum trading_optimal ENUM_TYPE_INT; -enum order_flag; +enum order_flag ENUM_TYPE_CHAR; -enum offset_type; +enum offset_type ENUM_TYPE_CHAR; -enum direction_type; +enum direction_type ENUM_TYPE_CHAR; -enum event_type; +enum event_type ENUM_TYPE_INT; -enum error_type; +enum error_type ENUM_TYPE_INT; -enum deal_direction ; +enum deal_direction ENUM_TYPE_INT; -enum deal_status; +enum deal_status ENUM_TYPE_INT; typedef std::function filter_function; @@ -162,13 +174,13 @@ extern "C" EXPORT_FLAG void log_format(log_level lv,const char* format, ...); } #ifndef NDEBUG -#define LOG_TRACE(format, ...) log_format(LLV_TRACE,format, __VA_ARGS__); -#define LOG_DEBUG(format, ...) log_format(LLV_DEBUG,format, __VA_ARGS__); +#define LOG_TRACE(format, ...) log_format(LLV_TRACE, format, ##__VA_ARGS__); +#define LOG_DEBUG(format, ...) log_format(LLV_DEBUG, format, ##__VA_ARGS__); #else #define LOG_DEBUG(format, ...) #define LOG_TRACE(format, ...) #endif -#define LOG_INFO(format, ...) log_format(LLV_INFO,format, __VA_ARGS__); -#define LOG_WARNING(format, ...) log_format(LLV_WARNING,format, __VA_ARGS__); -#define LOG_ERROR(format, ...) log_format(LLV_ERROR,format, __VA_ARGS__); -#define LOG_FATAL(format, ...) log_format(LLV_FATAL,format, __VA_ARGS__); \ No newline at end of file +#define LOG_INFO(format, ...) log_format(LLV_INFO, format, ##__VA_ARGS__); +#define LOG_WARNING(format, ...) log_format(LLV_WARNING, format, ##__VA_ARGS__); +#define LOG_ERROR(format, ...) log_format(LLV_ERROR, format, ##__VA_ARGS__); +#define LOG_FATAL(format, ...) log_format(LLV_FATAL, format, ##__VA_ARGS__); \ No newline at end of file diff --git a/src/include/save_s.hpp b/src/include/save_s.hpp new file mode 100644 index 0000000000000000000000000000000000000000..170fd0163ec07548b52b0205acd08065d4cd47ce --- /dev/null +++ b/src/include/save_s.hpp @@ -0,0 +1,88 @@ +#pragma once +#ifndef __SAVE_S_H__ +#define __SAVE_S_H__ + +#ifndef WIN32 + +#include +#include +#include +#include +#include + +#define sscanf_s sscanf +// #define localtime_s localtime + + +inline error_t memcpy_s(void *dest, size_t destSize, const void *src, size_t count) +{ + if (dest == NULL || src == NULL) + return EINVAL; + if (destSize < count) + return ERANGE; + memcpy(dest, src, count); + return 0; +} + +inline error_t strcpy_s(char *dest, size_t destSize, const char *src) +{ + if (dest == NULL || src == NULL) + return EINVAL; + if (destSize < strlen(src) + 1) + return ERANGE; + strcpy(dest, src); + return 0; +} + +inline error_t strcpy_s(char *dest, const char *src) +{ + strcpy(dest, src); + return 0; +} + +inline error_t strlen_s(const char *str, size_t strSize, size_t *len) +{ + if (str == NULL || len == NULL) + return EINVAL; + *len = strnlen(str, strSize); + return 0; +} + +inline size_t strnlen_s(const char *str, size_t strSize) +{ + if (str == NULL) + return 0; + return strnlen(str, strSize); +} + +inline error_t localtime_s(struct tm *tm, const time_t *time) +{ + if (tm == NULL || time == NULL) + return EINVAL; + struct tm *result = localtime(time); + if (result == NULL) + return -1; + *tm = *result; + return 0; +} + +inline int sprintf_s(char *__restrict __s, size_t __maxlen, const char *__restrict __format, ...) +{ + va_list va; + va_start(va, __format); + int ret =snprintf(__s, __maxlen, __format, va); + va_end(va); + return ret; +} + +inline int sprintf_s(char *__restrict __s, const char *__restrict __format, ...) +{ + va_list va; + va_start(va, __format); + int ret = sprintf(__s, __format, va); + return ret; +} + +#endif + +#endif diff --git a/src/include/strategy.h b/src/include/strategy.h index c31df581687dcef9070f5c411443ca2eb241bbff..41900ea1eb2f50f6c83752c6209adb51af8ff760 100644 --- a/src/include/strategy.h +++ b/src/include/strategy.h @@ -1,4 +1,5 @@ #pragma once +#include #include #include #include @@ -14,13 +15,14 @@ public : public: param(const char* str); - template< typename T> - T get(const std::string& key)const + template + T get(const char key[]) const { - return get(key); + return get(std::string(key)); } - template<> - const char* get(const std::string& key)const + + template + typename std::enable_if::value, T>::type get(const std::string &key) const { auto it = _param.find(key); if (it == _param.end()) @@ -30,8 +32,8 @@ public : return it->second.c_str(); } - template<> - int32_t get(const std::string& key)const + template + typename std::enable_if::value, T>::type get(const std::string &key) const { auto it = _param.find(key); if (it == _param.end()) @@ -40,8 +42,9 @@ public : } return std::atoi(it->second.c_str()); } - template<> - uint32_t get(const std::string& key)const + + template + typename std::enable_if::value, T>::type get(const std::string &key) const { auto it = _param.find(key); if (it == _param.end()) @@ -51,8 +54,8 @@ public : return static_cast(std::atoi(it->second.c_str())); } - template<> - double_t get(const std::string& key)const + template + typename std::enable_if::value, T>::type get(const std::string &key) const { auto it = _param.find(key); if (it == _param.end()) @@ -61,8 +64,8 @@ public : } return std::atof(it->second.c_str()); } - template<> - int64_t get(const std::string& key)const + template + typename std::enable_if::value, T>::type get(const std::string &key) const { auto it = _param.find(key); if (it == _param.end()) @@ -71,8 +74,8 @@ public : } return std::atoll(it->second.c_str()); } - template<> - uint64_t get(const std::string& key)const + template + typename std::enable_if::value, T>::type get(const std::string &key) const { auto it = _param.find(key); if (it == _param.end()) @@ -95,24 +98,22 @@ public: virtual ~strategy(); /* - * ʼ - */ + * ʼ + */ void init(straid_t id,class strategy_manager* manager); - //ص + // ص private: - /* * ʼ¼ * ֻصһ */ - virtual void on_init() {}; + virtual void on_init(){}; public: - /* - * ճʼ - */ + * ճʼ + */ virtual void on_ready() {}; /* @@ -120,7 +121,6 @@ public: */ virtual void on_tick(const tick_info& tick, const deal_info& deal) {} - /* * ջر * @is_success Ƿɹ @@ -132,7 +132,7 @@ public: * ɽر * * @localid ضid - */ + */ virtual void on_deal(estid_t localid,uint32_t deal_volume, uint32_t total_volume) {} /* @@ -142,7 +142,6 @@ public: */ virtual void on_trade(estid_t localid, const code_t& code, offset_type offset, direction_type direction, double_t price, uint32_t volume) {} - /* * * @localid ضid @@ -162,7 +161,7 @@ public: virtual void on_destory() {} protected: - //ܺ + // ܺ /* * ൥ * code ڻ SHFF.rb2301 @@ -200,9 +199,9 @@ protected: estid_t buy_for_close(const code_t& code, uint32_t count, double_t price = 0, order_flag flag = OF_NOR); /* - * µ - * order_id µصid - */ + * µ + * order_id µصid + */ estid_t place_order(offset_type offset, direction_type direction, const code_t& code, uint32_t count, double_t price = 0, order_flag flag = OF_NOR); /* * @@ -210,36 +209,35 @@ protected: */ void cancel_order(estid_t order_id); - /** - * ȡλϢ - */ + /** + * ȡλϢ + */ const position_info& get_position(const code_t& code) const; /** - * ȡ˻ʽ - */ + * ȡ˻ʽ + */ const account_info& get_account() const; - /** - * ȡίж - **/ + /** + * ȡίж + **/ const order_info& get_order(estid_t order_id) const; - /** - * - **/ + * + **/ void subscribe(const code_t& code) ; /** - * ȡ - **/ + * ȡ + **/ void unsubscribe(const code_t& code) ; /** - * ȡʱ - * - */ + * ȡʱ + * + */ time_t get_last_time() const ; /** @@ -248,15 +246,14 @@ protected: void use_custom_chain(bool flag); /* - * ó(trueʱ) - */ + * ó(trueʱ) + */ void set_cancel_condition(estid_t order_id, std::function callback); - /** - * ȡһµʱ - * 罻շ0 - */ + * ȡһµʱ + * 罻շ0 + */ time_t last_order_time(); @@ -267,21 +264,21 @@ protected: } /** - * ȡûݣֱдᱻ浽ڴ - * עʱidܸı - * IDֵlocaldbеuserdata_blockӦ - */ + * ȡûݣֱдᱻ浽ڴ + * עʱidܸı + * IDֵlocaldbеuserdata_blockӦ + */ void* get_userdata(size_t size); /** - * ȡ - */ + * ȡ + */ uint32_t get_trading_day()const; /** - * Ƿ׼ - */ + * Ƿ׼ + */ bool is_trading_ready()const; }; diff --git a/src/market/ctp_market.cpp b/src/market/ctp_market.cpp index 2cf17452defd8a21ad9cbf88606416114cfb0b92..fe5d10839bc4e1a318c14f607e4a7c1644d52683 100644 --- a/src/market/ctp_market.cpp +++ b/src/market/ctp_market.cpp @@ -81,7 +81,7 @@ void ctp_market::OnRspUserLogin( CThostFtdcRspUserLoginField *pRspUserLogin, CTh if(bIsLast) { LOG_INFO("UserLogin : Market data server logined, {%s} {%s}", pRspUserLogin->TradingDay, pRspUserLogin->UserID); - // + //订阅行情数据 do_subscribe(); if(!_is_inited) { @@ -113,7 +113,7 @@ void ctp_market::OnRtnDepthMarketData( CThostFtdcDepthMarketDataField *pDepthMar LOG_DEBUG("MarketData = [%s] [%f]\n", pDepthMarketData->InstrumentID, pDepthMarketData->LastPrice); tick_info tick ; - auto& excg_it = _instrument_id_list.find(pDepthMarketData->InstrumentID); + auto excg_it = _instrument_id_list.find(pDepthMarketData->InstrumentID); if(excg_it != _instrument_id_list.end()) { tick.id = code_t(pDepthMarketData->InstrumentID, excg_it->second.c_str()); @@ -122,7 +122,7 @@ void ctp_market::OnRtnDepthMarketData( CThostFtdcDepthMarketDataField *pDepthMar { tick.id = code_t(pDepthMarketData->InstrumentID, pDepthMarketData->ExchangeID); } - //ҵڷصǿգԼȡڼϸʱҵʱ + //业务日期返回的是空,所以这里自己获取本地日期加上更新时间来计算业务日期时间 tick.time = get_day_begin(get_now()) + make_time(pDepthMarketData->UpdateTime); tick.tick = pDepthMarketData->UpdateMillisec; tick.price = pDepthMarketData->LastPrice; @@ -198,14 +198,14 @@ void ctp_market::do_subscribe() num++; if (num == 500) { - _md_api->SubscribeMarketData(id_list, num);// + _md_api->SubscribeMarketData(id_list, num);//订阅行情 num = 0; } i++; } if (num > 0) { - _md_api->SubscribeMarketData(id_list, num);// + _md_api->SubscribeMarketData(id_list, num);//订阅行情 num = 0; } } @@ -220,13 +220,13 @@ void ctp_market::do_unsubscribe(const std::vector& code_list) num++; if (num == 500) { - _md_api->UnSubscribeMarketData(id_list, num);// + _md_api->UnSubscribeMarketData(id_list, num);//订阅行情 num = 0; } } if (num > 0) { - _md_api->UnSubscribeMarketData(id_list, num);// + _md_api->UnSubscribeMarketData(id_list, num);//订阅行情 num = 0; } } diff --git a/src/recorder/csv_recorder.cpp b/src/recorder/csv_recorder.cpp index 7daa42f0291b993febf5d47b5df0d3d6791adddd..458927f73c612178e1d68e5895a7a97453711fd3 100644 --- a/src/recorder/csv_recorder.cpp +++ b/src/recorder/csv_recorder.cpp @@ -6,7 +6,7 @@ #include #include -csv_recorder::csv_recorder(const char* basic_path) :_is_dirty(false), _order_lifecycle_csv(std::string(),rapidcsv::LabelParams::LabelParams(0,0)) +csv_recorder::csv_recorder(const char *basic_path) : _is_dirty(false), _order_lifecycle_csv(std::string(), rapidcsv::LabelParams((ssize_t)0, (ssize_t)0)) { if (!file_wapper::exists(basic_path)) { diff --git a/src/share/event_center.hpp b/src/share/event_center.hpp index 7163f0038a00ed8ec284e9a4f4b4d448bcebd476..62e1a3ee79006a7d629e6671d837307e21b49e61 100644 --- a/src/share/event_center.hpp +++ b/src/share/event_center.hpp @@ -4,8 +4,7 @@ #include #include - -typedef enum event_type +typedef enum event_type ENUM_TYPE_INT { ET_Invalid, ET_LoadFinish, diff --git a/src/share/time_utils.hpp b/src/share/time_utils.hpp index 7c4291dcf89e960259c7f7f3c9f4ccfd7e45b4e1..8544777836e0f9c19504c86b77da30abb2a8238b 100644 --- a/src/share/time_utils.hpp +++ b/src/share/time_utils.hpp @@ -2,6 +2,7 @@ #include #include +#include "save_s.hpp" #define ONE_DAY_SECONDS 86400 #define ONE_MINUTE_SECONDS 60 diff --git a/src/simulator/contract_parser.cpp b/src/simulator/contract_parser.cpp index a10a6ecae6f47b75ab1c9dad0e1cc1eef3713a06..3a4b761dd408050f88e5face69f0e2a86a7d332d 100644 --- a/src/simulator/contract_parser.cpp +++ b/src/simulator/contract_parser.cpp @@ -13,14 +13,14 @@ void contract_parser::init(const std::string& config_path) { LOG_INFO("contract_parser init \n"); _contract_info.clear(); - rapidcsv::Document config_csv(config_path, rapidcsv::LabelParams::LabelParams(0, -1)); + rapidcsv::Document config_csv(config_path, rapidcsv::LabelParams(0, -1)); for (size_t i = 0; i < config_csv.GetRowCount(); i++) { contract_info info ; const std::string& code_str = config_csv.GetCell("code", i); LOG_INFO("load contract code : %s \n", code_str.c_str()); info.code = code_t(code_str.c_str()); - info.charge_type = static_cast(config_csv.GetCell("charge_type", i)); + info.charge_type = static_cast(config_csv.GetCell("charge_type", i)); info.open_charge = config_csv.GetCell("open_charge", i); info.close_today_charge = config_csv.GetCell("close_today_charge", i); info.close_yestoday_charge = config_csv.GetCell("close_yestoday_charge", i); diff --git a/src/simulator/contract_parser.h b/src/simulator/contract_parser.h index be2458905223eabdc85ab16e06284393cc1e6e96..e111b33627c14d6e20847e78d2c8c0eecae22f46 100644 --- a/src/simulator/contract_parser.h +++ b/src/simulator/contract_parser.h @@ -3,22 +3,22 @@ #include #include -typedef enum +typedef enum { - CT_FIXED_AMOUNT = 1 ,//̶ - CT_PRICE_RATIO = 2,//۸ -}charge_type; + CT_FIXED_AMOUNT = 1 ,//固定金额 + CT_PRICE_RATIO = 2,//价格比例 +} charge_type_t; struct contract_info { code_t code ; - charge_type charge_type; + charge_type_t charge_type; double_t open_charge; double_t close_today_charge; double_t close_yestoday_charge; - double_t multiple; // - double_t margin_rate; //֤ + double_t multiple; //乘数 + double_t margin_rate; //保证金率 contract_info():charge_type(CT_FIXED_AMOUNT), open_charge(.0F), close_today_charge(.0F), close_yestoday_charge(.0F), multiple(.0F), margin_rate(.0F) {} diff --git a/src/simulator/order_container.cpp b/src/simulator/order_container.cpp index 960c3c9265fb254b475a61ce3ea41148182a8e47..d4bf359386f559e9c51246044fd466b26cc98942 100644 --- a/src/simulator/order_container.cpp +++ b/src/simulator/order_container.cpp @@ -27,7 +27,7 @@ void order_container::add_order(const order_info& order,order_flag flag,bool is_ void order_container::del_order(estid_t estid) { spin_lock lock(_mutex); - auto& odit = _order_info.find(estid); + auto odit = _order_info.find(estid); if (odit != _order_info.end()) { auto match = _order_match.find(odit->second.code); @@ -50,7 +50,7 @@ void order_container::del_order(estid_t estid) void order_container::set_seat(estid_t estid, uint32_t seat) { spin_lock lock(_mutex); - auto& odit = _order_info.find(estid); + auto odit = _order_info.find(estid); if (odit != _order_info.end()) { auto it = _order_match.find(odit->second.code); @@ -71,7 +71,7 @@ void order_container::set_seat(estid_t estid, uint32_t seat) void order_container::set_state(estid_t estid, order_state state) { spin_lock lock(_mutex); - auto& odit = _order_info.find(estid); + auto odit = _order_info.find(estid); if (odit != _order_info.end()) { auto it = _order_match.find(odit->second.code); @@ -129,7 +129,7 @@ void order_container::get_order_match(std::vector& match_list, cons const order_match* order_container::get_order_match(estid_t estid)const { spin_lock lock(_mutex); - auto& odit = _order_info.find(estid); + auto odit = _order_info.find(estid); if (odit != _order_info.end()) { auto it = _order_match.find(odit->second.code); @@ -152,7 +152,7 @@ bool order_container::get_order_info(order_info& order, estid_t estid)const { spin_lock lock(_mutex); LOG_TRACE("order_container get_order_info %lld %d ", estid, _order_info.size()); - auto& odit = _order_info.find(estid); + auto odit = _order_info.find(estid); if (odit != _order_info.end()) { order = odit->second; diff --git a/src/simulator/tick_simulator.cpp b/src/simulator/tick_simulator.cpp index a665966ef56240e5397d546056758fb6f9c8f57e..e93ba5e5ff72fd7aa066485ec799b6fcada2917a 100644 --- a/src/simulator/tick_simulator.cpp +++ b/src/simulator/tick_simulator.cpp @@ -1,4 +1,5 @@ #include "tick_simulator.h" +#include #include #include #include "contract_parser.h" diff --git a/src/trader/ctp_trader.cpp b/src/trader/ctp_trader.cpp index 318fefc09e0b1806359ce941f134d6bbbc3e4c1e..ad48a011f68ca59996c3d75e2c300a16ca428442 100644 --- a/src/trader/ctp_trader.cpp +++ b/src/trader/ctp_trader.cpp @@ -59,7 +59,7 @@ bool ctp_trader::init(const boost::property_tree::ptree& config) } char path_buff[64]; - sprintf_s(path_buff,64,"td_flow/%s/%s/", _broker_id.c_str(), _userid.c_str()); + snprintf(path_buff, 64, "td_flow/%s/%s/", _broker_id.c_str(), _userid.c_str()); if (!file_wapper::exists(path_buff)) { file_wapper::create_directories(path_buff); @@ -75,7 +75,7 @@ bool ctp_trader::init(const boost::property_tree::ptree& config) LOG_INFO("ctp_trader init %s ", _td_api->GetApiVersion()); _process_signal.wait(_process_mutex); _is_runing = true ; - //ѯ߳ȥͬ˻Ϣ + //启动查询线程去同步账户信息 if (_work_thread == nullptr) { _work_thread = new std::thread([this]() { @@ -294,11 +294,11 @@ void ctp_trader::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CTho if (pRspUserLogin) { - LOG_INFO("[%s][û¼] UserID:%s AppID:%s SessionID:%d FrontID:%d\n", + LOG_INFO("[%s][用户登录] UserID:%s AppID:%s SessionID:%d FrontID:%d\n", datetime_to_string(pRspUserLogin->TradingDay, pRspUserLogin->LoginTime).c_str(), pRspUserLogin->UserID, _appid.c_str(), pRspUserLogin->SessionID, pRspUserLogin->FrontID); //LOG("OnRspUserLogin\tErrorID = [%d] ErrorMsg = [%s]\n", pRspInfo->ErrorID, pRspInfo->ErrorMsg); - // Ự + // 保存会话参数 _front_id = pRspUserLogin->FrontID; _session_id = pRspUserLogin->SessionID; _order_ref = atoi(pRspUserLogin->MaxOrderRef); @@ -514,7 +514,7 @@ void ctp_trader::OnRspQryInvestorPositionDetail(CThostFtdcInvestorPositionDetail position.id = code; if(strcmp(pInvestorPositionDetail->OpenDate ,pInvestorPositionDetail->TradingDay)==0) { - // + //今仓 if (pInvestorPositionDetail->Direction == THOST_FTDC_D_Buy) { position.today_long.postion += pInvestorPositionDetail->Volume; @@ -530,7 +530,7 @@ void ctp_trader::OnRspQryInvestorPositionDetail(CThostFtdcInvestorPositionDetail } else { - // + //昨仓 if (pInvestorPositionDetail->Direction == THOST_FTDC_D_Buy) { position.yestoday_long.postion += pInvestorPositionDetail->Volume; @@ -635,7 +635,7 @@ void ctp_trader::OnRtnOrder(CThostFtdcOrderField *pOrder) } if (pOrder->OrderStatus == THOST_FTDC_OST_Canceled) { - //ⶳλ + //撤销解冻仓位 if (offset == OT_CLOSE) { thawing_deduction(code, direction, pOrder->VolumeTotal + pOrder->VolumeTraded, is_today); @@ -674,12 +674,12 @@ void ctp_trader::OnRtnOrder(CThostFtdcOrderField *pOrder) this->fire_event(ET_OrderPlace, order->second); if(offset == OT_OPEN) { - //ֶʽ + //开仓冻结资金 query_account(); } else { - //ƽֶλ + //平仓冻结仓位 frozen_deduction(code, direction, entrust.total_volume, is_today); } } @@ -703,7 +703,7 @@ void ctp_trader::OnRtnOrder(CThostFtdcOrderField *pOrder) if (pOrder->OrderStatus == THOST_FTDC_OST_PartTradedQueueing || pOrder->OrderStatus == THOST_FTDC_OST_PartTradedNotQueueing) { - // deal ¼ + //触发 deal 事件 this->fire_event(ET_OrderDeal, estid, (uint32_t)pOrder->VolumeTotal, (uint32_t)(pOrder->VolumeTraded + pOrder->VolumeTotal)); } } @@ -714,7 +714,7 @@ void ctp_trader::OnRtnTrade(CThostFtdcTradeField *pTrade) { if(pTrade&& pTrade->OffsetFlag != THOST_FTDC_OF_Open) { - //ƽּӯ + //平仓计算盈亏 query_account(); } @@ -816,12 +816,12 @@ estid_t ctp_trader::place_order(offset_type offset, direction_type direction, co uint32_t order_ref = 0, season_id = 0, front_id = 0; extract_estid(est_id, front_id, season_id, order_ref); - /// + ///报单引用 sprintf_s(req.OrderRef, "%u", order_ref); if(price != .0F) { - ///۸: ޼ + ///报单价格条件: 限价 req.OrderPriceType = THOST_FTDC_OPT_LimitPrice; } @@ -829,15 +829,15 @@ estid_t ctp_trader::place_order(offset_type offset, direction_type direction, co { req.OrderPriceType = THOST_FTDC_OPT_BestPrice; } - ///: + ///买卖方向: req.Direction = wrap_direction_offset(direction, offset); - ///Ͽƽ־: + ///组合开平标志: 开仓 req.CombOffsetFlag[0] = wrap_offset_type(code,volume,offset, direction); - ///Ͷױ־ + ///组合投机套保标志 req.CombHedgeFlag[0] = THOST_FTDC_HF_Speculation; - ///۸ + ///价格 req.LimitPrice = price; - ///: 1 + ///数量: 1 req.VolumeTotalOriginal = volume; if (flag == OF_NOR) @@ -860,13 +860,13 @@ estid_t ctp_trader::place_order(offset_type offset, direction_type direction, co } - ///: + ///触发条件: 立即 req.ContingentCondition = THOST_FTDC_CC_Immediately; - ///ǿƽԭ: ǿƽ + ///强平原因: 非强平 req.ForceCloseReason = THOST_FTDC_FCC_NotForceClose; - ///Զ־: + ///自动挂起标志: 否 req.IsAutoSuspend = 0; - ///ûǿ־: + ///用户强评标志: 否 req.UserForceClose = 0; int iResult = _td_api->ReqOrderInsert(&req, genreqid()); @@ -902,16 +902,16 @@ void ctp_trader::cancel_order(estid_t order_id) strcpy_s(req.BrokerID, _broker_id.c_str()); strcpy_s(req.InvestorID, _userid.c_str()); strcpy_s(req.UserID, _userid.c_str()); - /// + ///报单引用 sprintf_s(req.OrderRef, "%d", orderref); - /// - ///ǰñ + ///请求编号 + ///前置编号 req.FrontID = frontid; - ///Ự + ///会话编号 req.SessionID = sessionid; - ///־ + ///操作标志 req.ActionFlag = wrap_action_flag(AF_CANCEL); - ///Լ + ///合约代码 strcpy_s(req.InstrumentID, order.code.get_id()); //req.LimitPrice = change.price; diff --git a/src/trader/ctp_trader.h b/src/trader/ctp_trader.h index e7a21c47bf5d883eda44afc6eb67e018c86c1d7a..8ba70a0811d4dd6111f6574663873cdf3513b79d 100644 --- a/src/trader/ctp_trader.h +++ b/src/trader/ctp_trader.h @@ -8,15 +8,15 @@ #include #include #include - +#include /* - * + * 订单操作类型 */ typedef enum action_flag { - AF_CANCEL = '0', // - AF_MODIFY = '3', //޸ + AF_CANCEL = '0', //撤销 + AF_MODIFY = '3', //修改 } action_flag; @@ -31,7 +31,7 @@ public: bool init(const boost::property_tree::ptree& config); ////////////////////////////////////////////////////////////////////////// - //trader_apiӿ + //trader_api接口 public: @@ -46,7 +46,7 @@ public: virtual uint32_t get_trading_day()const override; ////////////////////////////////////////////////////////////////////////// - //CTP׽ӿʵ + //CTP交易接口实现 public: virtual void OnFrontConnected() override; @@ -69,10 +69,10 @@ public: virtual void OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override; virtual void OnRspQryInvestorPositionDetail(CThostFtdcInvestorPositionDetailField* pInvestorPositionDetail, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) override; - ///ѯͶֲ߳ϸӦ + ///请求查询投资者持仓明细响应 virtual void OnRspQryInvestorPositionCombineDetail(CThostFtdcInvestorPositionCombineDetailField* pInvestorPositionCombineDetail, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) override; - ///ѯɽӦ + ///请求查询成交响应 virtual void OnRspQryTrade(CThostFtdcTradeField *pTrade, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override; virtual void OnRspQryOrder(CThostFtdcOrderField *pOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override; @@ -92,9 +92,9 @@ public: private: - //֤ + //认证 bool do_auth(); - //¼ + //登录 bool do_login(); bool logout(); @@ -161,7 +161,7 @@ private: const auto& it = _position_info.find(code); if (it != _position_info.end()) { - //TODO Ȳֲ + //TODO 先不处理分仓 if (direction == DT_LONG) { if (it->second.yestoday_long.usable() >= volume) @@ -262,11 +262,11 @@ protected: std::string _usernick; time_t _last_query_time; - uint32_t _front_id; //ǰñ - uint32_t _session_id; //Ự - std::atomic _order_ref; // + uint32_t _front_id; //前置编号 + uint32_t _session_id; //会话编号 + std::atomic _order_ref; //报单引用 typedef std::function common_executer; - typedef std::queue query_queue; //ѯ + typedef std::queue query_queue; //查询队列 query_queue _query_queue; //boost::pool_allocator a ; @@ -280,7 +280,7 @@ protected: entrust_map _order_info; - //ѯ״̬ͼ Լ֤ʱʹ + //查询状态和计算 合约保证金时候使用 std::unordered_map _instrument_state; account_info _account_info ;