diff --git a/linux/include/ccapi_cpp/ccapi_http_retry.h b/linux/include/ccapi_cpp/ccapi_http_retry.h index bc8eb559c..27f3a0f35 100644 --- a/linux/include/ccapi_cpp/ccapi_http_retry.h +++ b/linux/include/ccapi_cpp/ccapi_http_retry.h @@ -1,5 +1,6 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_HTTP_RETRY_H_ #define INCLUDE_CCAPI_CPP_CCAPI_HTTP_RETRY_H_ +#include #include namespace ccapi { /** diff --git a/linux/include/ccapi_cpp/ccapi_inflate_stream.h b/linux/include/ccapi_cpp/ccapi_inflate_stream.h new file mode 100644 index 000000000..6a7156730 --- /dev/null +++ b/linux/include/ccapi_cpp/ccapi_inflate_stream.h @@ -0,0 +1,95 @@ +#ifndef INCLUDE_CCAPI_CPP_CCAPI_INFLATE_STREAM_H_ +#define INCLUDE_CCAPI_CPP_CCAPI_INFLATE_STREAM_H_ +#ifndef CCAPI_DECOMPRESS_BUFFER_SIZE +#define CCAPI_DECOMPRESS_BUFFER_SIZE 1 << 20 +#endif +#include "zlib.h" +namespace ccapi { +/** + * Due to Huobi using gzip instead of zip in data compression, we cannot use beast::zboost::system::inflate_stream. Therefore we have to create our own. + */ +class InflateStream CCAPI_FINAL { + public: + explicit InflateStream() { + this->windowBits = 15; + this->windowBitsOverride = 0; + this->istate.zalloc = Z_NULL; + this->istate.zfree = Z_NULL; + this->istate.opaque = Z_NULL; + this->istate.avail_in = 0; + this->istate.next_in = Z_NULL; + this->decompressBufferSize = CCAPI_DECOMPRESS_BUFFER_SIZE; + } + std::string toString() const { + std::string output = "InflateStream [windowBits = " + ccapi::toString(windowBits) + "]"; + return output; + } + virtual ~InflateStream() { + if (!this->initialized) { + return; + } + int ret = inflateEnd(&this->istate); + if (ret != Z_OK) { + CCAPI_LOGGER_ERROR("error cleaning up zlib decompression state"); + } + } + void setWindowBitsOverride(int windowBitsOverride) { this->windowBitsOverride = windowBitsOverride; } + boost::system::error_code init() { + int ret; + if (this->windowBitsOverride == 0) { + ret = inflateInit2(&this->istate, -1 * this->windowBits); + } else { + ret = inflateInit2(&this->istate, this->windowBitsOverride + // 31 + ); + } + if (ret != Z_OK) { + CCAPI_LOGGER_ERROR("decompress error"); + return boost::system::error_code(); + } + this->buffer.reset(new unsigned char[this->decompressBufferSize]); + this->initialized = true; + return boost::system::error_code(); + } + boost::system::error_code decompress(uint8_t const *buf, size_t len, std::string &out) { + if (!this->initialized) { + CCAPI_LOGGER_ERROR("decompress error"); + return boost::system::error_code(); + } + int ret; + this->istate.avail_in = len; + this->istate.next_in = const_cast(buf); + do { + this->istate.avail_out = this->decompressBufferSize; + this->istate.next_out = this->buffer.get(); + int ret = inflate(&this->istate, Z_SYNC_FLUSH); + if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) { + CCAPI_LOGGER_ERROR("decompress error"); + return boost::system::error_code(); + } + out.append(reinterpret_cast(this->buffer.get()), this->decompressBufferSize - this->istate.avail_out); + } while (this->istate.avail_out == 0); + return boost::system::error_code(); + } + boost::system::error_code inflate_reset() { + int ret = inflateReset(&this->istate); + if (ret != Z_OK) { + CCAPI_LOGGER_ERROR("decompress error"); + return boost::system::error_code(); + } + return boost::system::error_code(); + } +#ifndef CCAPI_EXPOSE_INTERNAL + + private: +#endif + int windowBits; + int windowBitsOverride; + bool initialized; + std::unique_ptr buffer; + z_stream istate; + size_t decompressBufferSize; +}; + +} /* namespace ccapi */ +#endif // INCLUDE_CCAPI_CPP_CCAPI_INFLATE_STREAM_H_ diff --git a/linux/include/ccapi_cpp/ccapi_macro.h b/linux/include/ccapi_cpp/ccapi_macro.h index 76a5f850b..0f1655aab 100644 --- a/linux/include/ccapi_cpp/ccapi_macro.h +++ b/linux/include/ccapi_cpp/ccapi_macro.h @@ -45,6 +45,10 @@ #endif #define CCAPI_MARKET_DEPTH_RETURN_UPDATE_DEFAULT "0" #define CCAPI_MARKET_DEPTH_RETURN_UPDATE_ENABLE "1" +#ifndef CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS +#define CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS "FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS" +#endif +#define CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS_DEFAULT "0" #ifndef CCAPI_EXCHANGE_NAME_COINBASE #define CCAPI_EXCHANGE_NAME_COINBASE "coinbase" #endif @@ -72,6 +76,9 @@ #ifndef CCAPI_EXCHANGE_NAME_BINANCE #define CCAPI_EXCHANGE_NAME_BINANCE "binance" #endif +// #ifndef CCAPI_EXCHANGE_NAME_BINANCE_MARGIN +// #define CCAPI_EXCHANGE_NAME_BINANCE_MARGIN "binance-margin" +// #endif #ifndef CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES #define CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES "binance-usds-futures" #endif @@ -87,8 +94,8 @@ #ifndef CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP #define CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP "huobi-coin-swap" #endif -#ifndef CCAPI_EXCHANGE_NAME_OKEX -#define CCAPI_EXCHANGE_NAME_OKEX "okex" +#ifndef CCAPI_EXCHANGE_NAME_OKX +#define CCAPI_EXCHANGE_NAME_OKX "okx" #endif #ifndef CCAPI_EXCHANGE_NAME_ERISX #define CCAPI_EXCHANGE_NAME_ERISX "erisx" @@ -120,15 +127,30 @@ #ifndef CCAPI_EXCHANGE_NAME_BYBIT #define CCAPI_EXCHANGE_NAME_BYBIT "bybit" #endif -// #ifndef CCAPI_EXCHANGE_NAME_BYBIT_USDT_PERPETUAL -// #define CCAPI_EXCHANGE_NAME_BYBIT_USDT_PERPETUAL "bybit-usdt-perpetual" -// #endif -// #ifndef CCAPI_EXCHANGE_NAME_BYBIT_INVERSE_PERPETUAL -// #define CCAPI_EXCHANGE_NAME_BYBIT_INVERSE_PERPETUAL "bybit-inverse-perpetual" -// #endif +#ifndef CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES +#define CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES "bybit-derivatives" +#endif #ifndef CCAPI_EXCHANGE_NAME_ASCENDEX #define CCAPI_EXCHANGE_NAME_ASCENDEX "ascendex" #endif +#ifndef CCAPI_EXCHANGE_NAME_BITGET +#define CCAPI_EXCHANGE_NAME_BITGET "bitget" +#endif +#ifndef CCAPI_EXCHANGE_NAME_BITGET_FUTURES +#define CCAPI_EXCHANGE_NAME_BITGET_FUTURES "bitget-futures" +#endif +#ifndef CCAPI_EXCHANGE_NAME_BITMART +#define CCAPI_EXCHANGE_NAME_BITMART "bitmart" +#endif +#ifndef CCAPI_EXCHANGE_NAME_MEXC +#define CCAPI_EXCHANGE_NAME_MEXC "mexc" +#endif +#ifndef CCAPI_EXCHANGE_NAME_MEXC_FUTURES +#define CCAPI_EXCHANGE_NAME_MEXC_FUTURES "mexc-futures" +#endif +#ifndef CCAPI_EXCHANGE_NAME_WHITEBIT +#define CCAPI_EXCHANGE_NAME_WHITEBIT "whitebit" +#endif #ifndef CCAPI_LAST_PRICE #define CCAPI_LAST_PRICE "LAST_PRICE" #endif @@ -201,6 +223,9 @@ #ifndef CCAPI_MARGIN_ASSET #define CCAPI_MARGIN_ASSET "MARGIN_ASSET" #endif +#ifndef CCAPI_SETTLE_ASSET +#define CCAPI_SETTLE_ASSET "SETTLE_ASSET" +#endif #ifndef CCAPI_ORDER_PRICE_INCREMENT #define CCAPI_ORDER_PRICE_INCREMENT "PRICE_INCREMENT" #endif @@ -213,6 +238,12 @@ #ifndef CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN #define CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN "PRICE_TIMES_QUANTITY_MIN" #endif +#ifndef CCAPI_CONTRACT_SIZE +#define CCAPI_CONTRACT_SIZE "CONTRACT_SIZE" +#endif +#ifndef CCAPI_CONTRACT_MULTIPLIER +#define CCAPI_CONTRACT_MULTIPLIER "CONTRACT_MULTIPLIER" +#endif #define CCAPI_WEBSOCKET_COINBASE_CHANNEL_MATCH "matches" #define CCAPI_WEBSOCKET_COINBASE_CHANNEL_LEVEL2 "level2" #define CCAPI_WEBSOCKET_GEMINI_PARAMETER_TRADES "trades" @@ -242,11 +273,14 @@ #define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO_REGEX "market\\.(.+)\\.bbo" #define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH "market.$symbol.depth.step0" #define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH_REGEX "market\\.(.+)\\.depth\\.step0" -#define CCAPI_WEBSOCKET_OKEX_CHANNEL_TRADE "trades" -#define CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH50_L2_TBT "books50-l2-tbt" -#define CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400_L2_TBT "books-l2-tbt" -#define CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5 "books5" -#define CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400 "books" +#define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE "market.$symbol.mbp.refresh.$levels" +#define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE_REGEX "market\\.(.+)\\.mbp.refresh\\.(.+)" +#define CCAPI_WEBSOCKET_OKX_CHANNEL_TRADE "trades" +#define CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH50_L2_TBT "books50-l2-tbt" +#define CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400_L2_TBT "books-l2-tbt" +#define CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5 "books5" +#define CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400 "books" +#define CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT "bbo-tbt" #define CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE "MarketDataSubscribe" #define CCAPI_WEBSOCKET_ERISX_CHANNEL_TOP_OF_BOOK_MARKET_DATA_SUBSCRIBE "TopOfBookMarketDataSubscribe" #define CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_MATCH "/market/match" @@ -274,18 +308,30 @@ #define CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_ORDER_BOOK "futures.order_book" #define CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_TRADE "trade.{instrument_name}" #define CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK "book.{instrument_name}.{depth}" -#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE "trade" -#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER "bookTicker" -#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH "depth" -// #define CCAPI_WEBSOCKET_BYBIT_USDT_PERPETUAL_CHANNEL_TRADE "trade" -// #define CCAPI_WEBSOCKET_BYBIT_USDT_PERPETUAL_CHANNEL_ORDER_BOOK_L2_25 "orderBookL2_25" -// #define CCAPI_WEBSOCKET_BYBIT_USDT_PERPETUAL_CHANNEL_ORDER_BOOK_L2_200 "orderBookL2_200" -// #define CCAPI_WEBSOCKET_BYBIT_INVERSE_PERPETUAL_CHANNEL_TRADE "trade" -// #define CCAPI_WEBSOCKET_BYBIT_INVERSE_PERPETUAL_CHANNEL_ORDER_BOOK_L2_25 "orderBookL2_25" -// #define CCAPI_WEBSOCKET_BYBIT_INVERSE_PERPETUAL_CHANNEL_ORDER_BOOK_L2_200 "orderBookL2_200" +#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE "trade.{symbol}" +#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER "bookticker.{symbol}" +#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH "orderbook.40.{symbol}" +#define CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE "publicTrade.{symbol}" +#define CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK "orderbook.{depth}.{symbol}" #define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_TRADES "trades" #define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BBO "bbo" #define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH "depth" +#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES "trade" +#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS "books" +#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1 "books1" +#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5 "books5" +#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15 "books15" +#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES "trade" +#define CCAPI_WEBSOCKET_BITMART_CHANNEL_TRADE "spot/trade" +#define CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5 "spot/depth5" +#define CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH20 "spot/depth20" +#define CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH50 "spot/depth50" +#define CCAPI_WEBSOCKET_MEXC_CHANNEL_TRADE "spot@public.deals.v3.api" +#define CCAPI_WEBSOCKET_MEXC_CHANNEL_DIFF_DEPTH "spot@public.increase.depth.v3.api" +#define CCAPI_WEBSOCKET_MEXC_FUTURES_CHANNEL_TRANSACTION "deal" +#define CCAPI_WEBSOCKET_MEXC_FUTURES_CHANNEL_DEPTH "depth" +#define CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES "trades" +#define CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH "depth" #ifndef CCAPI_CHANNEL_ID #define CCAPI_CHANNEL_ID "channelId" #endif @@ -295,6 +341,9 @@ #ifndef CCAPI_CONNECTION_ID #define CCAPI_CONNECTION_ID "CONNECTION_ID" #endif +#ifndef CCAPI_CONNECTION_URL +#define CCAPI_CONNECTION_URL "CONNECTION_URL" +#endif #ifndef CCAPI_REASON #define CCAPI_REASON "REASON" #endif @@ -354,6 +403,12 @@ #ifndef CCAPI_EM_ACCOUNT_TYPE #define CCAPI_EM_ACCOUNT_TYPE "ACCOUNT_TYPE" #endif +#ifndef CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN +#define CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN "CROSS_MARGIN" +#endif +#ifndef CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN +#define CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN "ISOLATED_MARGIN" +#endif #ifndef CCAPI_EM_ASSET #define CCAPI_EM_ASSET "ASSET" #endif @@ -363,6 +418,9 @@ #ifndef CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING #define CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING "QUANTITY_AVAILABLE_FOR_TRADING" #endif +#ifndef CCAPI_EM_QUANTITY_LIABILITY +#define CCAPI_EM_QUANTITY_LIABILITY "QUANTITY_LIABILITY" +#endif #ifndef CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL #define CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL "BASE_ASSET_QUANTITY_TOTAL" #endif @@ -375,6 +433,9 @@ #ifndef CCAPI_EM_QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING #define CCAPI_EM_QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING "QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING" #endif +#ifndef CCAPI_EM_INSTRUMENT +#define CCAPI_EM_INSTRUMENT "INSTRUMENT" +#endif #ifndef CCAPI_EM_SYMBOL #define CCAPI_EM_SYMBOL "SYMBOL" #endif @@ -390,6 +451,9 @@ #ifndef CCAPI_EM_POSITION_COST #define CCAPI_EM_POSITION_COST "COST" #endif +#ifndef CCAPI_EM_POSITION_ENTRY_PRICE +#define CCAPI_EM_POSITION_ENTRY_PRICE "ENTRY_PRICE" +#endif #ifndef CCAPI_EM_PARTY_ID #define CCAPI_EM_PARTY_ID "PARTY_ID" #endif @@ -411,6 +475,9 @@ #ifndef CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY #define CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY "CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY" #endif +#ifndef CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE +#define CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE "AVERAGE_FILLED_PRICE" +#endif #ifndef CCAPI_EM_ORDER_INSTRUMENT #define CCAPI_EM_ORDER_INSTRUMENT "INSTRUMENT" #endif @@ -519,6 +586,12 @@ #ifndef CCAPI_BINANCE_LISTEN_KEY_PATH #define CCAPI_BINANCE_LISTEN_KEY_PATH "/api/v3/userDataStream" #endif +#ifndef CCAPI_BINANCE_LISTEN_KEY_CROSS_MARGIN_PATH +#define CCAPI_BINANCE_LISTEN_KEY_CROSS_MARGIN_PATH "/sapi/v1/userDataStream" +#endif +#ifndef CCAPI_BINANCE_LISTEN_KEY_ISOLATED_MARGIN_PATH +#define CCAPI_BINANCE_LISTEN_KEY_ISOLATED_MARGIN_PATH "/sapi/v1/userDataStream/isolated" +#endif #ifndef CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE #define CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE "https://fapi.binance.com" #endif @@ -594,8 +667,8 @@ #ifndef CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH #define CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH "/swap-ex/market/history/trade" #endif -#ifndef CCAPI_OKEX_URL_REST_BASE -#define CCAPI_OKEX_URL_REST_BASE "https://www.okex.com" +#ifndef CCAPI_OKX_URL_REST_BASE +#define CCAPI_OKX_URL_REST_BASE "https://www.okx.com" #endif #ifndef CCAPI_ERISX_URL_REST_BASE #define CCAPI_ERISX_URL_REST_BASE "https://trade-api.erisx.com" @@ -627,15 +700,36 @@ #ifndef CCAPI_BYBIT_URL_REST_BASE #define CCAPI_BYBIT_URL_REST_BASE "https://api.bybit.com" #endif -// #ifndef CCAPI_BYBIT_USDT_PERPETUAL_URL_REST_BASE -// #define CCAPI_BYBIT_USDT_PERPETUAL_URL_REST_BASE "https://api.bybit.com" -// #endif -// #ifndef CCAPI_BYBIT_INVERSE_PERPETUAL_URL_REST_BASE -// #define CCAPI_BYBIT_INVERSE_PERPETUAL_URL_REST_BASE "https://api.bybit.com" -// #endif +#ifndef CCAPI_BYBIT_DERIVATIVES_URL_REST_BASE +#define CCAPI_BYBIT_DERIVATIVES_URL_REST_BASE "https://api.bybit.com" +#endif #ifndef CCAPI_ASCENDEX_URL_REST_BASE #define CCAPI_ASCENDEX_URL_REST_BASE "https://ascendex.com" #endif +#ifndef CCAPI_BITGET_URL_REST_BASE +#define CCAPI_BITGET_URL_REST_BASE "https://api.bitget.com" +#endif +#ifndef CCAPI_BITGET_FUTURES_URL_REST_BASE +#define CCAPI_BITGET_FUTURES_URL_REST_BASE "https://api.bitget.com" +#endif +#ifndef CCAPI_BITMART_URL_REST_BASE +#define CCAPI_BITMART_URL_REST_BASE "https://api-cloud.bitmart.com" +#endif +#ifndef CCAPI_MEXC_URL_REST_BASE +#define CCAPI_MEXC_URL_REST_BASE "https://api.mexc.com" +#endif +#ifndef CCAPI_MEXC_CREATE_ORDER_PATH +#define CCAPI_MEXC_CREATE_ORDER_PATH "/api/v3/order" +#endif +#ifndef CCAPI_MEXC_LISTEN_KEY_PATH +#define CCAPI_MEXC_LISTEN_KEY_PATH "/api/v3/userDataStream" +#endif +#ifndef CCAPI_MEXC_FUTURES_URL_REST_BASE +#define CCAPI_MEXC_FUTURES_URL_REST_BASE "https://contract.mexc.com" +#endif +#ifndef CCAPI_WHITEBIT_URL_REST_BASE +#define CCAPI_WHITEBIT_URL_REST_BASE "https://whitebit.com" +#endif // end: exchange REST urls // start: exchange WS urls @@ -699,14 +793,14 @@ #ifndef CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC #define CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC "matchOrders" #endif -#ifndef CCAPI_OKEX_URL_WS_BASE -#define CCAPI_OKEX_URL_WS_BASE "wss://ws.okex.com:8443" +#ifndef CCAPI_OKX_URL_WS_BASE +#define CCAPI_OKX_URL_WS_BASE "wss://ws.okx.com:8443" #endif -#ifndef CCAPI_OKEX_PUBLIC_WS_PATH -#define CCAPI_OKEX_PUBLIC_WS_PATH "/ws/v5/public" +#ifndef CCAPI_OKX_PUBLIC_WS_PATH +#define CCAPI_OKX_PUBLIC_WS_PATH "/ws/v5/public" #endif -#ifndef CCAPI_OKEX_PRIVATE_WS_PATH -#define CCAPI_OKEX_PRIVATE_WS_PATH "/ws/v5/private" +#ifndef CCAPI_OKX_PRIVATE_WS_PATH +#define CCAPI_OKX_PRIVATE_WS_PATH "/ws/v5/private" #endif #ifndef CCAPI_ERISX_URL_WS_BASE #define CCAPI_ERISX_URL_WS_BASE "wss://publicmd-api.erisx.com" @@ -732,15 +826,30 @@ #ifndef CCAPI_BYBIT_URL_WS_BASE #define CCAPI_BYBIT_URL_WS_BASE "wss://stream.bybit.com" #endif -// #ifndef CCAPI_BYBIT_USDT_PERPETUAL_URL_WS_BASE -// #define CCAPI_BYBIT_USDT_PERPETUAL_URL_WS_BASE "https://api.bybit.com" -// #endif -// #ifndef CCAPI_BYBIT_INVERSE_PERPETUAL_URL_WS_BASE -// #define CCAPI_BYBIT_INVERSE_PERPETUAL_URL_WS_BASE "https://api.bybit.com" -// #endif +#ifndef CCAPI_BYBIT_DERIVATIVES_URL_WS_BASE +#define CCAPI_BYBIT_DERIVATIVES_URL_WS_BASE "wss://stream.bybit.com" +#endif #ifndef CCAPI_ASCENDEX_URL_WS_BASE #define CCAPI_ASCENDEX_URL_WS_BASE "wss://ascendex.com" #endif +#ifndef CCAPI_BITGET_URL_WS_BASE +#define CCAPI_BITGET_URL_WS_BASE "wss://ws.bitget.com" +#endif +#ifndef CCAPI_BITGET_FUTURES_URL_WS_BASE +#define CCAPI_BITGET_FUTURES_URL_WS_BASE "wss://ws.bitget.com" +#endif +#ifndef CCAPI_BITMART_URL_WS_BASE +#define CCAPI_BITMART_URL_WS_BASE "wss://ws-manager-compress.bitmart.com" +#endif +#ifndef CCAPI_MEXC_URL_WS_BASE +#define CCAPI_MEXC_URL_WS_BASE "wss://wbs.mexc.com" +#endif +#ifndef CCAPI_MEXC_FUTURES_URL_WS_BASE +#define CCAPI_MEXC_FUTURES_URL_WS_BASE "wss://contract.mexc.com" +#endif +#ifndef CCAPI_WHITEBIT_URL_WS_BASE +#define CCAPI_WHITEBIT_URL_WS_BASE "wss://api.whitebit.com" +#endif // end: exchange WS urls // start: exchange FIX urls @@ -828,6 +937,12 @@ #ifndef CCAPI_BINANCE_API_SECRET #define CCAPI_BINANCE_API_SECRET "BINANCE_API_SECRET" #endif +// #ifndef CCAPI_BINANCE_MARGIN_API_KEY +// #define CCAPI_BINANCE_MARGIN_API_KEY "BINANCE_MARGIN_API_KEY" +// #endif +// #ifndef CCAPI_BINANCE_MARGIN_API_SECRET +// #define CCAPI_BINANCE_MARGIN_API_SECRET "BINANCE_MARGIN_API_SECRET" +// #endif #ifndef CCAPI_BINANCE_USDS_FUTURES_API_KEY #define CCAPI_BINANCE_USDS_FUTURES_API_KEY "BINANCE_USDS_FUTURES_API_KEY" #endif @@ -858,17 +973,17 @@ #ifndef CCAPI_HUOBI_COIN_SWAP_API_SECRET #define CCAPI_HUOBI_COIN_SWAP_API_SECRET "HUOBI_COIN_SWAP_API_SECRET" #endif -#ifndef CCAPI_OKEX_API_KEY -#define CCAPI_OKEX_API_KEY "OKEX_API_KEY" +#ifndef CCAPI_OKX_API_KEY +#define CCAPI_OKX_API_KEY "OKX_API_KEY" #endif -#ifndef CCAPI_OKEX_API_SECRET -#define CCAPI_OKEX_API_SECRET "OKEX_API_SECRET" +#ifndef CCAPI_OKX_API_SECRET +#define CCAPI_OKX_API_SECRET "OKX_API_SECRET" #endif -#ifndef CCAPI_OKEX_API_PASSPHRASE -#define CCAPI_OKEX_API_PASSPHRASE "OKEX_API_PASSPHRASE" +#ifndef CCAPI_OKX_API_PASSPHRASE +#define CCAPI_OKX_API_PASSPHRASE "OKX_API_PASSPHRASE" #endif -#ifndef CCAPI_OKEX_API_X_SIMULATED_TRADING -#define CCAPI_OKEX_API_X_SIMULATED_TRADING "OKEX_API_X_SIMULATED_TRADING" +#ifndef CCAPI_OKX_API_X_SIMULATED_TRADING +#define CCAPI_OKX_API_X_SIMULATED_TRADING "OKX_API_X_SIMULATED_TRADING" #endif #ifndef CCAPI_ERISX_API_KEY #define CCAPI_ERISX_API_KEY "ERISX_API_KEY" @@ -897,9 +1012,6 @@ #ifndef CCAPI_KUCOIN_FUTURES_API_PASSPHRASE #define CCAPI_KUCOIN_FUTURES_API_PASSPHRASE "KUCOIN_FUTURES_API_PASSPHRASE" #endif -#ifndef CCAPI_KUCOIN_FUTURES_API_KEY_VERSION -#define CCAPI_KUCOIN_FUTURES_API_KEY_VERSION "KUCOIN_FUTURES_API_KEY_VERSION" -#endif #ifndef CCAPI_FTX_API_KEY #define CCAPI_FTX_API_KEY "FTX_API_KEY" #endif @@ -948,18 +1060,12 @@ #ifndef CCAPI_BYBIT_API_SECRET #define CCAPI_BYBIT_API_SECRET "BYBIT_API_SECRET" #endif -// #ifndef CCAPI_BYBIT_USDT_PERPETUAL_API_KEY -// #define CCAPI_BYBIT_USDT_PERPETUAL_API_KEY "BYBIT_USDT_PERPETUAL_API_KEY" -// #endif -// #ifndef CCAPI_BYBIT_USDT_PERPETUAL_API_SECRET -// #define CCAPI_BYBIT_USDT_PERPETUAL_API_SECRET "BYBIT_USDT_PERPETUAL_API_SECRET" -// #endif -// #ifndef CCAPI_BYBIT_INVERSE_PERPETUAL_API_KEY -// #define CCAPI_BYBIT_INVERSE_PERPETUAL_API_KEY "BYBIT_INVERSE_PERPETUAL_API_KEY" -// #endif -// #ifndef CCAPI_BYBIT_INVERSE_PERPETUAL_API_SECRET -// #define CCAPI_BYBIT_INVERSE_PERPETUAL_API_SECRET "BYBIT_INVERSE_PERPETUAL_API_SECRET" -// #endif +#ifndef CCAPI_BYBIT_DERIVATIVES_API_KEY +#define CCAPI_BYBIT_DERIVATIVES_API_KEY "BYBIT_DERIVATIVES_API_KEY" +#endif +#ifndef CCAPI_BYBIT_DERIVATIVES_API_SECRET +#define CCAPI_BYBIT_DERIVATIVES_API_SECRET "BYBIT_DERIVATIVES_API_SECRET" +#endif #ifndef CCAPI_ASCENDEX_API_KEY #define CCAPI_ASCENDEX_API_KEY "ASCENDEX_API_KEY" #endif @@ -969,6 +1075,45 @@ #ifndef CCAPI_ASCENDEX_API_ACCOUNT_GROUP #define CCAPI_ASCENDEX_API_ACCOUNT_GROUP "ASCENDEX_API_ACCOUNT_GROUP" #endif +#ifndef CCAPI_BITGET_API_KEY +#define CCAPI_BITGET_API_KEY "BITGET_API_KEY" +#endif +#ifndef CCAPI_BITGET_API_SECRET +#define CCAPI_BITGET_API_SECRET "BITGET_API_SECRET" +#endif +#ifndef CCAPI_BITGET_API_PASSPHRASE +#define CCAPI_BITGET_API_PASSPHRASE "BITGET_API_PASSPHRASE" +#endif +#ifndef CCAPI_BITGET_FUTURES_API_KEY +#define CCAPI_BITGET_FUTURES_API_KEY "BITGET_FUTURES_API_KEY" +#endif +#ifndef CCAPI_BITGET_FUTURES_API_SECRET +#define CCAPI_BITGET_FUTURES_API_SECRET "BITGET_FUTURES_API_SECRET" +#endif +#ifndef CCAPI_BITGET_FUTURES_API_PASSPHRASE +#define CCAPI_BITGET_FUTURES_API_PASSPHRASE "BITGET_FUTURES_API_PASSPHRASE" +#endif +#ifndef CCAPI_BITMART_API_KEY +#define CCAPI_BITMART_API_KEY "BITMART_API_KEY" +#endif +#ifndef CCAPI_BITMART_API_SECRET +#define CCAPI_BITMART_API_SECRET "BITMART_API_SECRET" +#endif +#ifndef CCAPI_BITMART_API_MEMO +#define CCAPI_BITMART_API_MEMO "BITMART_API_MEMO" +#endif +#ifndef CCAPI_MEXC_API_KEY +#define CCAPI_MEXC_API_KEY "MEXC_API_KEY" +#endif +#ifndef CCAPI_MEXC_API_SECRET +#define CCAPI_MEXC_API_SECRET "MEXC_API_SECRET" +#endif +#ifndef CCAPI_MEXC_FUTURES_API_KEY +#define CCAPI_MEXC_FUTURES_API_KEY "MEXC_FUTURES_API_KEY" +#endif +#ifndef CCAPI_MEXC_FUTURES_API_SECRET +#define CCAPI_MEXC_FUTURES_API_SECRET "MEXC_FUTURES_API_SECRET" +#endif // end: exchange API credentials #define CCAPI_HTTP_PORT_DEFAULT "80" @@ -998,4 +1143,29 @@ #ifndef CCAPI_FIX_PROTOCOL_VERSION_DERIBIT #define CCAPI_FIX_PROTOCOL_VERSION_DERIBIT "FIX.4.4" #endif +#ifndef CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS +#define CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS 5000 +#endif + +#ifndef CCAPI_OKX_API_BROKER_CODE +#define CCAPI_OKX_API_BROKER_CODE "9cbc6a17a1fcBCDE" +#endif +#ifndef CCAPI_KUCOIN_API_PARTNER_PLATFORM_ID +#define CCAPI_KUCOIN_API_PARTNER_PLATFORM_ID "CCAPI" +#endif +#ifndef CCAPI_KUCOIN_API_PARTNER_PRIVATE_KEY +#define CCAPI_KUCOIN_API_PARTNER_PRIVATE_KEY "acd80910-9304-4625-93c0-dabe644d2ae3" +#endif +#ifndef CCAPI_BITGET_API_CHANNEL_API_CODE +#define CCAPI_BITGET_API_CHANNEL_API_CODE "95mpa" +#endif +#ifndef CCAPI_GATEIO_API_CHANNEL_ID +#define CCAPI_GATEIO_API_CHANNEL_ID "cryptochassis" +#endif +#ifndef CCAPI_MEXC_API_SOURCE +#define CCAPI_MEXC_API_SOURCE "CHAS" +#endif +#ifndef CCAPI_BYBIT_API_BROKER_ID +#define CCAPI_BYBIT_API_BROKER_ID "Vs000261" +#endif #endif // INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_ diff --git a/linux/include/ccapi_cpp/ccapi_message.h b/linux/include/ccapi_cpp/ccapi_message.h index cd2f21bfa..da6270d5c 100644 --- a/linux/include/ccapi_cpp/ccapi_message.h +++ b/linux/include/ccapi_cpp/ccapi_message.h @@ -16,8 +16,8 @@ class Message CCAPI_FINAL { public: enum class RecapType { UNKNOWN, - NONE, // normal data tick; not a recap - SOLICITED, // generated on request by subscriber + NONE, // Normal data tick, not a recap. For market depth, it represents the new snapshot. For public trade, it represents the new trades. + SOLICITED, // A recap. For market depth, it represents the initial snapshot. For public trade, it represents the recent trades. }; static std::string recapTypeToString(RecapType recapType) { std::string output; @@ -185,7 +185,8 @@ class Message CCAPI_FINAL { std::string toString() const { std::string output = "Message [type = " + typeToString(type) + ", recapType = " + recapTypeToString(recapType) + ", time = " + UtilTime::getISOTimestamp(time) + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + - ", elementList = " + ccapi::firstNToString(elementList, 10) + ", correlationIdList = " + ccapi::toString(correlationIdList) + "]"; + ", elementList = " + ccapi::firstNToString(elementList, 10) + ", correlationIdList = " + ccapi::toString(correlationIdList) + + ", secondaryCorrelationIdMap = " + ccapi::toString(secondaryCorrelationIdMap) + "]"; return output; } std::string toStringPretty(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const { @@ -195,14 +196,19 @@ class Message CCAPI_FINAL { "recapType = " + recapTypeToString(recapType) + ",\n" + ss + "time = " + UtilTime::getISOTimestamp(time) + ",\n" + ss + "timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ",\n" + ss + "elementList = " + ccapi::firstNToStringPretty(elementList, 10, space, space + leftToIndent, false) + ",\n" + ss + - "correlationIdList = " + ccapi::toString(correlationIdList) + "\n" + sl + "]"; + "correlationIdList = " + ccapi::toString(correlationIdList) + ",\n" + ss + + "secondaryCorrelationIdMap = " + ccapi::toString(secondaryCorrelationIdMap) + "\n" + sl + "]"; return output; } const std::vector& getElementList() const { return elementList; } void setElementList(const std::vector& elementList) { this->elementList = elementList; } void setElementList(std::vector& elementList) { this->elementList = std::move(elementList); } const std::vector& getCorrelationIdList() const { return correlationIdList; } + const std::map& getSecondaryCorrelationIdMap() const { return secondaryCorrelationIdMap; } void setCorrelationIdList(const std::vector& correlationIdList) { this->correlationIdList = correlationIdList; } + void setSecondaryCorrelationIdMap(const std::map& secondaryCorrelationIdMap) { + this->secondaryCorrelationIdMap = secondaryCorrelationIdMap; + } // 'getTime' only works in C++. For other languages, please use 'getTimeISO'. TimePoint getTime() const { return time; } std::string getTimeISO() const { return UtilTime::getISOTimestamp(time); } @@ -227,6 +233,7 @@ class Message CCAPI_FINAL { TimePoint timeReceived{std::chrono::seconds{0}}; std::vector elementList; std::vector correlationIdList; + std::map secondaryCorrelationIdMap; Type type{Type::UNKNOWN}; RecapType recapType{RecapType::UNKNOWN}; }; diff --git a/linux/include/ccapi_cpp/ccapi_request.h b/linux/include/ccapi_cpp/ccapi_request.h index 9f7118d5f..19905e96d 100644 --- a/linux/include/ccapi_cpp/ccapi_request.h +++ b/linux/include/ccapi_cpp/ccapi_request.h @@ -123,14 +123,17 @@ class Request CCAPI_FINAL { shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH))); } std::string output = - "Request [exchange = " + exchange + ", instrument = " + instrument + ", serviceName = " + serviceName + ", correlationId = " + correlationId + + "Request [exchange = " + exchange + ", marginType = " + marginType + ", instrument = " + instrument + ", serviceName = " + serviceName + + ", correlationId = " + correlationId + ", secondaryCorrelationId = " + secondaryCorrelationId + (this->serviceName == CCAPI_FIX ? ", paramListFix = " + ccapi::toString(paramListFix) : ", paramList = " + ccapi::toString(paramList)) + ", credential = " + ccapi::toString(shortCredential) + ", operation = " + operationToString(operation) + ", timeSent = " + UtilTime::getISOTimestamp(timeSent) + "]"; return output; } const std::string& getCorrelationId() const { return correlationId; } + const std::string& getSecondaryCorrelationId() const { return secondaryCorrelationId; } const std::string& getExchange() const { return exchange; } + const std::string& getMarginType() const { return marginType; } const std::string& getInstrument() const { return instrument; } const std::map& getCredential() const { return credential; } const std::string& getServiceName() const { return serviceName; } @@ -160,14 +163,18 @@ class Request CCAPI_FINAL { void setIndex(int index) { this->index = index; } void setCredential(const std::map& credential) { this->credential = credential; } void setCorrelationId(const std::string& correlationId) { this->correlationId = correlationId; } + void setSecondaryCorrelationId(const std::string& secondaryCorrelationId) { this->secondaryCorrelationId = secondaryCorrelationId; } + void setMarginType(const std::string& marginType) { this->marginType = marginType; } #ifndef CCAPI_EXPOSE_INTERNAL private: #endif std::string exchange; + std::string marginType; std::string instrument; std::string serviceName; std::string correlationId; + std::string secondaryCorrelationId; std::vector > paramList; std::map credential; Operation operation; diff --git a/linux/include/ccapi_cpp/ccapi_session.h b/linux/include/ccapi_cpp/ccapi_session.h index 43e31989e..f280f7486 100644 --- a/linux/include/ccapi_cpp/ccapi_session.h +++ b/linux/include/ccapi_cpp/ccapi_session.h @@ -46,8 +46,8 @@ #ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP #include "ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h" #endif -#ifdef CCAPI_ENABLE_EXCHANGE_OKEX -#include "ccapi_cpp/service/ccapi_market_data_service_okex.h" +#ifdef CCAPI_ENABLE_EXCHANGE_OKX +#include "ccapi_cpp/service/ccapi_market_data_service_okx.h" #endif #ifdef CCAPI_ENABLE_EXCHANGE_ERISX #include "ccapi_cpp/service/ccapi_market_data_service_erisx.h" @@ -79,9 +79,30 @@ #ifdef CCAPI_ENABLE_EXCHANGE_BYBIT #include "ccapi_cpp/service/ccapi_market_data_service_bybit.h" #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES +#include "ccapi_cpp/service/ccapi_market_data_service_bybit_derivatives.h" +#endif #ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX #include "ccapi_cpp/service/ccapi_market_data_service_ascendex.h" #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET +#include "ccapi_cpp/service/ccapi_market_data_service_bitget.h" +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES +#include "ccapi_cpp/service/ccapi_market_data_service_bitget_futures.h" +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITMART +#include "ccapi_cpp/service/ccapi_market_data_service_bitmart.h" +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC +#include "ccapi_cpp/service/ccapi_market_data_service_mexc.h" +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES +#include "ccapi_cpp/service/ccapi_market_data_service_mexc_futures.h" +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_WHITEBIT +#include "ccapi_cpp/service/ccapi_market_data_service_whitebit.h" +#endif #endif // end: enable exchanges for market data @@ -114,6 +135,9 @@ #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE #include "ccapi_cpp/service/ccapi_execution_management_service_binance.h" #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_MARGIN +// #include "ccapi_cpp/service/ccapi_execution_management_service_binance_margin.h" +// #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES #include "ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h" #endif @@ -129,8 +153,8 @@ #ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP #include "ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h" #endif -#ifdef CCAPI_ENABLE_EXCHANGE_OKEX -#include "ccapi_cpp/service/ccapi_execution_management_service_okex.h" +#ifdef CCAPI_ENABLE_EXCHANGE_OKX +#include "ccapi_cpp/service/ccapi_execution_management_service_okx.h" #endif #ifdef CCAPI_ENABLE_EXCHANGE_ERISX #include "ccapi_cpp/service/ccapi_execution_management_service_erisx.h" @@ -162,9 +186,30 @@ #ifdef CCAPI_ENABLE_EXCHANGE_BYBIT #include "ccapi_cpp/service/ccapi_execution_management_service_bybit.h" #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES +#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_derivatives.h" +#endif #ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX #include "ccapi_cpp/service/ccapi_execution_management_service_ascendex.h" #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET +#include "ccapi_cpp/service/ccapi_execution_management_service_bitget.h" +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES +#include "ccapi_cpp/service/ccapi_execution_management_service_bitget_futures.h" +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITMART +#include "ccapi_cpp/service/ccapi_execution_management_service_bitmart.h" +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC +#include "ccapi_cpp/service/ccapi_execution_management_service_mexc.h" +#endif +// #ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES +// #include "ccapi_cpp/service/ccapi_execution_management_service_mexc_futures.h" +// #endif +#ifdef CCAPI_ENABLE_EXCHANGE_WHITEBIT +#include "ccapi_cpp/service/ccapi_execution_management_service_whitebit.h" +#endif #endif // end: enable exchanges for execution management @@ -218,10 +263,13 @@ class Session { : sessionOptions(sessionOptions), sessionConfigs(sessionConfigs), eventHandler(eventHandler), +#ifndef CCAPI_USE_SINGLE_THREAD eventDispatcher(eventDispatcher), +#endif eventQueue(sessionOptions.maxEventQueueSize), serviceContextPtr(new ServiceContext()) { CCAPI_LOGGER_FUNCTION_ENTER; +#ifndef CCAPI_USE_SINGLE_THREAD if (this->eventHandler) { if (!this->eventDispatcher) { this->eventDispatcher = new EventDispatcher(); @@ -232,14 +280,17 @@ class Session { throw std::runtime_error("undefined behavior"); } } +#endif this->start(); CCAPI_LOGGER_FUNCTION_EXIT; } virtual ~Session() { CCAPI_LOGGER_FUNCTION_ENTER; +#ifndef CCAPI_USE_SINGLE_THREAD if (this->useInternalEventDispatcher) { delete this->eventDispatcher; } +#endif CCAPI_LOGGER_FUNCTION_EXIT; } virtual void start() { @@ -304,9 +355,9 @@ class Session { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif -#ifdef CCAPI_ENABLE_EXCHANGE_OKEX - this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_OKEX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#ifdef CCAPI_ENABLE_EXCHANGE_OKX + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_OKX] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_ERISX this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_ERISX] = @@ -348,10 +399,38 @@ class Session { this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BYBIT] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif #ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_ASCENDEX] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITGET] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITGET_FUTURES] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITMART + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITMART] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_MEXC] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_MEXC_FUTURES] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_WHITEBIT + this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_WHITEBIT] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif #endif #ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT #ifdef CCAPI_ENABLE_EXCHANGE_COINBASE @@ -378,7 +457,6 @@ class Session { this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITFINEX] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif - #ifdef CCAPI_ENABLE_EXCHANGE_BITMEX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITMEX] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); @@ -391,6 +469,10 @@ class Session { this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_MARGIN +// this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_MARGIN] = +// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// #endif #ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); @@ -411,9 +493,9 @@ class Session { this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif -#ifdef CCAPI_ENABLE_EXCHANGE_OKEX - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_OKEX] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#ifdef CCAPI_ENABLE_EXCHANGE_OKX + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_OKX] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_ERISX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_ERISX] = @@ -452,14 +534,43 @@ class Session { std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif #ifdef CCAPI_ENABLE_EXCHANGE_BYBIT - this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_CRYPTOCOM] = + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BYBIT] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif #ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_ASCENDEX] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITGET] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITGET_FUTURES] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_BITMART + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITMART] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC + this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_MEXC] = + std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +#endif +// #ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES +// this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_MEXC_FUTURES] = +// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// #endif +// #ifdef CCAPI_ENABLE_EXCHANGE_WHITEBIT +// this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_WHITEBIT] = +// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// #endif +#endif + #ifdef CCAPI_ENABLE_SERVICE_FIX #ifdef CCAPI_ENABLE_EXCHANGE_COINBASE this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_COINBASE] = @@ -492,9 +603,11 @@ class Session { CCAPI_LOGGER_FUNCTION_EXIT; } virtual void stop() { +#ifndef CCAPI_USE_SINGLE_THREAD if (this->useInternalEventDispatcher) { this->eventDispatcher->stop(); } +#endif for (const auto& x : this->serviceByServiceNameExchangeMap) { for (const auto& y : x.second) { y.second->stop(); @@ -560,11 +673,23 @@ class Session { "unsupported exchange fields: " + toString(unsupportedExchangeFieldSet)); return; } + for (const auto& subscription : subscriptionList) { + auto exchange = subscription.getExchange(); + if (exchange == CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES) { + const auto& instrumentType = subscription.getInstrumentType(); + std::vector instrumentTypeList = {"usdt-contract", "usdc-contract", "usdc-options"}; + if (std::find(instrumentTypeList.begin(), instrumentTypeList.end(), instrumentType) == instrumentTypeList.end()) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, + "unsupported exchange instrument types: " + toString(instrumentType) + ". Allowed values: " + toString(instrumentTypeList) + "."); + return; + } + } + } CCAPI_LOGGER_TRACE("subscriptionListByExchangeMap = " + toString(subscriptionListByExchangeMap)); for (auto& subscriptionListByExchange : subscriptionListByExchangeMap) { auto exchange = subscriptionListByExchange.first; auto subscriptionList = subscriptionListByExchange.second; - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "please enable exchange: " + exchange); return; @@ -581,7 +706,7 @@ class Session { for (auto& subscriptionListByExchange : subscriptionListByExchangeMap) { auto exchange = subscriptionListByExchange.first; auto subscriptionList = subscriptionListByExchange.second; - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "please enable exchange: " + exchange); return; @@ -600,7 +725,7 @@ class Session { return; } auto exchange = subscription.getExchange(); - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable exchange: " + exchange); return; @@ -623,14 +748,10 @@ class Session { #ifdef CCAPI_USE_SINGLE_THREAD bool shouldContinue = true; try { - shouldContinue = this->eventHandler->processEvent(event, this); + this->eventHandler->processEvent(event, this); } catch (const std::runtime_error& e) { CCAPI_LOGGER_ERROR(e.what()); } - if (!shouldContinue) { - CCAPI_LOGGER_DEBUG("about to pause the event dispatcher"); - this->eventDispatcher->pause(); - } #else this->eventDispatcher->dispatch([that = this, event = std::move(event)] { bool shouldContinue = true; @@ -660,7 +781,7 @@ class Session { this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable service: " + serviceName + ", and the exchanges that you want"); return; } - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); auto exchange = request.getExchange(); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable exchange: " + exchange); @@ -684,7 +805,7 @@ class Session { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable service: " + serviceName + ", and the exchanges that you want"); return; } - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); auto exchange = request.getExchange(); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable exchange: " + exchange); @@ -720,7 +841,7 @@ class Session { "please enable service: " + serviceName + ", and the exchanges that you want", eventQueuePtr); return; } - std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); + std::map >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName); auto exchange = request.getExchange(); if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable exchange: " + exchange, eventQueuePtr); @@ -767,10 +888,17 @@ class Session { #ifndef SWIG virtual void setTimer(const std::string& id, long delayMilliSeconds, std::function errorHandler, std::function successHandler) { - wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [this, id, delayMilliSeconds, errorHandler, successHandler]() { + boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, id, delayMilliSeconds, errorHandler, successHandler]() { std::shared_ptr timerPtr(new steady_timer(*this->serviceContextPtr->ioContextPtr, boost::asio::chrono::milliseconds(delayMilliSeconds))); timerPtr->async_wait([this, id, errorHandler, successHandler](const boost::system::error_code& ec) { if (this->eventHandler) { +#ifdef CCAPI_USE_SINGLE_THREAD + if (ec) { + errorHandler(ec); + } else { + successHandler(); + } +#else this->eventDispatcher->dispatch([ec, errorHandler, successHandler] { if (ec) { errorHandler(ec); @@ -778,6 +906,7 @@ class Session { successHandler(); } }); +#endif } this->delayTimerByIdMap.erase(id); }); @@ -785,13 +914,24 @@ class Session { }); } virtual void cancelTimer(const std::string& id) { - wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [this, id]() { + boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, id]() { if (this->delayTimerByIdMap.find(id) != this->delayTimerByIdMap.end()) { this->delayTimerByIdMap[id]->cancel(); this->delayTimerByIdMap.erase(id); } }); } + void purgeHttpConnectionPool(const std::string& serviceName = "", const std::string& exchangeName = "") { + for (const auto& x : this->serviceByServiceNameExchangeMap) { + if (serviceName.empty() || serviceName == x.first) { + for (const auto& y : x.second) { + if (exchangeName.empty() || exchangeName == y.first) { + y.second->purgeHttpConnectionPool(); + } + } + } + } + } #endif #ifndef CCAPI_EXPOSE_INTERNAL @@ -800,10 +940,12 @@ class Session { SessionOptions sessionOptions; SessionConfigs sessionConfigs; EventHandler* eventHandler; +#ifndef CCAPI_USE_SINGLE_THREAD EventDispatcher* eventDispatcher; bool useInternalEventDispatcher{}; - wspp::lib::shared_ptr serviceContextPtr; - std::map > > serviceByServiceNameExchangeMap; +#endif + std::shared_ptr serviceContextPtr; + std::map > > serviceByServiceNameExchangeMap; std::thread t; Queue eventQueue; std::function* eventQueue)> internalEventHandler; diff --git a/linux/include/ccapi_cpp/ccapi_session_configs.h b/linux/include/ccapi_cpp/ccapi_session_configs.h index 97f116e88..dc77aa6b5 100644 --- a/linux/include/ccapi_cpp/ccapi_session_configs.h +++ b/linux/include/ccapi_cpp/ccapi_session_configs.h @@ -27,6 +27,9 @@ class SessionConfigs CCAPI_FINAL { const std::map& getUrlFixBase() const { return urlFixBase; } const std::map& getInitialSequenceByExchangeMap() const { return initialSequenceByExchangeMap; } const std::map& getCredential() const { return credential; } + void setUrlWebsocketBase(const std::map& urlWebsocketBase) { this->urlWebsocketBase = urlWebsocketBase; } + void setUrlRestBase(const std::map& urlRestBase) { this->urlRestBase = urlRestBase; } + void setUrlFixBase(const std::map& urlFixBase) { this->urlFixBase = urlFixBase; } void setCredential(const std::map& credential) { this->credential = credential; } #ifndef CCAPI_EXPOSE_INTERNAL @@ -91,9 +94,9 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_TRADE, CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL}, {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH}, }; - std::map fieldWebsocketChannelMapOkex = { - {CCAPI_TRADE, CCAPI_WEBSOCKET_OKEX_CHANNEL_TRADE}, - {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400}, + std::map fieldWebsocketChannelMapOkx = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_OKX_CHANNEL_TRADE}, + {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400}, }; std::map fieldWebsocketChannelMapErisx = { {CCAPI_TRADE, CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE}, @@ -135,10 +138,38 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_TRADE, CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE}, {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH}, }; + std::map fieldWebsocketChannelMapBybitDerivatives = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE}, + {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK}, + }; std::map fieldWebsocketChannelMapAscendex = { {CCAPI_TRADE, CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_TRADES}, {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH}, }; + std::map fieldWebsocketChannelMapBitget = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES}, + {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS}, + }; + std::map fieldWebsocketChannelMapBitgetFutures = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES}, + {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS}, + }; + std::map fieldWebsocketChannelMapBitmart = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_BITMART_CHANNEL_TRADE}, + {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5}, + }; + std::map fieldWebsocketChannelMapMexc = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_MEXC_CHANNEL_TRADE}, + {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_MEXC_CHANNEL_DIFF_DEPTH}, + }; + std::map fieldWebsocketChannelMapMexcFutures = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_MEXC_FUTURES_CHANNEL_TRANSACTION}, + {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_MEXC_FUTURES_CHANNEL_DEPTH}, + }; + std::map fieldWebsocketChannelMapWhitebit = { + {CCAPI_TRADE, CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES}, + {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH}, + }; for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapCoinbase) { this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_COINBASE].push_back(fieldWebsocketChannel.first); } @@ -181,8 +212,8 @@ class SessionConfigs CCAPI_FINAL { for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapHuobiCoinSwap) { this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP].push_back(fieldWebsocketChannel.first); } - for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapOkex) { - this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_OKEX].push_back(fieldWebsocketChannel.first); + for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapOkx) { + this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_OKX].push_back(fieldWebsocketChannel.first); } for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapErisx) { this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_ERISX].push_back(fieldWebsocketChannel.first); @@ -214,9 +245,30 @@ class SessionConfigs CCAPI_FINAL { for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBybit) { this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BYBIT].push_back(fieldWebsocketChannel.first); } + for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBybitDerivatives) { + this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES].push_back(fieldWebsocketChannel.first); + } for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapAscendex) { this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_ASCENDEX].push_back(fieldWebsocketChannel.first); } + for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBitget) { + this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BITGET].push_back(fieldWebsocketChannel.first); + } + for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBitgetFutures) { + this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BITGET_FUTURES].push_back(fieldWebsocketChannel.first); + } + for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBitmart) { + this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BITMART].push_back(fieldWebsocketChannel.first); + } + for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapMexc) { + this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_MEXC].push_back(fieldWebsocketChannel.first); + } + for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapMexcFutures) { + this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_MEXC_FUTURES].push_back(fieldWebsocketChannel.first); + } + for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapWhitebit) { + this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_WHITEBIT].push_back(fieldWebsocketChannel.first); + } for (auto& x : this->exchangeFieldMap) { x.second.push_back(CCAPI_GENERIC_PUBLIC_SUBSCRIPTION); } @@ -236,7 +288,7 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_EXCHANGE_NAME_HUOBI, fieldWebsocketChannelMapHuobi}, {CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP, fieldWebsocketChannelMapHuobiUsdtSwap}, {CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP, fieldWebsocketChannelMapHuobiCoinSwap}, - {CCAPI_EXCHANGE_NAME_OKEX, fieldWebsocketChannelMapOkex}, + {CCAPI_EXCHANGE_NAME_OKX, fieldWebsocketChannelMapOkx}, {CCAPI_EXCHANGE_NAME_ERISX, fieldWebsocketChannelMapErisx}, {CCAPI_EXCHANGE_NAME_KUCOIN, fieldWebsocketChannelMapKucoin}, {CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES, fieldWebsocketChannelMapKucoinFutures}, @@ -247,7 +299,14 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, fieldWebsocketChannelMapGateioPerpetualFutures}, {CCAPI_EXCHANGE_NAME_CRYPTOCOM, fieldWebsocketChannelMapCryptocom}, {CCAPI_EXCHANGE_NAME_BYBIT, fieldWebsocketChannelMapBybit}, + {CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES, fieldWebsocketChannelMapBybitDerivatives}, {CCAPI_EXCHANGE_NAME_ASCENDEX, fieldWebsocketChannelMapAscendex}, + {CCAPI_EXCHANGE_NAME_BITGET, fieldWebsocketChannelMapBitget}, + {CCAPI_EXCHANGE_NAME_BITGET_FUTURES, fieldWebsocketChannelMapBitgetFutures}, + {CCAPI_EXCHANGE_NAME_BITMART, fieldWebsocketChannelMapBitmart}, + {CCAPI_EXCHANGE_NAME_MEXC, fieldWebsocketChannelMapMexc}, + {CCAPI_EXCHANGE_NAME_MEXC_FUTURES, fieldWebsocketChannelMapMexcFutures}, + {CCAPI_EXCHANGE_NAME_WHITEBIT, fieldWebsocketChannelMapWhitebit}, }; this->urlWebsocketBase = { {CCAPI_EXCHANGE_NAME_COINBASE, CCAPI_COINBASE_URL_WS_BASE}, @@ -260,12 +319,13 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_EXCHANGE_NAME_BITMEX, CCAPI_BITMEX_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_BINANCE_US, CCAPI_BINANCE_US_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_WS_BASE}, + // {CCAPI_EXCHANGE_NAME_BINANCE_MARGIN, CCAPI_BINANCE_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES, CCAPI_BINANCE_USDS_FUTURES_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES, CCAPI_BINANCE_COIN_FUTURES_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_HUOBI, CCAPI_HUOBI_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP, CCAPI_HUOBI_USDT_SWAP_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP, CCAPI_HUOBI_COIN_SWAP_URL_WS_BASE}, - {CCAPI_EXCHANGE_NAME_OKEX, CCAPI_OKEX_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_OKX, CCAPI_OKX_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_ERISX, CCAPI_ERISX_URL_WS_BASE}, // Kucoin has dynamic websocket url. Here it is only a placeholder for subscription grouping purposes. {CCAPI_EXCHANGE_NAME_KUCOIN, "CCAPI_EXCHANGE_NAME_KUCOIN_URL_WEBSOCKET_BASE"}, @@ -278,7 +338,14 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, CCAPI_GATEIO_PERPETUAL_FUTURES_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_CRYPTOCOM, CCAPI_CRYPTOCOM_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_BYBIT, CCAPI_BYBIT_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES, CCAPI_BYBIT_DERIVATIVES_URL_WS_BASE}, {CCAPI_EXCHANGE_NAME_ASCENDEX, CCAPI_ASCENDEX_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_BITGET, CCAPI_BITGET_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_BITGET_FUTURES, CCAPI_BITGET_FUTURES_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_BITMART, CCAPI_BITMART_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_MEXC, CCAPI_MEXC_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_MEXC_FUTURES, CCAPI_MEXC_FUTURES_URL_WS_BASE}, + {CCAPI_EXCHANGE_NAME_WHITEBIT, CCAPI_WHITEBIT_URL_WS_BASE}, }; this->initialSequenceByExchangeMap = {{CCAPI_EXCHANGE_NAME_GEMINI, 0}, {CCAPI_EXCHANGE_NAME_BITFINEX, 1}}; } @@ -294,12 +361,13 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_EXCHANGE_NAME_BITMEX, CCAPI_BITMEX_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_BINANCE_US, CCAPI_BINANCE_US_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_REST_BASE}, + // {CCAPI_EXCHANGE_NAME_BINANCE_MARGIN, CCAPI_BINANCE_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES, CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES, CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_HUOBI, CCAPI_HUOBI_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP, CCAPI_HUOBI_USDT_SWAP_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP, CCAPI_HUOBI_COIN_SWAP_URL_REST_BASE}, - {CCAPI_EXCHANGE_NAME_OKEX, CCAPI_OKEX_URL_REST_BASE}, + {CCAPI_EXCHANGE_NAME_OKX, CCAPI_OKX_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_ERISX, CCAPI_ERISX_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_KUCOIN, CCAPI_KUCOIN_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES, CCAPI_KUCOIN_FUTURES_URL_REST_BASE}, @@ -310,7 +378,14 @@ class SessionConfigs CCAPI_FINAL { {CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, CCAPI_GATEIO_PERPETUAL_FUTURES_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_CRYPTOCOM, CCAPI_CRYPTOCOM_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_BYBIT, CCAPI_BYBIT_URL_REST_BASE}, + {CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES, CCAPI_BYBIT_DERIVATIVES_URL_REST_BASE}, {CCAPI_EXCHANGE_NAME_ASCENDEX, CCAPI_ASCENDEX_URL_REST_BASE}, + {CCAPI_EXCHANGE_NAME_BITGET, CCAPI_BITGET_URL_REST_BASE}, + {CCAPI_EXCHANGE_NAME_BITGET_FUTURES, CCAPI_BITGET_FUTURES_URL_REST_BASE}, + {CCAPI_EXCHANGE_NAME_BITMART, CCAPI_BITMART_URL_REST_BASE}, + {CCAPI_EXCHANGE_NAME_MEXC, CCAPI_MEXC_URL_REST_BASE}, + {CCAPI_EXCHANGE_NAME_MEXC_FUTURES, CCAPI_MEXC_FUTURES_URL_REST_BASE}, + {CCAPI_EXCHANGE_NAME_WHITEBIT, CCAPI_WHITEBIT_URL_REST_BASE}, }; } void initializUrlFixBase() { diff --git a/linux/include/ccapi_cpp/ccapi_session_options.h b/linux/include/ccapi_cpp/ccapi_session_options.h index bb27345ec..e4ab61342 100644 --- a/linux/include/ccapi_cpp/ccapi_session_options.h +++ b/linux/include/ccapi_cpp/ccapi_session_options.h @@ -54,6 +54,10 @@ class SessionOptions CCAPI_FINAL { long httpConnectionPoolIdleTimeoutMilliSeconds{0}; // used to purge the http connection pool if all connections in the // pool have stayed idle for at least this amount of time bool enableOneHttpConnectionPerRequest{}; // create a new http connection for each request +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + long websocketConnectTimeoutMilliSeconds{10000}; +#endif }; } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_SESSION_OPTIONS_H_ diff --git a/linux/include/ccapi_cpp/ccapi_subscription.h b/linux/include/ccapi_cpp/ccapi_subscription.h index 269ddbb47..5f48519f0 100644 --- a/linux/include/ccapi_cpp/ccapi_subscription.h +++ b/linux/include/ccapi_cpp/ccapi_subscription.h @@ -33,6 +33,7 @@ class Subscription CCAPI_FINAL { this->optionMap[CCAPI_CONFLATE_INTERVAL_MILLISECONDS] = CCAPI_CONFLATE_INTERVAL_MILLISECONDS_DEFAULT; this->optionMap[CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS] = CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS_DEFAULT; this->optionMap[CCAPI_MARKET_DEPTH_RETURN_UPDATE] = CCAPI_MARKET_DEPTH_RETURN_UPDATE_DEFAULT; + this->optionMap[CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS] = CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS_DEFAULT; for (const auto& option : optionList) { auto optionKeyValue = UtilString::split(option, "="); this->optionMap[optionKeyValue.at(0)] = optionKeyValue.at(1); @@ -59,15 +60,16 @@ class Subscription CCAPI_FINAL { for (const auto& x : credential) { shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH))); } - std::string output = "Subscription [exchange = " + exchange + ", instrument = " + instrument + ", field = " + field + - ", optionMap = " + ccapi::toString(optionMap) + ", correlationId = " + correlationId + - ", credential = " + ccapi::toString(shortCredential) + ", serviceName = " + serviceName + + std::string output = "Subscription [exchange = " + exchange + ", marginType = " + marginType + ", instrumentType = " + instrumentType + + ", instrument = " + instrument + ", field = " + field + ", optionMap = " + ccapi::toString(optionMap) + + ", correlationId = " + correlationId + ", credential = " + ccapi::toString(shortCredential) + ", serviceName = " + serviceName + ", timeSent = " + UtilTime::getISOTimestamp(timeSent) + "]"; return output; } const std::string& getCorrelationId() const { return correlationId; } const std::string& getExchange() const { return exchange; } const std::string& getInstrument() const { return instrument; } + const std::string& getInstrumentType() const { return instrumentType; } const std::string& getField() const { return field; } const std::string& getRawOptions() const { return rawOptions; } const std::map& getOptionMap() const { return optionMap; } @@ -93,11 +95,15 @@ class Subscription CCAPI_FINAL { } return output; } + const std::string getSerializedCredential() const { return ::ccapi::toString(this->credential); } // 'getTimeSent' only works in C++. For other languages, please use 'getTimeSentISO'. TimePoint getTimeSent() const { return timeSent; } std::string getTimeSentISO() const { return UtilTime::getISOTimestamp(timeSent); } std::pair getTimeSentPair() const { return UtilTime::divide(timeSent); } + const std::string& getMarginType() const { return marginType; } void setTimeSent(TimePoint timeSent) { this->timeSent = timeSent; } + void setInstrumentType(const std::string& instrumentType) { this->instrumentType = instrumentType; } + void setMarginType(const std::string& marginType) { this->marginType = marginType; } enum class Status { UNKNOWN, SUBSCRIBING, @@ -133,6 +139,8 @@ class Subscription CCAPI_FINAL { private: #endif std::string exchange; + std::string marginType; + std::string instrumentType; std::string instrument; std::string field; std::string rawOptions; diff --git a/linux/include/ccapi_cpp/ccapi_ws_connection.h b/linux/include/ccapi_cpp/ccapi_ws_connection.h index f21071bf1..cde6d64f1 100644 --- a/linux/include/ccapi_cpp/ccapi_ws_connection.h +++ b/linux/include/ccapi_cpp/ccapi_ws_connection.h @@ -1,5 +1,6 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_WS_CONNECTION_H_ #define INCLUDE_CCAPI_CPP_CCAPI_WS_CONNECTION_H_ +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET #include #include "ccapi_cpp/ccapi_logger.h" @@ -11,17 +12,23 @@ namespace ccapi { */ class WsConnection CCAPI_FINAL { public: - WsConnection(std::string url, std::string group, std::vector subscriptionList) : url(url), group(group), subscriptionList(subscriptionList) { + WsConnection(std::string url, std::string group, std::vector subscriptionList, std::map credential) + : url(url), group(group), subscriptionList(subscriptionList), credential(credential) { this->assignDummyId(); } WsConnection() {} void assignDummyId() { - this->id = this->url + "||" + this->group + "||" + ccapi::toString(this->subscriptionList); + this->id = this->url + "||" + this->group + "||" + ccapi::toString(this->subscriptionList) + "||" + ccapi::toString(this->credential); this->hdl.reset(); } std::string toString() const { + std::map shortCredential; + for (const auto& x : credential) { + shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH))); + } std::string output = "WsConnection [id = " + id + ", url = " + url + ", group = " + group + ", subscriptionList = " + ccapi::toString(subscriptionList) + - ", status = " + statusToString(status) + ", headers = " + ccapi::toString(headers) + "]"; + ", credential = " + ccapi::toString(shortCredential) + ", status = " + statusToString(status) + + ", headers = " + ccapi::toString(headers) + "]"; return output; } enum class Status { @@ -65,6 +72,101 @@ class WsConnection CCAPI_FINAL { Status status{Status::UNKNOWN}; wspp::connection_hdl hdl = wspp::lib::weak_ptr(); std::map headers; + std::map credential; }; } /* namespace ccapi */ +#else +#include + +#include "ccapi_cpp/ccapi_logger.h" +#include "ccapi_cpp/ccapi_subscription.h" +namespace ccapi { +/** + * This class represents a TCP socket connection for the websocket API. + */ +class WsConnection CCAPI_FINAL { + public: + WsConnection(std::string url, std::string group, std::vector subscriptionList, std::map credential, + std::shared_ptr > > streamPtr) + : url(url), group(group), subscriptionList(subscriptionList), credential(credential), streamPtr(streamPtr) { + this->id = this->url + "||" + this->group + "||" + ccapi::toString(this->subscriptionList) + "||" + ccapi::toString(this->credential); + this->correlationIdList.reserve(subscriptionList.size()); + std::transform(subscriptionList.cbegin(), subscriptionList.cend(), this->correlationIdList.begin(), + [](Subscription subscription) { return subscription.getCorrelationId(); }); + auto splitted1 = UtilString::split(url, "://"); + auto foundSlash = splitted1[1].find_first_of('/'); + auto foundQuestionMark = splitted1[1].find_first_of('?'); + if (foundSlash == std::string::npos && foundQuestionMark == std::string::npos) { + this->path = "/"; + } else if (foundSlash == std::string::npos && foundQuestionMark != std::string::npos) { + this->path = "/" + splitted1[1].substr(foundQuestionMark); + } else if (foundSlash != std::string::npos && foundQuestionMark == std::string::npos) { + this->path = splitted1[1].substr(foundSlash); + } else { + this->path = splitted1[1].substr(foundSlash); + } + } + WsConnection() {} + std::string toString() const { + std::map shortCredential; + for (const auto& x : credential) { + shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH))); + } + std::ostringstream oss; + oss << streamPtr; + std::string output = "WsConnection [id = " + id + ", url = " + url + ", group = " + group + ", subscriptionList = " + ccapi::toString(subscriptionList) + + ", credential = " + ccapi::toString(shortCredential) + ", status = " + statusToString(status) + + ", headers = " + ccapi::toString(headers) + ", streamPtr = " + oss.str() + "]"; + return output; + } + enum class Status { + UNKNOWN, + CONNECTING, + OPEN, + FAILED, + CLOSING, + CLOSED, + }; + static std::string statusToString(Status status) { + std::string output; + switch (status) { + case Status::UNKNOWN: + output = "UNKNOWN"; + break; + case Status::CONNECTING: + output = "CONNECTING"; + break; + case Status::OPEN: + output = "OPEN"; + break; + case Status::FAILED: + output = "FAILED"; + break; + case Status::CLOSING: + output = "CLOSING"; + break; + case Status::CLOSED: + output = "CLOSED"; + break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + return output; + } + std::string id; + std::string url; + std::string group; + std::vector subscriptionList; + std::vector correlationIdList; + Status status{Status::UNKNOWN}; + std::map headers; + std::map credential; + std::shared_ptr > > streamPtr; + beast::websocket::close_code remoteCloseCode; + beast::websocket::close_reason remoteCloseReason; + std::string hostHttpHeaderValue; + std::string path; +}; +} /* namespace ccapi */ +#endif #endif // INCLUDE_CCAPI_CPP_CCAPI_WS_CONNECTION_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h index c07c02213..0e5544d98 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h @@ -45,16 +45,33 @@ class ExecutionManagementService : public Service { // each subscription creates a unique websocket connection void subscribe(std::vector& subscriptionList) override { CCAPI_LOGGER_FUNCTION_ENTER; - CCAPI_LOGGER_DEBUG("this->baseUrl = " + this->baseUrl); + CCAPI_LOGGER_DEBUG("this->baseUrlWs = " + this->baseUrlWs); if (this->shouldContinue.load()) { for (auto& subscription : subscriptionList) { - wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), - [that = shared_from_base(), subscription]() mutable { - auto now = UtilTime::now(); - subscription.setTimeSent(now); - WsConnection wsConnection(that->baseUrl, "", {subscription}); - that->prepareConnect(wsConnection); - }); + boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base(), subscription]() mutable { + auto now = UtilTime::now(); + subscription.setTimeSent(now); + auto credential = subscription.getCredential(); + if (credential.empty()) { + credential = that->credentialDefault; + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + WsConnection wsConnection(that->baseUrlWs, "", {subscription}, credential); + that->prepareConnect(wsConnection); +#else + std::shared_ptr>> streamPtr(nullptr); + try { + streamPtr = that->createStream>>(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs); + } catch (const beast::error_code& ec) { + CCAPI_LOGGER_TRACE("fail"); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", {subscription.getCorrelationId()}); + return; + } + std::shared_ptr wsConnectionPtr(new WsConnection(that->baseUrlWs, "", {subscription}, credential, streamPtr)); + CCAPI_LOGGER_WARN("about to subscribe with new wsConnectionPtr " + toString(*wsConnectionPtr)); + that->prepareConnect(wsConnectionPtr); +#endif + }); } } CCAPI_LOGGER_FUNCTION_EXIT; @@ -112,7 +129,7 @@ class ExecutionManagementService : public Service { void processSuccessfulTextMessageRest(int statusCode, const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Queue* eventQueuePtr) override { Event event; - if (this->doesHttpBodyContainError(request, textMessage)) { + if (this->doesHttpBodyContainError(textMessage)) { event.setType(Event::Type::RESPONSE); Message message; message.setType(Message::Type::RESPONSE_ERROR); @@ -162,6 +179,13 @@ class ExecutionManagementService : public Service { } } } + virtual void convertRequestForWebsocketCustom(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, + const Request& request, int wsRequestId, const TimePoint& now, const std::string& symbolId, + const std::map& credential) { + auto errorMessage = "Websocket unimplemented operation " + Request::operationToString(request.getOperation()) + " for exchange " + request.getExchange(); + throw std::runtime_error(errorMessage); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET virtual void logonToExchange(const WsConnection& wsConnection, const TimePoint& now, const std::map& credential) { CCAPI_LOGGER_INFO("about to logon to exchange"); CCAPI_LOGGER_INFO("exchange is " + this->exchangeName); @@ -179,9 +203,7 @@ class ExecutionManagementService : public Service { void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override { WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); auto subscription = wsConnection.subscriptionList.at(0); - rj::Document document; - document.Parse(textMessage.c_str()); - this->onTextMessage(wsConnection, subscription, textMessage, document, timeReceived); + this->onTextMessage(wsConnection, subscription, textMessage, timeReceived); this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived); } void onOpen(wspp::connection_hdl hdl) override { @@ -192,10 +214,7 @@ class ExecutionManagementService : public Service { auto correlationId = wsConnection.subscriptionList.at(0).getCorrelationId(); this->wsConnectionByCorrelationIdMap.insert({correlationId, wsConnection}); this->correlationIdByConnectionIdMap.insert({wsConnection.id, correlationId}); - auto credential = wsConnection.subscriptionList.at(0).getCredential(); - if (credential.empty()) { - credential = this->credentialDefault; - } + auto credential = wsConnection.credential; this->logonToExchange(wsConnection, now, credential); } void onClose(wspp::connection_hdl hdl) override { @@ -208,53 +227,53 @@ class ExecutionManagementService : public Service { this->wsRequestIdByConnectionIdMap.erase(wsConnection.id); Service::onClose(hdl); } - void sendRequestByWebsocket(Request& request, const TimePoint& now) override { - CCAPI_LOGGER_FUNCTION_ENTER; - CCAPI_LOGGER_TRACE("now = " + toString(now)); - wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [that = shared_from_base(), request]() mutable { - auto now = UtilTime::now(); - CCAPI_LOGGER_DEBUG("request = " + toString(request)); - CCAPI_LOGGER_TRACE("now = " + toString(now)); - request.setTimeSent(now); - auto nowFixTimeStr = UtilTime::convertTimePointToFIXTime(now); - auto& correlationId = request.getCorrelationId(); - auto it = that->wsConnectionByCorrelationIdMap.find(correlationId); - if (it == that->wsConnectionByCorrelationIdMap.end()) { - that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "Websocket connection was not found", {correlationId}); - return; - } - auto& wsConnection = it->second; - CCAPI_LOGGER_TRACE("wsConnection = " + toString(wsConnection)); - auto instrument = request.getInstrument(); - auto symbolId = instrument; - CCAPI_LOGGER_TRACE("symbolId = " + symbolId); + virtual void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + const TimePoint& timeReceived) {} +#else + virtual void logonToExchange(std::shared_ptr wsConnectionPtr, const TimePoint& now, const std::map& credential) { + CCAPI_LOGGER_INFO("about to logon to exchange"); + CCAPI_LOGGER_INFO("exchange is " + this->exchangeName); + WsConnection& wsConnection = *wsConnectionPtr; + auto subscription = wsConnection.subscriptionList.at(0); + std::vector sendStringList = this->createSendStringListFromSubscription(wsConnection, subscription, now, credential); + for (const auto& sendString : sendStringList) { + CCAPI_LOGGER_INFO("sendString = " + sendString); ErrorCode ec; - rj::Document document; - rj::Document::AllocatorType& allocator = document.GetAllocator(); - auto credential = request.getCredential(); - if (credential.empty()) { - credential = that->credentialDefault; - } - that->convertRequestForWebsocket(document, allocator, wsConnection, request, ++that->wsRequestIdByConnectionIdMap[wsConnection.id], now, symbolId, - credential); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - std::string sendString = stringBuffer.GetString(); - CCAPI_LOGGER_TRACE("sendString = " + sendString); - that->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); + this->send(wsConnectionPtr, sendString, ec); if (ec) { - that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); } - }); - CCAPI_LOGGER_FUNCTION_EXIT; + } } - virtual void convertRequestForWebsocketCustom(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, - const Request& request, int wsRequestId, const TimePoint& now, const std::string& symbolId, - const std::map& credential) { - auto errorMessage = "Websocket unimplemented operation " + Request::operationToString(request.getOperation()) + " for exchange " + request.getExchange(); - throw std::runtime_error(errorMessage); + void onTextMessage(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived) override { + auto subscription = wsConnectionPtr->subscriptionList.at(0); + this->onTextMessage(wsConnectionPtr, subscription, textMessageView, timeReceived); + this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived); } + void onOpen(std::shared_ptr wsConnectionPtr) override { + CCAPI_LOGGER_FUNCTION_ENTER; + Service::onOpen(wsConnectionPtr); + auto now = UtilTime::now(); + WsConnection& wsConnection = *wsConnectionPtr; + auto correlationId = wsConnection.subscriptionList.at(0).getCorrelationId(); + this->wsConnectionByCorrelationIdMap.insert({correlationId, wsConnectionPtr}); + this->correlationIdByConnectionIdMap.insert({wsConnection.id, correlationId}); + auto credential = wsConnection.credential; + this->logonToExchange(wsConnectionPtr, now, credential); + } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + CCAPI_LOGGER_FUNCTION_ENTER; + WsConnection& wsConnection = *wsConnectionPtr; + if (this->correlationIdByConnectionIdMap.find(wsConnection.id) != this->correlationIdByConnectionIdMap.end()) { + this->wsConnectionByCorrelationIdMap.erase(this->correlationIdByConnectionIdMap.at(wsConnection.id)); + this->correlationIdByConnectionIdMap.erase(wsConnection.id); + } + this->wsRequestIdByConnectionIdMap.erase(wsConnection.id); + Service::onClose(wsConnectionPtr, ec); + } + virtual void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessage, + const TimePoint& timeReceived) {} +#endif void convertRequestForRestGenericPrivateRequest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& credential) { const std::map param = request.getFirstParamWithDefault(); @@ -291,8 +310,56 @@ class ExecutionManagementService : public Service { int64_t nonce = std::chrono::duration_cast(now.time_since_epoch()).count() + requestIndex; return nonce; } - virtual void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, - const TimePoint& timeReceived) {} + void sendRequestByWebsocket(Request& request, const TimePoint& now) override { + CCAPI_LOGGER_FUNCTION_ENTER; + CCAPI_LOGGER_TRACE("now = " + toString(now)); + boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base(), request]() mutable { + auto now = UtilTime::now(); + CCAPI_LOGGER_DEBUG("request = " + toString(request)); + CCAPI_LOGGER_TRACE("now = " + toString(now)); + request.setTimeSent(now); + auto nowFixTimeStr = UtilTime::convertTimePointToFIXTime(now); + auto& correlationId = request.getCorrelationId(); + auto it = that->wsConnectionByCorrelationIdMap.find(correlationId); + if (it == that->wsConnectionByCorrelationIdMap.end()) { + that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "Websocket connection was not found", {correlationId}); + return; + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + auto& wsConnection = it->second; +#else + auto wsConnectionPtr = it->second; + auto& wsConnection = *wsConnectionPtr; +#endif + CCAPI_LOGGER_TRACE("wsConnection = " + toString(wsConnection)); + auto instrument = request.getInstrument(); + auto symbolId = instrument; + CCAPI_LOGGER_TRACE("symbolId = " + symbolId); + ErrorCode ec; + rj::Document document; + rj::Document::AllocatorType& allocator = document.GetAllocator(); + auto credential = request.getCredential(); + if (credential.empty()) { + credential = that->credentialDefault; + } + that->convertRequestForWebsocket(document, allocator, wsConnection, request, ++that->wsRequestIdByConnectionIdMap[wsConnection.id], now, symbolId, + credential); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + CCAPI_LOGGER_TRACE("sendString = " + sendString); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + that->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); +#else + that->send(wsConnectionPtr, sendString, ec); +#endif + if (ec) { + that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); + } + }); + CCAPI_LOGGER_FUNCTION_EXIT; + } virtual void convertRequestForRest(http::request& req, const Request& request, const std::string& wsRequestId, const TimePoint& now, const std::string& symbolId, const std::map& credential) {} virtual void convertRequestForWebsocket(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, @@ -318,7 +385,12 @@ class ExecutionManagementService : public Service { std::string getAccountBalancesTarget; std::string getAccountPositionsTarget; std::map correlationIdByConnectionIdMap; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET std::map wsConnectionByCorrelationIdMap; +#else + std::map > + wsConnectionByCorrelationIdMap; // TODO(cryptochassis): for consistency, to be renamed to wsConnectionPtrByCorrelationIdMap +#endif std::map wsRequestIdByConnectionIdMap; }; } /* namespace ccapi */ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ascendex.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ascendex.h index ae2a243e0..661ac8a74 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ascendex.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ascendex.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_ASCENDEX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_ASCENDEX_API_KEY; this->apiSecretName = CCAPI_ASCENDEX_API_SECRET; this->apiAccountGroupName = CCAPI_ASCENDEX_API_ACCOUNT_GROUP; @@ -38,8 +47,8 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService { WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); wsConnection.status = WsConnection::Status::OPEN; } - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({ "op": "ping" })", wspp::frame::opcode::text, ec); } + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, const std::map& credential) override { @@ -350,7 +359,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService { credential = that->credentialDefault; } const auto& accountGroup = mapGetWithDefault(credential, that->apiAccountGroupName); - WsConnection wsConnection(that->baseUrl + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription}); + WsConnection wsConnection(that->baseUrlWs + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription}, credential); that->prepareConnect(wsConnection); }); } diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance.h index ae93cd13b..217b926d9 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance.h @@ -13,14 +13,23 @@ class ExecutionManagementServiceBinance : public ExecutionManagementServiceBinan ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BINANCE_API_KEY; this->apiSecretName = CCAPI_BINANCE_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -31,6 +40,15 @@ class ExecutionManagementServiceBinance : public ExecutionManagementServiceBinan this->cancelOpenOrdersTarget = "/api/v3/openOrders"; this->listenKeyTarget = CCAPI_BINANCE_LISTEN_KEY_PATH; this->getAccountBalancesTarget = "/api/v3/account"; + this->createOrderMarginTarget = "/sapi/v1/margin/order"; + this->cancelOrderMarginTarget = "/sapi/v1/margin/order"; + this->getOrderMarginTarget = "/sapi/v1/margin/order"; + this->getOpenOrdersMarginTarget = "/sapi/v1/margin/openOrders"; + this->cancelOpenOrdersMarginTarget = "/sapi/v1/margin/openOrders"; + this->getAccountBalancesCrossMarginTarget = "/sapi/v1/margin/account"; + this->getAccountBalancesIsolatedMarginTarget = "/sapi/v1/margin/isolated/account"; + this->listenKeyCrossMarginTarget = CCAPI_BINANCE_LISTEN_KEY_CROSS_MARGIN_PATH; + this->listenKeyIsolatedMarginTarget = CCAPI_BINANCE_LISTEN_KEY_ISOLATED_MARGIN_PATH; } virtual ~ExecutionManagementServiceBinance() {} }; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_base.h index 3e1ea7b7f..7e88c4686 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_base.h @@ -1,5 +1,5 @@ -#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_ -#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_ #ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT #if defined(CCAPI_ENABLE_EXCHANGE_BINANCE_US) || defined(CCAPI_ENABLE_EXCHANGE_BINANCE) || defined(CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES) || \ defined(CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES) @@ -92,7 +92,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService } } this->signRequest(queryString, param, now, credential); - req.target(std::string(this->createOrderTarget) + "?" + queryString); + req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN + ? this->createOrderMarginTarget + : this->createOrderTarget) + + "?" + queryString); } break; case Request::Operation::CANCEL_ORDER: { req.method(http::verb::delete_); @@ -105,7 +108,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService }); this->appendSymbolId(queryString, symbolId); this->signRequest(queryString, param, now, credential); - req.target(this->cancelOrderTarget + "?" + queryString); + req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN + ? this->cancelOrderMarginTarget + : this->cancelOrderTarget) + + "?" + queryString); } break; case Request::Operation::GET_ORDER: { req.method(http::verb::get); @@ -118,7 +124,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService }); this->appendSymbolId(queryString, symbolId); this->signRequest(queryString, param, now, credential); - req.target(this->getOrderTarget + "?" + queryString); + req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN + ? this->getOrderMarginTarget + : this->getOrderTarget) + + "?" + queryString); } break; case Request::Operation::GET_OPEN_ORDERS: { req.method(http::verb::get); @@ -128,7 +137,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService this->appendSymbolId(queryString, symbolId); } this->signRequest(queryString, {}, now, credential); - req.target(this->getOpenOrdersTarget + "?" + queryString); + req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN + ? this->getOpenOrdersMarginTarget + : this->getOpenOrdersTarget) + + "?" + queryString); } break; case Request::Operation::CANCEL_OPEN_ORDERS: { req.method(http::verb::delete_); @@ -136,14 +148,29 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService this->appendParam(queryString, {}); this->appendSymbolId(queryString, symbolId); this->signRequest(queryString, {}, now, credential); - req.target(this->cancelOpenOrdersTarget + "?" + queryString); + req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN + ? this->cancelOpenOrdersMarginTarget + : this->cancelOpenOrdersTarget) + + "?" + queryString); } break; case Request::Operation::GET_ACCOUNT_BALANCES: { req.method(http::verb::get); std::string queryString; this->appendParam(queryString, {}); + if (!symbolId.empty()) { + queryString += "symbols="; + queryString += Url::urlEncode(symbolId); + queryString += "&"; + } this->signRequest(queryString, {}, now, credential); - req.target(this->getAccountBalancesTarget + "?" + queryString); + const auto& marginType = request.getMarginType(); + std::string target = this->getAccountBalancesTarget; + if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) { + target = this->getAccountBalancesCrossMarginTarget; + } else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { + target = this->getAccountBalancesIsolatedMarginTarget; + } + req.target(target + "?" + queryString); } break; default: this->convertRequestForRestCustom(req, request, now, symbolId, credential); @@ -182,16 +209,58 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService const rj::Document& document) override { switch (request.getOperation()) { case Request::Operation::GET_ACCOUNT_BALANCES: { - for (const auto& x : document[this->isDerivatives ? "assets" : "balances"].GetArray()) { - Element element; - element.insert(CCAPI_EM_ASSET, x["asset"].GetString()); - if (this->isDerivatives) { + const auto& marginType = request.getMarginType(); + if (this->isDerivatives) { + for (const auto& x : document["assets"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ASSET, x["asset"].GetString()); element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString()); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString()); + elementList.emplace_back(std::move(element)); + } + } else { + if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) { + for (const auto& x : document["userAssets"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ASSET, x["asset"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString()); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString()); + element.insert(CCAPI_EM_QUANTITY_LIABILITY, Decimal(x["borrowed"].GetString()).add(Decimal(x["interest"].GetString())).toString()); + elementList.emplace_back(std::move(element)); + } + } else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { + for (const auto& x : document["assets"].GetArray()) { + std::string symbol = x["symbol"].GetString(); + { + const auto& y = x["baseAsset"]; + Element element; + element.insert(CCAPI_EM_INSTRUMENT, symbol); + element.insert(CCAPI_EM_ASSET, y["asset"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(y["free"].GetString()).add(Decimal(y["locked"].GetString())).toString()); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, y["free"].GetString()); + element.insert(CCAPI_EM_QUANTITY_LIABILITY, Decimal(y["borrowed"].GetString()).add(Decimal(y["interest"].GetString())).toString()); + elementList.emplace_back(std::move(element)); + } + { + const auto& y = x["quoteAsset"]; + Element element; + element.insert(CCAPI_EM_INSTRUMENT, symbol); + element.insert(CCAPI_EM_ASSET, y["asset"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(y["free"].GetString()).add(Decimal(y["locked"].GetString())).toString()); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, y["free"].GetString()); + element.insert(CCAPI_EM_QUANTITY_LIABILITY, Decimal(y["borrowed"].GetString()).add(Decimal(y["interest"].GetString())).toString()); + elementList.emplace_back(std::move(element)); + } + } } else { - element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString()); + for (const auto& x : document["balances"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ASSET, x["asset"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString()); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString()); + elementList.emplace_back(std::move(element)); + } } - element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x[this->isDerivatives ? "availableBalance" : "free"].GetString()); - elementList.emplace_back(std::move(element)); } } break; default: @@ -207,7 +276,13 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); req.method(http::verb::post); std::string target = this->listenKeyTarget; - if (this->listenKeyTarget == "/sapi/v1/userDataStream/isolated") { + const auto& marginType = wsConnection.subscriptionList.at(0).getMarginType(); + if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) { + target = this->listenKeyCrossMarginTarget; + } else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { + target = this->listenKeyIsolatedMarginTarget; + } + if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { auto symbol = wsConnection.subscriptionList.at(0).getInstrument(); target += "?" + symbol; } @@ -234,7 +309,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService rj::Document document; document.Parse(body.c_str()); std::string listenKey = document["listenKey"].GetString(); - std::string url = that->baseUrl + "/" + listenKey; + std::string url = that->baseUrlWs + "/" + listenKey; thisWsConnection.url = url; that->connect(thisWsConnection); that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({ @@ -258,25 +333,34 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService Message message; message.setTimeReceived(now); message.setType(Message::Type::SUBSCRIPTION_STARTED); + message.setCorrelationIdList({wsConnection.subscriptionList.at(0).getCorrelationId()}); event.setMessageList({message}); this->eventHandler(event, nullptr); - setPingListenKeyTimer(wsConnection); + this->setPingListenKeyTimer(wsConnection); } void setPingListenKeyTimer(const WsConnection& wsConnection) { this->pingListenKeyTimerMapByConnectionIdMap[wsConnection.id] = this->serviceContextPtr->tlsClientPtr->set_timer( this->pingListenKeyIntervalSeconds * 1000, [wsConnection, that = shared_from_base()](ErrorCode const& ec) { - if (ec) return; + if (ec) { + return; + } that->setPingListenKeyTimer(wsConnection); http::request req; req.set(http::field::host, that->hostRest); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); req.method(http::verb::put); std::string target = that->listenKeyTarget; + const auto& marginType = wsConnection.subscriptionList.at(0).getMarginType(); + if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) { + target = that->listenKeyCrossMarginTarget; + } else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { + target = that->listenKeyIsolatedMarginTarget; + } if (!that->isDerivatives) { std::map params; auto listenKey = that->extraPropertyByConnectionIdMap.at(wsConnection.id).at("listenKey"); params.insert({"listenKey", listenKey}); - if (that->listenKeyTarget == "/sapi/v1/userDataStream/isolated") { + if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { auto symbol = wsConnection.subscriptionList.at(0).getInstrument(); params.insert({"symbol", symbol}); } @@ -313,8 +397,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService } ExecutionManagementService::onClose(hdl); } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); @@ -394,7 +480,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService auto it = data.FindMember("ap"); if (it != data.MemberEnd() && !it->value.IsNull()) { info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, - std::to_string(std::stod(it->value.GetString()) * std::stod(data["z"].GetString()))); + UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["z"].GetString()))); } } std::vector elementList; @@ -411,8 +497,17 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService std::string listenKeyTarget; int pingListenKeyIntervalSeconds; std::map pingListenKeyTimerMapByConnectionIdMap; + std::string createOrderMarginTarget; + std::string cancelOrderMarginTarget; + std::string getOrderMarginTarget; + std::string getOpenOrdersMarginTarget; + std::string cancelOpenOrdersMarginTarget; + std::string getAccountBalancesCrossMarginTarget; + std::string getAccountBalancesIsolatedMarginTarget; + std::string listenKeyCrossMarginTarget; + std::string listenKeyIsolatedMarginTarget; }; } /* namespace ccapi */ #endif #endif -#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_ +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h index 5d335c380..cf5ddfbd1 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceBinanceCoinFutures : public ExecutionManagementS SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY; this->apiSecretName = CCAPI_BINANCE_COIN_FUTURES_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -29,7 +38,7 @@ class ExecutionManagementServiceBinanceCoinFutures : public ExecutionManagementS this->isDerivatives = true; this->listenKeyTarget = CCAPI_BINANCE_COIN_FUTURES_LISTEN_KEY_PATH; this->getAccountBalancesTarget = "/dapi/v1/account"; - this->getAccountPositionsTarget = "/dapi/v1/account"; + this->getAccountPositionsTarget = "/dapi/v1/positionRisk"; } virtual ~ExecutionManagementServiceBinanceCoinFutures() {} }; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h index cb2a034e8..611f47a39 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h @@ -31,7 +31,7 @@ class ExecutionManagementServiceBinanceDerivativesBase : public ExecutionManagem const rj::Document& document) override { switch (request.getOperation()) { case Request::Operation::GET_ACCOUNT_POSITIONS: { - for (const auto& x : document["positions"].GetArray()) { + for (const auto& x : document.GetArray()) { Element element; element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); element.insert(CCAPI_EM_POSITION_SIDE, x["positionSide"].GetString()); @@ -43,7 +43,7 @@ class ExecutionManagementServiceBinanceDerivativesBase : public ExecutionManagem positionAmt = x["maxQty"].GetString(); } element.insert(CCAPI_EM_POSITION_QUANTITY, positionAmt); - element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["entryPrice"].GetString()) * std::stod(positionAmt))); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString()); element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString()); elementList.emplace_back(std::move(element)); } diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_us.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_us.h index d1beb18e8..45979af98 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_us.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_us.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceBinanceUs : public ExecutionManagementServiceBin ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_US; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BINANCE_US_API_KEY; this->apiSecretName = CCAPI_BINANCE_US_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h index efe1222cc..895423088 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceBinanceUsdsFutures : public ExecutionManagementS SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY; this->apiSecretName = CCAPI_BINANCE_USDS_FUTURES_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -29,7 +38,7 @@ class ExecutionManagementServiceBinanceUsdsFutures : public ExecutionManagementS this->isDerivatives = true; this->listenKeyTarget = CCAPI_BINANCE_USDS_FUTURES_LISTEN_KEY_PATH; this->getAccountBalancesTarget = "/fapi/v2/account"; - this->getAccountPositionsTarget = "/fapi/v2/account"; + this->getAccountPositionsTarget = "/fapi/v2/positionRisk"; } virtual ~ExecutionManagementServiceBinanceUsdsFutures() {} }; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h index c8f116508..f2299fe25 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BITFINEX; - this->baseUrl = std::string(CCAPI_BITFINEX_PRIVATE_URL_WS_BASE) + "/ws/2"; + this->baseUrlWs = std::string(CCAPI_BITFINEX_PRIVATE_URL_WS_BASE) + "/ws/2"; this->baseUrlRest = CCAPI_BITFINEX_PRIVATE_URL_REST_BASE; this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BITFINEX_API_KEY; this->apiSecretName = CCAPI_BITFINEX_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -227,10 +236,14 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService { } void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - if (operation == Request::Operation::CREATE_ORDER || operation == Request::Operation::CANCEL_ORDER) { + if (operation == Request::Operation::CREATE_ORDER) { Element element; this->extractOrderInfo(element, document[4][0]); elementList.emplace_back(std::move(element)); + } else if (operation == Request::Operation::CANCEL_ORDER) { + Element element; + this->extractOrderInfo(element, document[4]); + elementList.emplace_back(std::move(element)); } else if (operation == Request::Operation::GET_ORDER) { Element element; this->extractOrderInfo(element, document[0]); @@ -269,7 +282,7 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService { std::string availPos = x["availPos"].GetString(); std::string positionQuantity = availPos.empty() ? x["pos"].GetString() : availPos; element.insert(CCAPI_EM_POSITION_QUANTITY, positionQuantity); - element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["avgPx"].GetString()) * std::stod(positionQuantity))); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPx"].GetString()); element.insert(CCAPI_EM_POSITION_LEVERAGE, x["lever"].GetString()); elementList.emplace_back(std::move(element)); } @@ -340,8 +353,10 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h new file mode 100644 index 000000000..279d2c5bc --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h @@ -0,0 +1,399 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET +#include "ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h" +namespace ccapi { +class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitgetBase { + public: + ExecutionManagementServiceBitget(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) + : ExecutionManagementServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/v1/stream"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_BITGET_API_KEY; + this->apiSecretName = CCAPI_BITGET_API_SECRET; + this->apiPassphraseName = CCAPI_BITGET_API_PASSPHRASE; + this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName}); + this->createOrderTarget = "/api/spot/v1/trade/orders"; + this->cancelOrderTarget = "/api/spot/v1/trade/cancel-order"; + this->getOrderTarget = "/api/spot/v1/trade/orderInfo"; + this->getOpenOrdersTarget = "/api/spot/v1/trade/open-orders"; + this->getAccountBalancesTarget = "/api/spot/v1/account/assets"; + } + virtual ~ExecutionManagementServiceBitget() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + private: +#endif + void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_SIDE, "side"}, + {CCAPI_EM_ORDER_QUANTITY, "quantity"}, + {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, + {CCAPI_EM_CLIENT_ORDER_ID, "clientOrderId"}, + {CCAPI_SYMBOL_ID, "symbol"}, + {CCAPI_EM_ORDER_ID, "orderId"}, + }) { + for (const auto& kv : param) { + auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + auto value = kv.second; + if (key == "side") { + value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell"; + } + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); + } + } + void appendParam(std::string& queryString, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_EM_CLIENT_ORDER_ID, "clientOrderId"}, + {CCAPI_SYMBOL_ID, "symbol"}, + }) { + for (const auto& kv : param) { + queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + queryString += "="; + queryString += Url::urlEncode(kv.second); + queryString += "&"; + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + this->prepareReq(req, request, now, symbolId, credential); + Request::Operation operation = request.getOperation(); + switch (operation) { + case Request::Operation::GENERIC_PRIVATE_REQUEST: { + ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::CREATE_ORDER: { + req.set("X-CHANNEL-API-CODE", CCAPI_BITGET_API_CHANNEL_API_CODE); + req.method(http::verb::post); + req.target(this->createOrderTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (param.find("orderType") == param.end()) { + document.AddMember("orderType", rj::Value("limit").Move(), allocator); + } + if (param.find("force") == param.end()) { + document.AddMember("force", rj::Value("normal").Move(), allocator); + } + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::CANCEL_ORDER: { + req.method(http::verb::post); + req.target(this->cancelOrderTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::GET_ORDER: { + req.method(http::verb::post); + req.target(this->getOrderTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::GET_OPEN_ORDERS: { + req.method(http::verb::post); + req.target(this->getOpenOrdersTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::GET_ACCOUNT_BALANCES: { + req.method(http::verb::get); + req.target(this->getAccountBalancesTarget); + this->signRequest(req, "", credential); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOrderId", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("quantity", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("fillQuantity", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("fillTotalAmount", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}}; + if (operation != Request::Operation::CANCEL_ORDER) { + const rj::Value& data = document["data"]; + if (data.IsObject()) { + Element element; + this->extractOrderInfo(element, data, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } else { + for (const auto& x : data.GetArray()) { + Element element; + this->extractOrderInfo(element, x, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } + } + } + void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + switch (request.getOperation()) { + case Request::Operation::GET_ACCOUNT_BALANCES: { + for (const auto& x : document["data"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ASSET, x["coinName"].GetString()); + std::string available = x["available"].GetString(); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, available); + std::string frozen = x["frozen"].GetString(); + std::string lock = x["lock"].GetString(); + element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(frozen)).add(Decimal(lock))).toString()); + elementList.emplace_back(std::move(element)); + } + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + void extractOrderInfo(Element& element, const rj::Value& x, + const std::map >& extractionFieldNameMap) override { + ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap); + { + auto it1 = x.FindMember("accFillSz"); + auto it2 = x.FindMember("avgPx"); + if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) { + auto it1Str = std::string(it1->value.GetString()); + auto it2Str = std::string(it2->value.GetString()); + if (!it1Str.empty() && !it2Str.empty()) { + element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))); + } + } + } + } + std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, + const std::map& credential) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("login").Move(), allocator); + rj::Value arg(rj::kObjectType); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); + std::string ts = std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); + arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator); + arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator); + arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator); + std::string signData = ts + "GET" + "/user/verify"; + std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData)); + arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator); + rj::Value args(rj::kArrayType); + args.PushBack(arg, allocator); + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + const TimePoint& timeReceived) override { + if (textMessage != "pong") { + rj::Document document; + document.Parse(textMessage.c_str()); + auto it = document.FindMember("event"); + std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; + if (eventStr == "login") { + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + for (const auto& field : fieldSet) { + std::string channel; + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + channel = "orders"; + } + for (const auto& instrument : instrumentSet) { + rj::Value arg(rj::kObjectType); + arg.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator); + arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator); + arg.AddMember("instType", rj::Value("spbl").Move(), allocator); + args.PushBack(arg, allocator); + } + } + document.AddMember("args", args, allocator); + rj::StringBuffer stringBufferSubscribe; + rj::Writer writerSubscribe(stringBufferSubscribe); + document.Accept(writerSubscribe); + std::string sendString = stringBufferSubscribe.GetString(); + ErrorCode ec; + this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } else { + Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } + } + } + Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr, + const TimePoint& timeReceived) { + Event event; + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + const auto& correlationId = subscription.getCorrelationId(); + message.setCorrelationIdList({correlationId}); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + if (eventStr.empty()) { + const rj::Value& arg = document["arg"]; + std::string channel = std::string(arg["channel"].GetString()); + event.setType(Event::Type::SUBSCRIPTION_DATA); + std::string instrument = arg["instId"].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + if (channel == "orders") { + if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + const rj::Value& data = document["data"]; + for (const auto& x : data.GetArray()) { + auto itTradeId = x.FindMember("tradeId"); + std::string tradeId = itTradeId != x.MemberEnd() ? itTradeId->value.GetString() : ""; + if (!tradeId.empty()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + element.insert(CCAPI_TRADE_ID, tradeId); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString())); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0"); + element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString())); + element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString())); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString())); + element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString())); + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + const rj::Value& data = document["data"]; + for (const auto& x : data.GetArray()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)}, + }; + Element info; + this->extractOrderInfo(info, x, extractionFieldNameMap); + info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + } + } else if (eventStr == "subscribe") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } else if (eventStr == "error") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + event.setMessageList(messageList); + return event; + } +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h new file mode 100644 index 000000000..5f4838f1f --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h @@ -0,0 +1,72 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_BASE_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_BASE_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#if defined(CCAPI_ENABLE_EXCHANGE_BITGET) || defined(CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES) +#include "ccapi_cpp/service/ccapi_execution_management_service.h" +namespace ccapi { +class ExecutionManagementServiceBitgetBase : public ExecutionManagementService { + public: + ExecutionManagementServiceBitgetBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) + : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {} + virtual ~ExecutionManagementServiceBitgetBase() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"00000\"")); } + void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, + std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, + const std::map& credential) override { + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("ACCESS-TIMESTAMP").to_string(); + preSignedText += methodString; + auto target = path; + if (!queryString.empty()) { + target += "?"; + target += queryString; + } + preSignedText += target; + preSignedText += body; + auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); + if (!headerString.empty()) { + headerString += "\r\n"; + } + headerString += "ACCESS-SIGN:" + signature; + } + void signRequest(http::request& req, const std::string& body, const std::map& credential) { + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("ACCESS-TIMESTAMP").to_string(); + preSignedText += std::string(req.method_string()); + preSignedText += req.target().to_string(); + preSignedText += body; + auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); + req.set("ACCESS-SIGN", signature); + req.body() = body; + req.prepare_payload(); + } + void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) { + rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); + } + void appendSymbolId(std::string& queryString, const std::string& symbolId) { + queryString += "symbol="; + queryString += Url::urlEncode(symbolId); + queryString += "&"; + } + void prepareReq(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) { + req.set(beast::http::field::content_type, "application/json"); + req.set("locale", "en-US"); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("ACCESS-KEY", apiKey); + req.set("ACCESS-TIMESTAMP", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); + auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); + req.set("ACCESS-PASSPHRASE", apiPassphrase); + } + std::string apiPassphraseName; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_BASE_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_futures.h new file mode 100644 index 000000000..324648947 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_futures.h @@ -0,0 +1,455 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_FUTURES_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_FUTURES_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES +#include "ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h" +namespace ccapi { +class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServiceBitgetBase { + public: + ExecutionManagementServiceBitgetFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) + : ExecutionManagementServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET_FUTURES; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/mix/v1/stream"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_BITGET_FUTURES_API_KEY; + this->apiSecretName = CCAPI_BITGET_FUTURES_API_SECRET; + this->apiPassphraseName = CCAPI_BITGET_FUTURES_API_PASSPHRASE; + this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName}); + this->createOrderTarget = "/api/mix/v1/order/placeOrder"; + this->cancelOrderTarget = "/api/mix/v1/order/cancel-order"; + this->getOrderTarget = "/api/mix/v1/order/detail"; + this->getOpenOrdersTarget = "/api/mix/v1/order/current"; + this->getAllOpenOrdersTarget = "/api/mix/v1/order/marginCoinCurrent"; + this->cancelOpenOrdersTarget = "/api/mix/v1/order/cancel-all-orders"; + this->getAccountBalancesTarget = "/api/mix/v1/account/accounts"; + this->getAccountPositionsTarget = "/api/mix/v1/position/singlePosition"; + this->getAccountAllPositionsTarget = "/api/mix/v1/position/allPosition"; + } + virtual ~ExecutionManagementServiceBitgetFutures() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + private: +#endif + void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, + const std::map standardizationMap = { + {CCAPI_MARGIN_ASSET, "marginCoin"}, + {CCAPI_EM_ORDER_SIDE, "side"}, + {CCAPI_EM_ORDER_QUANTITY, "size"}, + {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, + {CCAPI_EM_CLIENT_ORDER_ID, "clientOid"}, + {CCAPI_SYMBOL_ID, "symbol"}, + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_INSTRUMENT_TYPE, "productType"}, + }) { + for (const auto& kv : param) { + auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + auto value = kv.second; + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); + } + } + void appendParam(std::string& queryString, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_EM_CLIENT_ORDER_ID, "clientOrderId"}, + {CCAPI_SYMBOL_ID, "symbol"}, + {CCAPI_INSTRUMENT_TYPE, "productType"}, + }) { + for (const auto& kv : param) { + queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + queryString += "="; + queryString += Url::urlEncode(kv.second); + queryString += "&"; + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + this->prepareReq(req, request, now, symbolId, credential); + Request::Operation operation = request.getOperation(); + switch (operation) { + case Request::Operation::GENERIC_PRIVATE_REQUEST: { + ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::CREATE_ORDER: { + req.set("X-CHANNEL-API-CODE", CCAPI_BITGET_API_CHANNEL_API_CODE); + req.method(http::verb::post); + req.target(this->createOrderTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (param.find("orderType") == param.end()) { + document.AddMember("orderType", rj::Value("limit").Move(), allocator); + } + if (param.find("timeInForceValue") == param.end()) { + document.AddMember("timeInForceValue", rj::Value("normal").Move(), allocator); + } + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::CANCEL_ORDER: { + req.method(http::verb::post); + req.target(this->cancelOrderTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::GET_ORDER: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param); + if (!symbolId.empty()) { + this->appendSymbolId(queryString, symbolId); + } + if (queryString.back() == '&') { + queryString.pop_back(); + } + req.target(this->getOrderTarget + "?" + queryString); + this->signRequest(req, "", credential); + } break; + case Request::Operation::GET_OPEN_ORDERS: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param); + std::string path; + if (symbolId.empty()) { + path = this->getAllOpenOrdersTarget; + } else { + this->appendSymbolId(queryString, symbolId); + path = this->getOpenOrdersTarget; + } + if (queryString.back() == '&') { + queryString.pop_back(); + } + req.target(path + "?" + queryString); + this->signRequest(req, "", credential); + } break; + case Request::Operation::CANCEL_OPEN_ORDERS: { + req.method(http::verb::post); + req.target(this->cancelOpenOrdersTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::GET_ACCOUNT_BALANCES: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param); + if (!symbolId.empty()) { + this->appendSymbolId(queryString, symbolId); + } + if (queryString.back() == '&') { + queryString.pop_back(); + } + req.target(this->getAccountBalancesTarget + "?" + queryString); + this->signRequest(req, "", credential); + } break; + case Request::Operation::GET_ACCOUNT_POSITIONS: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param); + std::string path; + if (symbolId.empty()) { + path = this->getAccountAllPositionsTarget; + } else { + this->appendSymbolId(queryString, symbolId); + path = this->getAccountPositionsTarget; + } + if (queryString.back() == '&') { + queryString.pop_back(); + } + req.target(path + "?" + queryString); + this->signRequest(req, "", credential); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}}; + const rj::Value& data = document["data"]; + if (operation == Request::Operation::CREATE_ORDER || operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::GET_ORDER) { + Element element; + this->extractOrderInfo(element, data, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } else if (operation == Request::Operation::GET_OPEN_ORDERS) { + for (const auto& x : data.GetArray()) { + Element element; + this->extractOrderInfo(element, x, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } + } + void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + switch (request.getOperation()) { + case Request::Operation::GET_ACCOUNT_BALANCES: { + for (const auto& x : document["data"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ASSET, x["coinName"].GetString()); + std::string available = x["available"].GetString(); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, available); + std::string frozen = x["frozen"].GetString(); + std::string lock = x["lock"].GetString(); + element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(frozen)).add(Decimal(lock))).toString()); + elementList.emplace_back(std::move(element)); + } + } break; + case Request::Operation::GET_ACCOUNT_POSITIONS: { + for (const auto& x : document["data"].GetArray()) { + Element element; + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_MARGIN_ASSET, x["marginCoin"].GetString()); + element.insert(CCAPI_EM_POSITION_SIDE, x["holdSide"].GetString()); + element.insert(CCAPI_EM_POSITION_QUANTITY, x["total"].GetString()); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["averageOpenPrice"].GetString()); + element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString()); + elementList.emplace_back(std::move(element)); + } + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + void extractOrderInfo(Element& element, const rj::Value& x, + const std::map >& extractionFieldNameMap) override { + ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap); + { + auto it1 = x.FindMember("accFillSz"); + auto it2 = x.FindMember("avgPx"); + if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) { + auto it1Str = std::string(it1->value.GetString()); + auto it2Str = std::string(it2->value.GetString()); + if (!it1Str.empty() && !it2Str.empty()) { + element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))); + } + } + } + } + std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, + const std::map& credential) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("login").Move(), allocator); + rj::Value arg(rj::kObjectType); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); + std::string ts = std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); + arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator); + arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator); + arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator); + std::string signData = ts + "GET" + "/user/verify"; + std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData)); + arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator); + rj::Value args(rj::kArrayType); + args.PushBack(arg, allocator); + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + const TimePoint& timeReceived) override { + if (textMessage != "pong") { + rj::Document document; + document.Parse(textMessage.c_str()); + auto it = document.FindMember("event"); + std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; + if (eventStr == "login") { + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + for (const auto& field : fieldSet) { + std::string channel; + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + channel = "orders"; + } + for (const auto& instrument : instrumentSet) { + rj::Value arg(rj::kObjectType); + arg.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator); + arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator); + arg.AddMember("instType", rj::Value("spbl").Move(), allocator); + args.PushBack(arg, allocator); + } + } + document.AddMember("args", args, allocator); + rj::StringBuffer stringBufferSubscribe; + rj::Writer writerSubscribe(stringBufferSubscribe); + document.Accept(writerSubscribe); + std::string sendString = stringBufferSubscribe.GetString(); + ErrorCode ec; + this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } else { + Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } + } + } + Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr, + const TimePoint& timeReceived) { + Event event; + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + const auto& correlationId = subscription.getCorrelationId(); + message.setCorrelationIdList({correlationId}); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + if (eventStr.empty()) { + const rj::Value& arg = document["arg"]; + std::string channel = std::string(arg["channel"].GetString()); + event.setType(Event::Type::SUBSCRIPTION_DATA); + std::string instrument = arg["instId"].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + if (channel == "orders") { + if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + const rj::Value& data = document["data"]; + for (const auto& x : data.GetArray()) { + auto itTradeId = x.FindMember("tradeId"); + std::string tradeId = itTradeId != x.MemberEnd() ? itTradeId->value.GetString() : ""; + if (!tradeId.empty()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + element.insert(CCAPI_TRADE_ID, tradeId); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString())); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0"); + element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString())); + element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString())); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString())); + element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString())); + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + const rj::Value& data = document["data"]; + for (const auto& x : data.GetArray()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)}, + }; + Element info; + this->extractOrderInfo(info, x, extractionFieldNameMap); + info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + } + } else if (eventStr == "subscribe") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } else if (eventStr == "error") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + event.setMessageList(messageList); + return event; + } + std::string getAllOpenOrdersTarget, getAccountAllPositionsTarget; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_FUTURES_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h new file mode 100644 index 000000000..a3b887bf6 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h @@ -0,0 +1,481 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMART_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMART_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#ifdef CCAPI_ENABLE_EXCHANGE_BITMART +#include "ccapi_cpp/service/ccapi_execution_management_service.h" +namespace ccapi { +class ExecutionManagementServiceBitmart : public ExecutionManagementService { + public: + ExecutionManagementServiceBitmart(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) + : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_BITMART; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/user?protocol=1.1"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_BITMART_API_KEY; + this->apiSecretName = CCAPI_BITMART_API_SECRET; + this->apiMemoName = CCAPI_BITMART_API_MEMO; + this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiMemoName}); + this->createOrderTarget = "/spot/v2/submit_order"; + this->cancelOrderTarget = "/spot/v3/cancel_order"; + this->getOrderTarget = "/spot/v2/order_detail"; + this->getOpenOrdersTarget = "/spot/v3/orders"; + this->cancelOpenOrdersTarget = "/spot/v1/cancel_orders"; + this->getAccountBalancesTarget = "/spot/v1/wallet"; + this->needDecompressWebsocketMessage = true; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + ErrorCode ec = this->inflater.init(false); +#else + ErrorCode ec = this->inflater.init(); +#endif + if (ec) { + CCAPI_LOGGER_FATAL(ec.message()); + } + } + virtual ~ExecutionManagementServiceBitmart() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + private: +#endif + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*1000")); } + void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, + std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, + const std::map& credential) override { + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("X-BM-TIMESTAMP").to_string(); + preSignedText += "#"; + preSignedText += mapGetWithDefault(credential, this->apiMemoName); + preSignedText += "#"; + std::string paramString; + if (methodString == "GET" || methodString == "DELETE") { + paramString = queryString; + } else if (methodString == "POST" || methodString == "PUT") { + paramString = body; + } + preSignedText += paramString; + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true); + if (!headerString.empty()) { + headerString += "\r\n"; + } + headerString += "X-BM-SIGN:" + signature; + } + void signRequest(http::request& req, const std::string& paramString, const std::map& credential) { + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("X-BM-TIMESTAMP").to_string(); + preSignedText += "#"; + preSignedText += mapGetWithDefault(credential, this->apiMemoName); + preSignedText += "#"; + preSignedText += paramString; + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true); + req.set("X-BM-SIGN", signature); + } + void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_SIDE, "side"}, + {CCAPI_EM_ORDER_QUANTITY, "size"}, + {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, + {CCAPI_EM_CLIENT_ORDER_ID, "client_order_id"}, + {CCAPI_SYMBOL_ID, "symbol"}, + {CCAPI_EM_ORDER_ID, "order_id"}, + }) { + for (const auto& kv : param) { + auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + auto value = kv.second; + if (key == "side") { + value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell"; + } + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); + } + } + void appendParam(std::string& queryString, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_ID, "order_id"}, + {CCAPI_LIMIT, "N"}, + }) { + for (const auto& kv : param) { + queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + queryString += "="; + queryString += Url::urlEncode(kv.second); + queryString += "&"; + } + } + void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) { + rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); + } + void appendSymbolId(std::string& queryString, const std::string& symbolId) { + queryString += "symbol="; + queryString += Url::urlEncode(symbolId); + queryString += "&"; + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + req.set(beast::http::field::content_type, "application/json"); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("X-BM-KEY", apiKey); + req.set("X-BM-TIMESTAMP", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); + Request::Operation operation = request.getOperation(); + switch (operation) { + case Request::Operation::GENERIC_PRIVATE_REQUEST: { + ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::CREATE_ORDER: { + req.method(http::verb::post); + req.target(this->createOrderTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (param.find("type") == param.end()) { + document.AddMember("type", rj::Value("limit").Move(), allocator); + } + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::CANCEL_ORDER: { + req.method(http::verb::post); + req.target(this->cancelOrderTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::GET_ORDER: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param); + if (queryString.back() == '&') { + queryString.pop_back(); + } + req.target(this->getOrderTarget + "?" + queryString); + this->signRequest(req, "", credential); + } break; + case Request::Operation::GET_OPEN_ORDERS: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param); + if (!symbolId.empty()) { + this->appendSymbolId(queryString, symbolId); + } + queryString += "&status=9"; + if (queryString.back() == '&') { + queryString.pop_back(); + } + req.target(queryString.empty() ? this->getOpenOrdersTarget : this->getOpenOrdersTarget + "?" + queryString); + this->signRequest(req, queryString, credential); + } break; + case Request::Operation::CANCEL_OPEN_ORDERS: { + req.method(http::verb::post); + req.target(this->cancelOpenOrdersTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, credential); + } break; + case Request::Operation::GET_ACCOUNT_BALANCES: { + req.method(http::verb::get); + req.target(this->getAccountBalancesTarget); + this->signRequest(req, "", credential); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled_size", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("filled_notional", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}}; + const rj::Value& data = document["data"]; + if (operation == Request::Operation::GET_OPEN_ORDERS) { + for (const auto& x : data["orders"].GetArray()) { + Element element; + this->extractOrderInfo(element, x, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } else if (operation == Request::Operation::CANCEL_OPEN_ORDERS) { + } else { + Element element; + this->extractOrderInfo(element, data, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } + void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + switch (request.getOperation()) { + case Request::Operation::GET_ACCOUNT_BALANCES: { + for (const auto& x : document["data"]["wallet"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ASSET, x["id"].GetString()); + std::string available = x["available"].GetString(); + std::string frozen = x["frozen"].GetString(); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, available); + element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(frozen))).toString()); + elementList.emplace_back(std::move(element)); + } + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, + const std::map& credential) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("login").Move(), allocator); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto timestamp = std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + std::string preSignedText = timestamp + "#" + mapGetWithDefault(credential, this->apiMemoName) + "#bitmart.WebSocket"; + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true); + rj::Value args(rj::kArrayType); + args.PushBack(rj::Value(apiKey.c_str(), allocator).Move(), allocator); + args.PushBack(rj::Value(timestamp.c_str(), allocator).Move(), allocator); + args.PushBack(rj::Value(signature.c_str(), allocator).Move(), allocator); + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + const TimePoint& timeReceived) override { + if (textMessage != "pong") { + rj::Document document; + document.Parse(textMessage.c_str()); + auto it = document.FindMember("errorCode"); + std::string errorCode = it != document.MemberEnd() ? it->value.GetString() : ""; + Event event; + const auto& correlationId = subscription.getCorrelationId(); + if (errorCode.empty()) { + auto it = document.FindMember("event"); + std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; + if (eventStr == "login") { + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + for (const auto& instrument : instrumentSet) { + std::string arg = "spot/user/order:" + instrument; + args.PushBack(rj::Value(arg.c_str(), allocator).Move(), allocator); + } + document.AddMember("args", args, allocator); + rj::StringBuffer stringBufferSubscribe; + rj::Writer writerSubscribe(stringBufferSubscribe); + document.Accept(writerSubscribe); + std::string sendString = stringBufferSubscribe.GetString(); + ErrorCode ec; + this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + // else { + // this->serviceContextPtr->tlsClientPtr->set_timer(1000, + // [wsConnection,correlationId,sendString,that=this](ErrorCode const& ec) { + // auto timeReceived=UtilTime::now(); + // if (ec) { + // that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + // } else { + // if (!that->subscriptionFailedByConnectionIdCorrelationIdMap[wsConnection.id][correlationId]){ + // Event event; + // event.setType(Event::Type::SUBSCRIPTION_STATUS); + // std::vector messageList; + // Message message; + // message.setTimeReceived(timeReceived); + // message.setCorrelationIdList({correlationId}); + // message.setType(Message::Type::SUBSCRIPTION_STARTED); + // Element element; + // element.insert(CCAPI_INFO_MESSAGE, sendString); + // message.setElementList({element}); + // messageList.emplace_back(std::move(message)); + // event.addMessages(messageList); + // that->eventHandler(event, nullptr); + // } + // } + // }); + // } + } else { + event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived); + } + } else { + std::string eventStr = document["event"].GetString(); + if (eventStr.rfind("spot/user/order:", 0) == 0) { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + message.setCorrelationIdList({correlationId}); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); + // this->subscriptionFailedByConnectionIdCorrelationIdMap[wsConnection.id][correlationId] = true; + } + } + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } + } + Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr, + const TimePoint& timeReceived) { + Event event; + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + const auto& correlationId = subscription.getCorrelationId(); + message.setCorrelationIdList({correlationId}); + const auto& fieldSet = subscription.getFieldSet(); + const rj::Value& data = document["data"]; + if (data.IsString() && std::string(data.GetString()).empty() || data.IsArray() && data.GetArray().Empty()) { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } else { + std::string table = std::string(document["table"].GetString()); + if (table == "spot/user/order") { + event.setType(Event::Type::SUBSCRIPTION_DATA); + for (const auto& x : data.GetArray()) { + std::string instrument = x["symbol"].GetString(); + const auto& instrumentSet = subscription.getInstrumentSet(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + const auto& itDetailId = x.FindMember("detail_id"); + if (itDetailId != x.MemberEnd() && !itDetailId->value.IsNull()) { + std::string tradeId = itDetailId->value.GetString(); + if (!tradeId.empty()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["last_fill_time"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + element.insert(CCAPI_TRADE_ID, tradeId); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["last_fill_price"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["last_fill_count"].GetString())); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_IS_MAKER, std::string(x["exec_type"].GetString()) == "M" ? "1" : "0"); + element.insert(CCAPI_EM_ORDER_ID, std::string(x["order_id"].GetString())); + const auto& itClientOrderId = x.FindMember("client_order_id"); + if (itClientOrderId != x.MemberEnd() && !itClientOrderId->value.IsNull()) { + element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(itClientOrderId->value.GetString())); + } + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["dealFee"].GetString())); + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["ms_t"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled_size", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("filled_notional", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)}, + }; + Element info; + this->extractOrderInfo(info, x, extractionFieldNameMap); + info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + } + } + event.setMessageList(messageList); + return event; + } + // void onClose(wspp::connection_hdl hdl) override { + // WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + // this->subscriptionFailedByConnectionIdCorrelationIdMap.erase(wsConnection.id); + // ExecutionManagementService::onClose(hdl); + // } + std::string apiMemoName; + // std::map> subscriptionFailedByConnectionIdCorrelationIdMap; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMART_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmex.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmex.h index 07cbb059e..a6614cca1 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmex.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmex.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BITMEX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BITMEX_API_KEY; this->apiSecretName = CCAPI_BITMEX_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -254,6 +263,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService { element.insert(CCAPI_EM_ASSET, x["currency"].GetString()); element.insert(CCAPI_EM_POSITION_QUANTITY, x["currentQty"].GetString()); element.insert(CCAPI_EM_POSITION_COST, x["openingCost"].GetString()); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgEntryPrice"].GetString()); element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString()); elementList.emplace_back(std::move(element)); } @@ -301,9 +311,11 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { if (textMessage != "pong") { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h index 188fd406e..14fd36058 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BITSTAMP; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BITSTAMP_API_KEY; this->apiSecretName = CCAPI_BITSTAMP_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -38,7 +47,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService { void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec); } - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("status": "error")") != std::string::npos || body.find(R"("status":"error")") != std::string::npos || body.find(R"("error":)") != std::string::npos; } @@ -299,7 +308,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService { if (document.HasMember("token") && document.HasMember("user_id")) { std::string token = document["token"].GetString(); std::string userId = document["user_id"].GetString(); - thisWsConnection.url = that->baseUrl; + thisWsConnection.url = that->baseUrlWs; that->connect(thisWsConnection); that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({ {"token", token}, @@ -347,8 +356,10 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService { } return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit.h index 4f5e7334c..85d8438d0 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit.h @@ -1,162 +1,163 @@ -#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_ -#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_ #ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT #ifdef CCAPI_ENABLE_EXCHANGE_BYBIT -#include "ccapi_cpp/service/ccapi_execution_management_service.h" +#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h" namespace ccapi { -class ExecutionManagementServiceBybit : public ExecutionManagementService { +class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBase { public: ExecutionManagementServiceBybit(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr) - : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + : ExecutionManagementServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/private/v3"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BYBIT_API_KEY; this->apiSecretName = CCAPI_BYBIT_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); - this->createOrderTarget = "/spot/v1/order"; - this->cancelOrderTarget = "/spot/v1/order/fast"; - this->getOrderTarget = "/spot/v1/order"; - this->getOpenOrdersTarget = "/spot/v1/open-orders"; - this->cancelOpenOrdersTarget = "/spot/v1/order/fast"; - this->getAccountBalancesTarget = "/spot/v1/account"; + this->createOrderTarget = "/spot/v3/private/order"; + this->cancelOrderTarget = "/spot/v3/private/cancel-order"; + this->getOrderTarget = "/spot/v3/private/order"; + this->getOpenOrdersTarget = "/spot/v3/private/open-orders"; + this->cancelOpenOrdersTarget = "/spot/v3/private/cancel-orders"; + this->getAccountBalancesTarget = "/spot/v3/private/account"; } virtual ~ExecutionManagementServiceBybit() {} #ifndef CCAPI_EXPOSE_INTERNAL protected: #endif - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } - void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, - std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, - const std::map& credential) override { - auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); - auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, queryString, true); - queryString += "&signature="; - queryString += signature; - } - void signRequest(std::string& queryString, const std::map& param, const TimePoint& now, - const std::map& credential) { - if (param.find("timestamp") == param.end()) { - queryString += "timestamp="; - queryString += std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); - queryString += "&"; - } - if (queryString.back() == '&') { - queryString.pop_back(); - } - auto queryMap = Url::convertQueryStringToMap(queryString); - auto queryString = Url::convertMapToQueryString(queryMap); - auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); - auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, queryString, true); - queryString += "&sign="; - queryString += signature; - } - void appendParam(std::string& queryString, const std::map& param, - const std::map standardizationMap = {}) { + void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_SIDE, "side"}, + {CCAPI_EM_ORDER_QUANTITY, "orderQty"}, + {CCAPI_EM_ORDER_LIMIT_PRICE, "orderPrice"}, + {CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"}, + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_LIMIT, "limit"}, + }) { for (const auto& kv : param) { - queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; - queryString += "="; - queryString += Url::urlEncode(kv.second); - queryString += "&"; + auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + auto value = kv.second; + if (key == "side") { + value = value == CCAPI_EM_ORDER_SIDE_BUY ? "Buy" : "Sell"; + } + if (value != "null") { + if (key == "orderCategory") { + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), std::stoi(value), allocator); + } else { + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); + } + } } } - void appendSymbolId(std::string& queryString, const std::string& symbolId) { - queryString += "symbol="; - queryString += Url::urlEncode(symbolId); - queryString += "&"; - } - void prepareReq(http::request& req, const TimePoint& now, const std::map& credential) { - auto apiKey = mapGetWithDefault(credential, this->apiKeyName); - req.set("api_key", apiKey); - req.set("timestamp", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); - } void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& credential) override { - this->prepareReq(req, credential); + this->prepareReq(req, now, credential); switch (request.getOperation()) { case Request::Operation::GENERIC_PRIVATE_REQUEST: { ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); } break; case Request::Operation::CREATE_ORDER: { req.method(http::verb::post); - std::string queryString; + req.set(beast::http::field::content_type, "application/json"); const std::map param = request.getFirstParamWithDefault(); - this->appendParam(queryString, param, - { - {CCAPI_EM_ORDER_SIDE, "side"}, - {CCAPI_EM_ORDER_QUANTITY, "qty"}, - {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, - {CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"}, - }); - this->appendSymbolId(queryString, symbolId); - if (param.find("type") == param.end()) { - queryString += "type=LIMIT&"; - if (param.find("timeInForce") == param.end()) { - queryString += "timeInForce=GTC&"; - } + req.target(this->createOrderTarget); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(document, allocator, param); + if (param.find("orderType") == param.end()) { + document.AddMember("orderType", rj::Value("LIMIT").Move(), allocator); } - this->signRequest(queryString, param, now, credential); - req.target(std::string(this->createOrderTarget)); - req.set(beast::http::field::content_type, "application/x-www-form-urlencoded; charset=utf-8"); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId, "symbol"); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, now, credential); } break; case Request::Operation::CANCEL_ORDER: { - req.method(http::verb::delete_); - std::string queryString; + req.method(http::verb::post); + req.set(beast::http::field::content_type, "application/json"); const std::map param = request.getFirstParamWithDefault(); - this->appendParam(queryString, param, - { - {CCAPI_EM_ORDER_ID, "orderId"}, - {CCAPI_EM_CLIENT_ORDER_ID, "origClientOrderId"}, - }); - this->appendSymbolId(queryString, symbolId); - this->signRequest(queryString, param, now, credential); - req.target(this->cancelOrderTarget + "?" + queryString); + req.target(this->cancelOrderTarget); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(document, allocator, param); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, now, credential); } break; case Request::Operation::GET_ORDER: { req.method(http::verb::get); std::string queryString; const std::map param = request.getFirstParamWithDefault(); - this->appendParam(queryString, param, - { - {CCAPI_EM_ORDER_ID, "orderId"}, - {CCAPI_EM_CLIENT_ORDER_ID, "origClientOrderId"}, - }); - this->appendSymbolId(queryString, symbolId); - this->signRequest(queryString, param, now, credential); + this->appendParamToQueryString(queryString, param); req.target(this->getOrderTarget + "?" + queryString); + this->signRequest(req, queryString, now, credential); } break; case Request::Operation::GET_OPEN_ORDERS: { req.method(http::verb::get); std::string queryString; - this->appendParam(queryString, {}); + const std::map param = request.getFirstParamWithDefault(); + this->appendParamToQueryString(queryString, param); if (!symbolId.empty()) { - this->appendSymbolId(queryString, symbolId); + this->appendSymbolId(queryString, symbolId, "symbol"); } - this->signRequest(queryString, {}, now, credential); req.target(this->getOpenOrdersTarget + "?" + queryString); + this->signRequest(req, queryString, now, credential); } break; case Request::Operation::CANCEL_OPEN_ORDERS: { - req.method(http::verb::delete_); - std::string queryString; - this->appendParam(queryString, {}); - this->appendSymbolId(queryString, symbolId); - this->signRequest(queryString, {}, now, credential); - req.target(this->cancelOpenOrdersTarget + "?" + queryString); + req.method(http::verb::post); + req.set(beast::http::field::content_type, "application/json"); + const std::map param = request.getFirstParamWithDefault(); + req.target(this->cancelOpenOrdersTarget); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId, "symbol"); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, now, credential); } break; case Request::Operation::GET_ACCOUNT_BALANCES: { req.method(http::verb::get); std::string queryString; - this->appendParam(queryString, {}); - this->signRequest(queryString, {}, now, credential); - req.target(this->getAccountBalancesTarget + "?" + queryString); + this->appendParamToQueryString(queryString, {}); + req.target(this->getAccountBalancesTarget); + this->signRequest(req, queryString, now, credential); } break; default: this->convertRequestForRestCustom(req, request, now, symbolId, credential); @@ -165,45 +166,37 @@ class ExecutionManagementServiceBybit : public ExecutionManagementService { void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { std::map > extractionFieldNameMap = { - {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::INTEGER)}, + {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)}, {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("origQty", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("executedQty", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair(this->isDerivatives ? "cumQuote" : "cummulativeQuoteQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("orderPrice", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("execQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cummulativeQuoteQty", JsonDataType::STRING)}, {CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)}, {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, }; - if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) { - extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("origClientOrderId", JsonDataType::STRING)}); - } else { - extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOrderId", JsonDataType::STRING)}); - } - if (document.IsObject()) { - Element element; - this->extractOrderInfo(element, document, extractionFieldNameMap); - elementList.emplace_back(std::move(element)); - } else { - for (const auto& x : document.GetArray()) { + if (operation == Request::Operation::GET_OPEN_ORDERS) { + for (const auto& x : document["result"]["list"].GetArray()) { Element element; this->extractOrderInfo(element, x, extractionFieldNameMap); elementList.emplace_back(std::move(element)); } + } else if (operation != Request::Operation::CANCEL_OPEN_ORDERS) { + Element element; + this->extractOrderInfo(element, document["result"], extractionFieldNameMap); + elementList.emplace_back(std::move(element)); } } void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { switch (request.getOperation()) { case Request::Operation::GET_ACCOUNT_BALANCES: { - for (const auto& x : document[this->isDerivatives ? "assets" : "balances"].GetArray()) { + for (const auto& x : document["result"]["balances"].GetArray()) { Element element; - element.insert(CCAPI_EM_ASSET, x["asset"].GetString()); - if (this->isDerivatives) { - element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString()); - } else { - element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString()); - } - element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x[this->isDerivatives ? "availableBalance" : "free"].GetString()); + element.insert(CCAPI_EM_ASSET, x["coin"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, x["total"].GetString()); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString()); elementList.emplace_back(std::move(element)); } } break; @@ -211,124 +204,8 @@ class ExecutionManagementServiceBybit : public ExecutionManagementService { CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } } - void prepareConnect(WsConnection& wsConnection) override { - auto hostPort = this->extractHostFromUrl(this->baseUrlRest); - std::string host = hostPort.first; - std::string port = hostPort.second; - http::request req; - req.set(http::field::host, host); - req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); - req.method(http::verb::post); - std::string target = this->listenKeyTarget; - if (this->listenKeyTarget == "/sapi/v1/userDataStream/isolated") { - auto symbol = wsConnection.subscriptionList.at(0).getInstrument(); - target += "?" + symbol; - } - req.target(target); - auto credential = wsConnection.subscriptionList.at(0).getCredential(); - if (credential.empty()) { - credential = this->credentialDefault; - } - auto apiKey = mapGetWithDefault(credential, this->apiKeyName); - req.set("X-MBX-APIKEY", apiKey); - this->sendRequest( - req, - [wsConnection, that = shared_from_base()](const beast::error_code& ec) { - WsConnection thisWsConnection = wsConnection; - that->onFail_(thisWsConnection); - }, - [wsConnection, that = shared_from_base()](const http::response& res) { - WsConnection thisWsConnection = wsConnection; - int statusCode = res.result_int(); - std::string body = res.body(); - if (statusCode / 100 == 2) { - std::string urlWebsocketBase; - try { - rj::Document document; - document.Parse(body.c_str()); - std::string listenKey = document["listenKey"].GetString(); - std::string url = that->baseUrl + "/" + listenKey; - thisWsConnection.url = url; - that->connect(thisWsConnection); - that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({ - {"listenKey", listenKey}, - }); - return; - } catch (const std::runtime_error& e) { - CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); - } - } - that->onFail_(thisWsConnection); - }, - this->sessionOptions.httpRequestTimeoutMilliSeconds); - } - void onOpen(wspp::connection_hdl hdl) override { - ExecutionManagementService::onOpen(hdl); - auto now = UtilTime::now(); - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - Event event; - event.setType(Event::Type::SUBSCRIPTION_STATUS); - Message message; - message.setTimeReceived(now); - message.setType(Message::Type::SUBSCRIPTION_STARTED); - event.setMessageList({message}); - this->eventHandler(event, nullptr); - this->pingListenKeyTimerMapByConnectionIdMap[wsConnection.id] = this->serviceContextPtr->tlsClientPtr->set_timer( - this->pingListenKeyIntervalSeconds * 1000, [wsConnection, that = shared_from_base()](ErrorCode const& ec) { - http::request req; - req.set(http::field::host, that->hostRest); - req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); - req.method(http::verb::put); - std::string target = that->listenKeyTarget; - if (!that->isDerivatives) { - std::map params; - auto listenKey = that->extraPropertyByConnectionIdMap.at(wsConnection.id).at("listenKey"); - params.insert({"listenKey", listenKey}); - if (that->listenKeyTarget == "/sapi/v1/userDataStream/isolated") { - auto symbol = wsConnection.subscriptionList.at(0).getInstrument(); - params.insert({"symbol", symbol}); - } - target += "?"; - for (const auto& param : params) { - target += param.first + "=" + Url::urlEncode(param.second); - target += "&"; - } - } - req.target(target); - auto credential = wsConnection.subscriptionList.at(0).getCredential(); - if (credential.empty()) { - credential = that->credentialDefault; - } - auto apiKey = mapGetWithDefault(credential, that->apiKeyName); - req.set("X-MBX-APIKEY", apiKey); - that->sendRequest( - req, - [wsConnection, that_2 = that->shared_from_base()](const beast::error_code& ec) { - CCAPI_LOGGER_ERROR("ping listen key fail"); - that_2->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping listen key"); - }, - [wsConnection, that_2 = that->shared_from_base()](const http::response& res) { - CCAPI_LOGGER_DEBUG("ping listen key success"); - }, - that->sessionOptions.httpRequestTimeoutMilliSeconds); - }); - } - void onClose(wspp::connection_hdl hdl) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - if (this->pingListenKeyTimerMapByConnectionIdMap.find(wsConnection.id) != this->pingListenKeyTimerMapByConnectionIdMap.end()) { - this->pingListenKeyTimerMapByConnectionIdMap.at(wsConnection.id)->cancel(); - this->pingListenKeyTimerMapByConnectionIdMap.erase(wsConnection.id); - } - ExecutionManagementService::onClose(hdl); - } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, - const TimePoint& timeReceived) override { - Event event = this->createEvent(subscription, textMessage, document, timeReceived); - if (!event.getMessageList().empty()) { - this->eventHandler(event, nullptr); - } - } - Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const TimePoint& timeReceived) { + Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + const TimePoint& timeReceived) override { Event event; std::vector messageList; Message message; @@ -336,77 +213,121 @@ class ExecutionManagementServiceBybit : public ExecutionManagementService { message.setCorrelationIdList({subscription.getCorrelationId()}); const auto& fieldSet = subscription.getFieldSet(); const auto& instrumentSet = subscription.getInstrumentSet(); - std::string type = document["e"].GetString(); - if (type == (this->isDerivatives ? "ORDER_TRADE_UPDATE" : "executionReport")) { - event.setType(Event::Type::SUBSCRIPTION_DATA); - const rj::Value& data = this->isDerivatives ? document["o"] : document; - std::string executionType = data["x"].GetString(); - std::string instrument = data["s"].GetString(); - if (instrumentSet.empty() || instrumentSet.find(UtilString::toUpper(instrument)) != instrumentSet.end() || - instrumentSet.find(UtilString::toLower(instrument)) != instrumentSet.end()) { - message.setTime(TimePoint(std::chrono::milliseconds(std::stoll((this->isDerivatives ? document : data)["E"].GetString())))); - if (executionType == "TRADE" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); - std::vector elementList; - Element element; - element.insert(CCAPI_TRADE_ID, std::string(data["t"].GetString())); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(data["L"].GetString())); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(data["l"].GetString())); - element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["S"].GetString()) == "BUY" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); - element.insert(CCAPI_IS_MAKER, data["m"].GetBool() ? "1" : "0"); - element.insert(CCAPI_EM_ORDER_ID, std::string(data["i"].GetString())); - element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - { - auto it = data.FindMember("n"); - if (it != data.MemberEnd() && !it->value.IsNull()) { - element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString())); + if (document.HasMember("topic")) { + std::string topic = document["topic"].GetString(); + if (topic == "order") { + event.setType(Event::Type::SUBSCRIPTION_DATA); + const rj::Value& data = document["data"]; + for (const auto& x : data.GetArray()) { + std::string instrument = x["s"].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["E"].GetString()))); + auto itTradeId = x.FindMember("t"); + if (itTradeId != x.MemberEnd() && !itTradeId->value.IsNull() && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(time); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + element.insert(CCAPI_TRADE_ID, itTradeId->value.GetString()); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["L"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["l"].GetString())); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["S"].GetString()) == "BUY" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_IS_MAKER, x["m"].GetBool() ? "1" : "0"); + element.insert(CCAPI_EM_ORDER_ID, std::string(x["i"].GetString())); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + { + auto it = x.FindMember("n"); + if (it != x.MemberEnd() && !it->value.IsNull()) { + element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString())); + } + } + { + auto it = x.FindMember("N"); + if (it != x.MemberEnd() && !it->value.IsNull()) { + element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(it->value.GetString())); + } + } + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(time); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("i", JsonDataType::INTEGER)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("c", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("S", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("q", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("z", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("Z", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("X", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("s", JsonDataType::STRING)}, + }; + Element info; + this->extractOrderInfo(info, x, extractionFieldNameMap); + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); } } - { - auto it = data.FindMember("N"); - if (it != data.MemberEnd() && !it->value.IsNull()) { - element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(it->value.GetString())); - } - } - elementList.emplace_back(std::move(element)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } else if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); - const std::map >& extractionFieldNameMap = { - {CCAPI_EM_ORDER_ID, std::make_pair("i", JsonDataType::INTEGER)}, - {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("c", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_SIDE, std::make_pair("S", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("q", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("z", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("Z", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_STATUS, std::make_pair("X", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("s", JsonDataType::STRING)}, - }; - Element info; - this->extractOrderInfo(info, data, extractionFieldNameMap); - auto it = data.FindMember("ap"); - if (it != data.MemberEnd() && !it->value.IsNull()) { - info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, - std::to_string(std::stod(it->value.GetString()) * std::stod(data["z"].GetString()))); - } - std::vector elementList; - elementList.emplace_back(std::move(info)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); } } + } else if (document.HasMember("op")) { + std::string op = document["op"].GetString(); + if (op == "auth") { + bool success = document["success"].GetBool(); + if (success) { + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + args.PushBack(rj::Value("order").Move(), allocator); + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + ErrorCode ec; + this->send(hdl, sendString, wspp::frame::opcode::text, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } + } else if (op == "subscribe") { + bool success = document["success"].GetBool(); + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + } else if (document.HasMember("ret_code")) { + std::string ret_code = document["ret_code"].GetString(); + if (ret_code != "0") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } } event.setMessageList(messageList); return event; } - bool isDerivatives{}; - std::string listenKeyTarget; - int pingListenKeyIntervalSeconds; - std::map pingListenKeyTimerMapByConnectionIdMap; }; } /* namespace ccapi */ #endif #endif -#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_ +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h new file mode 100644 index 000000000..b51c8a8c3 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h @@ -0,0 +1,118 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#if defined(CCAPI_ENABLE_EXCHANGE_BYBIT) || defined(CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES) +#include "ccapi_cpp/service/ccapi_execution_management_service.h" +namespace ccapi { +class ExecutionManagementServiceBybitBase : public ExecutionManagementService { + public: + ExecutionManagementServiceBybitBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) + : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {} + virtual ~ExecutionManagementServiceBybitBase() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } + void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, + std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, + const std::map& credential) override { + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string(); + preSignedText += apiKey; + preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string(); + std::string aString; + if (methodString == "GET") { + aString = queryString; + } else if (methodString == "POST") { + aString = body; + } + preSignedText += aString; + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true); + req.set("X-BAPI-SIGN", signature); + } + void signRequest(http::request& req, const std::string aString, const TimePoint& now, + const std::map& credential) { + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string(); + preSignedText += apiKey; + preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string(); + preSignedText += aString; + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true); + req.set("X-BAPI-SIGN", signature); + } + void appendParamToQueryString(std::string& queryString, const std::map& param, + const std::map standardizationMap = {}) { + for (const auto& kv : param) { + queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + queryString += "="; + queryString += Url::urlEncode(kv.second); + queryString += "&"; + } + } + // void appendSymbolId(std::string& queryString, const std::string& symbolId) { + // queryString += "symbol="; + // queryString += Url::urlEncode(symbolId); + // queryString += "&"; + // } + // void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) { + // rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); + // } + void prepareReq(http::request& req, const TimePoint& now, const std::map& credential) { + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("X-BAPI-SIGN-TYPE", "2"); + req.set("X-BAPI-API-KEY", apiKey); + req.set("X-BAPI-TIMESTAMP", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); + req.set("X-BAPI-RECV-WINDOW", std::to_string(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS)); + req.set("Referer", CCAPI_BYBIT_API_BROKER_ID); + } + std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, + const std::map& credential) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("auth").Move(), allocator); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto expires = std::chrono::duration_cast( + (now + std::chrono::milliseconds(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS)).time_since_epoch()) + .count(); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + std::string preSignedText = "GET"; + preSignedText += "/realtime"; + preSignedText += std::to_string(expires); + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true); + rj::Value args(rj::kArrayType); + args.PushBack(rj::Value(apiKey.c_str(), allocator).Move(), allocator); + args.PushBack(rj::Value(expires).Move(), allocator); + args.PushBack(rj::Value(signature.c_str(), allocator).Move(), allocator); + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + virtual Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + const TimePoint& timeReceived) { + return {}; + } + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_derivatives.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_derivatives.h new file mode 100644 index 000000000..603be4e3b --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_derivatives.h @@ -0,0 +1,379 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES +#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h" +namespace ccapi { +class ExecutionManagementServiceBybitDerivatives : public ExecutionManagementServiceBybitBase { + public: + ExecutionManagementServiceBybitDerivatives(std::function*)> eventHandler, SessionOptions sessionOptions, + SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr) + : ExecutionManagementServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/unified/private/v3"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_BYBIT_DERIVATIVES_API_KEY; + this->apiSecretName = CCAPI_BYBIT_DERIVATIVES_API_SECRET; + this->setupCredential({this->apiKeyName, this->apiSecretName}); + this->createOrderTarget = "/unified/v3/private/order/create"; + this->cancelOrderTarget = "/unified/v3/private/order/cancel"; + this->getOrderTarget = "/unified/v3/private/order/list"; + this->getOpenOrdersTarget = "/unified/v3/private/order/unfilled-orders"; + this->cancelOpenOrdersTarget = "/unified/v3/private/order/cancel-all"; + this->getAccountBalancesTarget = "/unified/v3/private/account/wallet/balance"; + this->getAccountPositionsTarget = "/unified/v3/private/position/list"; + } + virtual ~ExecutionManagementServiceBybitDerivatives() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_SIDE, "side"}, + {CCAPI_EM_ORDER_QUANTITY, "qty"}, + {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, + {CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"}, + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_LIMIT, "limit"}, + {CCAPI_INSTRUMENT_TYPE, "category"}, + }) { + for (const auto& kv : param) { + auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + auto value = kv.second; + if (key == "side") { + value = value == CCAPI_EM_ORDER_SIDE_BUY ? "Buy" : "Sell"; + } + if (value != "null") { + if (key == "reduceOnly" || key == "closeOnTrigger" || key == "mmp") { + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator); + } else { + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); + } + } + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + this->prepareReq(req, now, credential); + switch (request.getOperation()) { + case Request::Operation::GENERIC_PRIVATE_REQUEST: { + ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::CREATE_ORDER: { + req.method(http::verb::post); + req.set(beast::http::field::content_type, "application/json"); + const std::map param = request.getFirstParamWithDefault(); + req.target(this->createOrderTarget); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(document, allocator, param); + if (param.find("orderType") == param.end()) { + document.AddMember("orderType", rj::Value("Limit").Move(), allocator); + } + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId, "symbol"); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, now, credential); + } break; + case Request::Operation::CANCEL_ORDER: { + req.method(http::verb::post); + req.set(beast::http::field::content_type, "application/json"); + const std::map param = request.getFirstParamWithDefault(); + req.target(this->cancelOrderTarget); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(document, allocator, param); + this->appendSymbolId(document, allocator, symbolId, "symbol"); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, now, credential); + } break; + case Request::Operation::GET_ORDER: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParamToQueryString(queryString, param, + { + {CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"}, + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_LIMIT, "limit"}, + {CCAPI_INSTRUMENT_TYPE, "category"}, + }); + req.target(this->getOrderTarget + "?" + queryString); + this->signRequest(req, queryString, now, credential); + } break; + case Request::Operation::GET_OPEN_ORDERS: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParamToQueryString(queryString, param, + { + {CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"}, + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_LIMIT, "limit"}, + {CCAPI_INSTRUMENT_TYPE, "category"}, + }); + if (!symbolId.empty()) { + this->appendSymbolId(queryString, symbolId, "symbol"); + } + req.target(this->getOpenOrdersTarget + "?" + queryString); + this->signRequest(req, queryString, now, credential); + } break; + case Request::Operation::CANCEL_OPEN_ORDERS: { + req.method(http::verb::post); + req.set(beast::http::field::content_type, "application/json"); + const std::map param = request.getFirstParamWithDefault(); + req.target(this->cancelOpenOrdersTarget); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(document, allocator, param); + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId, "symbol"); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, now, credential); + } break; + case Request::Operation::GET_ACCOUNT_BALANCES: { + req.method(http::verb::get); + std::string queryString; + this->appendParamToQueryString(queryString, {}); + req.target(queryString.empty() ? this->getAccountBalancesTarget : this->getAccountBalancesTarget + "?" + queryString); + this->signRequest(req, queryString, now, credential); + } break; + case Request::Operation::GET_ACCOUNT_POSITIONS: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParamToQueryString(queryString, param); + req.target(this->getAccountPositionsTarget + "?" + queryString); + this->signRequest(req, queryString, now, credential); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + std::map > extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("leavesQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, + }; + if (operation == Request::Operation::GET_ORDER || operation == Request::Operation::GET_OPEN_ORDERS || operation == Request::Operation::CANCEL_OPEN_ORDERS) { + for (const auto& x : document["result"]["list"].GetArray()) { + Element element; + this->extractOrderInfo(element, x, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } else { + Element element; + this->extractOrderInfo(element, document["result"], extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } + void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + switch (request.getOperation()) { + case Request::Operation::GET_ACCOUNT_BALANCES: { + for (const auto& x : document["result"]["coin"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ASSET, x["currencyCoin"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString()); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString()); + elementList.emplace_back(std::move(element)); + } + } break; + case Request::Operation::GET_ACCOUNT_POSITIONS: { + for (const auto& x : document["result"]["list"].GetArray()) { + Element element; + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString()); + element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString()); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString()); + element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString()); + elementList.emplace_back(std::move(element)); + } + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + const TimePoint& timeReceived) override { + Event event; + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + if (document.HasMember("topic")) { + std::string topic = document["topic"].GetString(); + if (topic == "user.order.unifiedAccount") { + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + event.setType(Event::Type::SUBSCRIPTION_DATA); + const rj::Value& data = document["data"]["result"]; + for (const auto& x : data.GetArray()) { + std::string instrument = x["symbol"].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["updatedTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::INTEGER)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, + }; + Element info; + this->extractOrderInfo(info, x, extractionFieldNameMap); + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + } else if (topic == "user.execution.unifiedAccount") { + if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + event.setType(Event::Type::SUBSCRIPTION_DATA); + const rj::Value& data = document["data"]["result"]; + for (const auto& x : data.GetArray()) { + std::string execType = x["execType"].GetString(); + if (execType == "TRADE") { + std::string instrument = x["symbol"].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["execTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + element.insert(CCAPI_TRADE_ID, x["execId"].GetString()); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["execPrice"].GetString()); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["execQty"].GetString()); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "Buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_IS_MAKER, std::string(x["lastLiquidityInd"].GetString()) == "MAKER" ? "1" : "0"); + element.insert(CCAPI_EM_ORDER_ID, x["orderId"].GetString()); + element.insert(CCAPI_EM_CLIENT_ORDER_ID, x["orderLinkId"].GetString()); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + { + auto it = x.FindMember("execFee"); + if (it != x.MemberEnd() && !it->value.IsNull()) { + element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString())); + } + } + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + } + } + } else if (document.HasMember("type")) { + std::string type = document["type"].GetString(); + if (type == "AUTH_RESP") { + bool success = document["success"].GetBool(); + if (success) { + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + for (const auto& field : subscription.getFieldSet()) { + std::string channelId; + if (field == CCAPI_EM_ORDER_UPDATE) { + channelId = "user.order.unifiedAccount"; + } else if (field == CCAPI_EM_PRIVATE_TRADE) { + channelId = "user.execution.unifiedAccount"; + } + args.PushBack(rj::Value(channelId.c_str(), allocator).Move(), allocator); + } + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + ErrorCode ec; + this->send(hdl, sendString, wspp::frame::opcode::text, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } + } else if (type == "COMMAND_RESP") { + bool success = document["success"].GetBool(); + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + } else if (document.HasMember("ret_code")) { + std::string ret_code = document["ret_code"].GetString(); + if (ret_code != "0") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + } + event.setMessageList(messageList); + return event; + } +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_coinbase.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_coinbase.h index ed2d189b5..827e34df9 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_coinbase.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_coinbase.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_COINBASE; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_COINBASE_API_KEY; this->apiSecretName = CCAPI_COINBASE_API_SECRET; this->apiPassphraseName = CCAPI_COINBASE_API_PASSPHRASE; @@ -284,8 +293,20 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, - const TimePoint& timeReceived) override { + void onTextMessage( +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage +#else + std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView +#endif + , + const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + std::string textMessage(textMessageView); +#endif + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h index 862eb7c41..8410f7222 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_CRYPTOCOM; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/user"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/user"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_CRYPTOCOM_API_KEY; this->apiSecretName = CCAPI_CRYPTOCOM_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -322,8 +331,10 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService { sendStringList.push_back(body); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(wsConnection, subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); @@ -452,14 +463,12 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService { } } } else if (method == "public/heartbeat") { - if (itCode == document.MemberEnd()) { - std::string id = document["id"].GetString(); - std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})"; - ErrorCode ec; - this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec); - if (ec) { - this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); - } + std::string id = document["id"].GetString(); + std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})"; + ErrorCode ec; + this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec); + if (ec) { + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); } } else if (method == "public/auth") { if (itCode != document.MemberEnd()) { diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_deribit.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_deribit.h index 1a5fabebb..70be1f325 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_deribit.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_deribit.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_DERIBIT; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->clientIdName = CCAPI_DERIBIT_CLIENT_ID; this->clientSecretName = CCAPI_DERIBIT_CLIENT_SECRET; this->setupCredential({this->clientIdName, this->clientSecretName}); @@ -263,8 +272,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { Element element; element.insert(CCAPI_INSTRUMENT, x["instrument_name"].GetString()); element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString()); - element.insert(CCAPI_EM_POSITION_COST, - std::to_string(std::stod(x["average_price"].GetString()) * std::stod(x["size"].GetString()) / std::stod(x["leverage"].GetString()))); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["average_price"].GetString()); element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString()); elementList.emplace_back(std::move(element)); } @@ -314,8 +322,10 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(wsConnection, subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_erisx.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_erisx.h index c18611ebd..c50384802 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_erisx.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_erisx.h @@ -11,13 +11,23 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_ERISX; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_ERISX_API_KEY; this->apiSecretName = CCAPI_ERISX_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -33,7 +43,7 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService { private: #endif - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { + bool doesHttpBodyContainError(const std::string& body) override { return body.find("\"ordStatus\":\"REJECTED\"") != std::string::npos || body.find("\"message\":\"Rejected with reason NO RESTING ORDERS\"") != std::string::npos; } diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx.h index 71a583a85..b9d225216 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceFtx : public ExecutionManagementServiceFtxBase { ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_FTX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_FTX_API_KEY; this->apiSecretName = CCAPI_FTX_API_SECRET; this->apiSubaccountName = CCAPI_FTX_API_SUBACCOUNT; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h index e755567e8..361097a53 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h @@ -133,12 +133,18 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService { case Request::Operation::CANCEL_ORDER: { req.method(http::verb::delete_); const std::map param = request.getFirstParamWithDefault(); - auto shouldUseOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end(); + bool shouldUseOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end(); std::string id = param.find(CCAPI_EM_ORDER_ID) != param.end() ? param.at(CCAPI_EM_ORDER_ID) : param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? param.at(CCAPI_EM_CLIENT_ORDER_ID) : ""; req.target(shouldUseOrderId ? this->cancelOrderTarget + "/" + id : this->cancelOrderTarget + "/by_client_id/" + id); - this->signRequest(req, "", credential); + std::string body; + if (!shouldUseOrderId && !symbolId.empty()) { + body = R"({"market":")"; + body += symbolId; + body += R"("})"; + } + this->signRequest(req, body, credential); } break; case Request::Operation::GET_ORDER: { req.method(http::verb::get); @@ -312,8 +318,10 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService { } return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h index 7ed37b87c..422bb5952 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceFtxUs : public ExecutionManagementServiceFtxBase ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_FTX_US; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_FTX_US_API_KEY; this->apiSecretName = CCAPI_FTX_US_API_SECRET; this->apiSubaccountName = CCAPI_FTX_US_API_SUBACCOUNT; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio.h index 489808ec1..aebaae744 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceGateio : public ExecutionManagementServiceGateio ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_GATEIO_API_KEY; this->apiSecretName = CCAPI_GATEIO_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h index 4a96acc60..c794f5cb3 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h @@ -14,6 +14,12 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService { protected: #endif + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { + auto now = UtilTime::now(); + this->send(hdl, + "{\"time\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"channel\":\"" + (this->isDerivatives ? "futures" : "spot") + ".ping\"}", + wspp::frame::opcode::text, ec); + } void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, const std::map& credential) override { @@ -128,6 +134,7 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService { ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); } break; case Request::Operation::CREATE_ORDER: { + req.set("X-Gate-Channel-Id", CCAPI_GATEIO_API_CHANNEL_ID); req.method(http::verb::post); const std::map param = request.getFirstParamWithDefault(); rj::Document document; @@ -257,6 +264,8 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService { Element element; element.insert(CCAPI_EM_ASSET, x["currency"].GetString()); element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].GetString()); + float total = std::stof(x["locked"].GetString()) + std::stof(x["available"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, std::to_string(total)); elementList.emplace_back(std::move(element)); } } break; @@ -334,8 +343,10 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService { } return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h index aef61e729..09a799947 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY; this->apiSecretName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -75,7 +84,7 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem } void subscribe(std::vector& subscriptionList) override { CCAPI_LOGGER_FUNCTION_ENTER; - CCAPI_LOGGER_DEBUG("this->baseUrl = " + this->baseUrl); + CCAPI_LOGGER_DEBUG("this->baseUrlWs = " + this->baseUrlWs); if (this->shouldContinue.load()) { for (auto& subscription : subscriptionList) { wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), @@ -92,7 +101,11 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem } else if (UtilString::endsWith(symbolId, "_USDT")) { settle = "usdt"; } - WsConnection wsConnection(that->baseUrl + settle, "", {subscription}); + auto credential = subscription.getCredential(); + if (credential.empty()) { + credential = that->credentialDefault; + } + WsConnection wsConnection(that->baseUrlWs + settle, "", {subscription}, credential); that->prepareConnect(wsConnection); } }); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gemini.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gemini.h index 3a0b2ceb2..6fff3bfb8 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gemini.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gemini.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_GEMINI; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/order/events"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/order/events"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_GEMINI_API_KEY; this->apiSecretName = CCAPI_GEMINI_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -294,8 +303,10 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService { wsConnection.headers.insert({"X-GEMINI-SIGNATURE", signature}); this->connect(wsConnection); } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi.h index a1b33fc1b..932a5b16c 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v2"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v2"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_HUOBI_API_KEY; this->apiSecretName = CCAPI_HUOBI_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -36,7 +45,7 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa private: #endif - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find("err-code") != std::string::npos; } + bool doesHttpBodyContainError(const std::string& body) override { return body.find("err-code") != std::string::npos; } void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) { ExecutionManagementServiceHuobiBase::appendSymbolId(document, allocator, symbolId, "symbol"); } @@ -183,6 +192,10 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa } else if (data.IsObject()) { Element element; this->extractOrderInfo(element, data, extractionFieldNameMap); + if (operation == Request::Operation::GET_ORDER) { + element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::string(data["field-amount"].GetString())); + element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::string(data["field-cash-amount"].GetString())); + } elementList.emplace_back(std::move(element)); } else { for (const auto& x : data.GetArray()) { @@ -252,8 +265,10 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); std::string actionStr = document["action"].GetString(); const auto& fieldSet = subscription.getFieldSet(); const auto& instrumentSet = subscription.getInstrumentSet(); @@ -275,9 +290,9 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa auto& allocator = document.GetAllocator(); document.AddMember("action", rj::Value("sub").Move(), allocator); std::string ch; - if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + if (field == CCAPI_EM_ORDER_UPDATE) { ch = "orders#" + symbol; - } else if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + } else if (field == CCAPI_EM_PRIVATE_TRADE) { ch = "trade.clearing#" + symbol; } document.AddMember("ch", rj::Value(ch.c_str(), allocator).Move(), allocator); @@ -359,6 +374,11 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa std::string dataEventType = data["eventType"].GetString(); if (dataEventType == "trigger" || dataEventType == "deletion") { info.insert(CCAPI_EM_ORDER_SIDE, std::string(data["orderSide"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + } else if (dataEventType == "trade") { + info.insert(CCAPI_TRADE_ID, std::string(data["tradeId"].GetString())); + info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["tradePrice"].GetString()); + info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["tradeVolume"].GetString()); + info.insert(CCAPI_IS_MAKER, data["aggressor"].GetBool() ? "0" : "1"); } std::vector elementList; elementList.emplace_back(std::move(info)); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h index 2ee2764c0..b0bd0a4ff 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h @@ -14,10 +14,6 @@ class ExecutionManagementServiceHuobiBase : public ExecutionManagementService { protected: #endif - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { - auto now = UtilTime::now(); - this->send(hdl, "{\"ping\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + "}", wspp::frame::opcode::text, ec); - } void createSignature(std::string& signature, std::string& queryString, const std::string& reqMethod, const std::string& host, const std::string& path, const std::map& queryParamMap, const std::map& credential) { std::string preSignedText; @@ -51,6 +47,12 @@ class ExecutionManagementServiceHuobiBase : public ExecutionManagementService { queryParamMap.insert(std::make_pair(y.at(0), y.at(1))); } } + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + queryParamMap.insert(std::make_pair("AccessKeyId", apiKey)); + queryParamMap.insert(std::make_pair("SignatureMethod", "HmacSHA256")); + queryParamMap.insert(std::make_pair("SignatureVersion", "2")); + std::string timestamp = UtilTime::getISOTimestamp(now, "%FT%T"); + queryParamMap.insert(std::make_pair("Timestamp", Url::urlEncode(timestamp))); std::string signature; this->createSignature(signature, queryString, methodString, this->hostRest, path, queryParamMap, credential); if (!queryString.empty()) { diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h index 1ecb26cb3..1efe0a654 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceHuobiCoinSwap : public ExecutionManagementServic ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-notification"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-notification"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_HUOBI_COIN_SWAP_API_KEY; this->apiSecretName = CCAPI_HUOBI_COIN_SWAP_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h index cb87bfd37..ef411a994 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h @@ -23,7 +23,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen protected: #endif - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find("err_code") != std::string::npos; } + bool doesHttpBodyContainError(const std::string& body) override { return body.find("err_code") != std::string::npos; } void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) { ExecutionManagementServiceHuobiBase::appendSymbolId(document, allocator, symbolId, "contract_code"); } @@ -239,8 +239,10 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); std::string op = document["op"].GetString(); const auto& fieldSet = subscription.getFieldSet(); const auto& instrumentSet = subscription.getInstrumentSet(); @@ -254,9 +256,9 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen auto& allocator = document.GetAllocator(); document.AddMember("op", rj::Value("sub").Move(), allocator); std::string topic; - if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + if (field == CCAPI_EM_ORDER_UPDATE) { topic = this->orderDataTopic + "." + instrument; - } else if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + } else if (field == CCAPI_EM_PRIVATE_TRADE) { topic = this->matchOrderDataTopic + "." + instrument; } document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), allocator); @@ -333,6 +335,12 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))); } } + for (const auto& x : document["trade"].GetArray()) { + info.insert(CCAPI_TRADE_ID, std::string(x["trade_id"].GetString())); + info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["trade_price"].GetString()); + info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["trade_volume"].GetString()); + info.insert(CCAPI_IS_MAKER, std::string(x["role"].GetString()) == "maker" ? "1" : "0"); + } std::vector elementList; elementList.emplace_back(std::move(info)); message.setElementList(elementList); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h index 91fedb3f9..a77805cb4 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h @@ -10,14 +10,23 @@ class ExecutionManagementServiceHuobiUsdtSwap : public ExecutionManagementServic ServiceContextPtr serviceContextPtr) : ExecutionManagementServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-notification"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-notification"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_HUOBI_USDT_SWAP_API_KEY; this->apiSecretName = CCAPI_HUOBI_USDT_SWAP_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken.h index 162eef575..f6d6cc740 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken.h @@ -11,14 +11,23 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN; - this->baseUrl = CCAPI_KRAKEN_URL_WS_BASE_PRIVATE; + this->baseUrlWs = CCAPI_KRAKEN_URL_WS_BASE_PRIVATE; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_KRAKEN_API_KEY; this->apiSecretName = CCAPI_KRAKEN_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -41,7 +50,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { auto now = UtilTime::now(); this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec); } - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("error":[])") == std::string::npos; } + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("error":[])") == std::string::npos; } void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, const std::map& credential) override { @@ -294,7 +303,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { document.Parse(body.c_str()); if (document.HasMember("result") && document["result"].HasMember("token")) { std::string token = document["result"]["token"].GetString(); - thisWsConnection.url = that->baseUrl; + thisWsConnection.url = that->baseUrlWs; that->connect(thisWsConnection); that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({ {"token", token}, @@ -336,8 +345,10 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { } return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h index 1d2804f7e..9470cec99 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h @@ -11,14 +11,23 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_KRAKEN_FUTURES_API_KEY; this->apiSecretName = CCAPI_KRAKEN_FUTURES_API_SECRET; this->setupCredential({this->apiKeyName, this->apiSecretName}); @@ -42,7 +51,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic protected: #endif - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("result":"success")") == std::string::npos; } + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("result":"success")") == std::string::npos; } void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, const std::map& credential) override { @@ -240,8 +249,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString()); element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString()); - element.insert(CCAPI_EM_POSITION_COST, - Decimal(UtilString::printDoubleScientific(std::stod(x["price"].GetString()) * std::stod(x["size"].GetString()))).toString()); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["price"].GetString()); elementList.emplace_back(std::move(element)); } } break; @@ -265,8 +273,10 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); @@ -279,62 +289,64 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic if (document.FindMember("event") == document.MemberEnd()) { if (document.FindMember("feed") != document.MemberEnd()) { std::string feed = document["feed"].GetString(); - std::string field; - if (feed == "fills") { - field = CCAPI_EM_PRIVATE_TRADE; - } else if (feed == "open_orders") { - field = CCAPI_EM_ORDER_UPDATE; - } - const auto& fieldSet = subscription.getFieldSet(); - if (fieldSet.find(field) != fieldSet.end()) { - const auto& instrumentSet = subscription.getInstrumentSet(); - if (field == CCAPI_EM_PRIVATE_TRADE) { - for (const auto& x : document["fills"].GetArray()) { + if (feed == "fills" || feed == "open_orders") { + std::string field; + if (feed == "fills") { + field = CCAPI_EM_PRIVATE_TRADE; + } else if (feed == "open_orders") { + field = CCAPI_EM_ORDER_UPDATE; + } + const auto& fieldSet = subscription.getFieldSet(); + if (fieldSet.find(field) != fieldSet.end()) { + const auto& instrumentSet = subscription.getInstrumentSet(); + if (field == CCAPI_EM_PRIVATE_TRADE) { + for (const auto& x : document["fills"].GetArray()) { + std::string instrument = x["instrument"].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + Message message; + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()))); + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + std::vector elementList; + Element element; + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["price"].GetString()); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["qty"].GetString()); + element.insert(CCAPI_EM_ORDER_SIDE, x["buy"].GetBool() ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_EM_ORDER_ID, std::string(x["order_id"].GetString())); + element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["cli_ord_id"].GetString())); + element.insert(CCAPI_IS_MAKER, std::string(x["fill_type"].GetString()) == "maker" ? "1" : "0"); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fee_paid"].GetString())); + element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fee_currency"].GetString())); + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } else if (field == CCAPI_EM_ORDER_UPDATE) { + const rj::Value& x = document["order"]; std::string instrument = x["instrument"].GetString(); if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { Message message; - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); - message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["last_update_time"].GetString()))); message.setTimeReceived(timeReceived); message.setCorrelationIdList({subscription.getCorrelationId()}); std::vector elementList; Element element; - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["price"].GetString()); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["qty"].GetString()); - element.insert(CCAPI_EM_ORDER_SIDE, x["buy"].GetBool() ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); - element.insert(CCAPI_EM_ORDER_ID, std::string(x["order_id"].GetString())); - element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["cli_ord_id"].GetString())); - element.insert(CCAPI_IS_MAKER, std::string(x["fill_type"].GetString()) == "maker" ? "1" : "0"); element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fee_paid"].GetString())); - element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fee_currency"].GetString())); + element.insert(CCAPI_EM_ORDER_QUANTITY, x["qty"].GetString()); + element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, x["filled"].GetString()); + element.insert(CCAPI_EM_ORDER_LIMIT_PRICE, x["limit_price"].GetString()); + element.insert(CCAPI_EM_ORDER_ID, x["order_id"].GetString()); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["direction"].GetString()) == "0" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert("is_cancel", document["is_cancel"].GetBool() ? "1" : "0"); elementList.emplace_back(std::move(element)); message.setElementList(elementList); messageList.emplace_back(std::move(message)); } } - } else if (field == CCAPI_EM_ORDER_UPDATE) { - const rj::Value& x = document["order"]; - std::string instrument = x["instrument"].GetString(); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - Message message; - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); - message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["last_update_time"].GetString()))); - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - std::vector elementList; - Element element; - element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - element.insert(CCAPI_EM_ORDER_QUANTITY, x["qty"].GetString()); - element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, x["filled"].GetString()); - element.insert(CCAPI_EM_ORDER_LIMIT_PRICE, x["limit_price"].GetString()); - element.insert(CCAPI_EM_ORDER_ID, x["order_id"].GetString()); - element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["direction"].GetString()) == "0" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); - element.insert("is_cancel", document["is_cancel"].GetBool() ? "1" : "0"); - elementList.emplace_back(std::move(element)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } } } } @@ -352,25 +364,39 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA512, UtilAlgorithm::base64Decode(apiSecret), challengeToSignSha256)); std::vector sendStringList; for (const auto& field : subscription.getFieldSet()) { - std::string feed; - if (field == CCAPI_EM_PRIVATE_TRADE) { - feed = "fills"; - } else if (field == CCAPI_EM_ORDER_UPDATE) { - feed = "open_orders"; + { + std::string feed; + if (field == CCAPI_EM_PRIVATE_TRADE) { + feed = "fills"; + } else if (field == CCAPI_EM_ORDER_UPDATE) { + feed = "open_orders"; + } + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("event", rj::Value("subscribe").Move(), allocator); + document.AddMember("feed", rj::Value(feed.c_str(), allocator).Move(), allocator); + document.AddMember("api_key", rj::Value(apiKey.c_str(), allocator).Move(), allocator); + document.AddMember("original_challenge", rj::Value(challengeToSign.c_str(), allocator).Move(), allocator); + document.AddMember("signed_challenge", rj::Value(signature.c_str(), allocator).Move(), allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + } + { + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("event", rj::Value("subscribe").Move(), allocator); + document.AddMember("feed", rj::Value("heartbeat").Move(), allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); } - rj::Document document; - document.SetObject(); - auto& allocator = document.GetAllocator(); - document.AddMember("event", rj::Value("subscribe").Move(), allocator); - document.AddMember("feed", rj::Value(feed.c_str(), allocator).Move(), allocator); - document.AddMember("api_key", rj::Value(apiKey.c_str(), allocator).Move(), allocator); - document.AddMember("original_challenge", rj::Value(challengeToSign.c_str(), allocator).Move(), allocator); - document.AddMember("signed_challenge", rj::Value(signature.c_str(), allocator).Move(), allocator); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - std::string sendString = stringBuffer.GetString(); - sendStringList.push_back(sendString); } for (const auto& sendString : sendStringList) { ErrorCode ec; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin.h index 70da1c187..87e34935d 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin.h @@ -2,15 +2,14 @@ #define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_H_ #ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT #ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN -#include "ccapi_cpp/service/ccapi_execution_management_service.h" +#include "ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h" namespace ccapi { -class ExecutionManagementServiceKucoin : public ExecutionManagementService { +class ExecutionManagementServiceKucoin : public ExecutionManagementServiceKucoinBase { public: ExecutionManagementServiceKucoin(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr) - : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + : ExecutionManagementServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); try { @@ -18,311 +17,34 @@ class ExecutionManagementServiceKucoin : public ExecutionManagementService { } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_KUCOIN_API_KEY; this->apiSecretName = CCAPI_KUCOIN_API_SECRET; this->apiPassphraseName = CCAPI_KUCOIN_API_PASSPHRASE; - this->apiKeyVersionName = CCAPI_KUCOIN_API_KEY_VERSION; - this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName, this->apiKeyVersionName}); + this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName}); this->createOrderTarget = "/api/v1/orders"; this->cancelOrderTarget = "/api/v1/orders/"; this->getOrderTarget = "/api/v1/orders/"; + this->getOrderByClientOrderIdTarget = "/api/v1/order/client-order/"; this->getOpenOrdersTarget = "/api/v1/orders"; this->cancelOpenOrdersTarget = "/api/v1/orders"; this->getAccountsTarget = "/api/v1/accounts"; this->getAccountBalancesTarget = "/api/v1/accounts/"; + this->topicTradeOrders = "/spotMarket/tradeOrders"; + this->createOrderMarginTarget = "/api/v1/margin/order"; } virtual ~ExecutionManagementServiceKucoin() {} #ifndef CCAPI_EXPOSE_INTERNAL protected: #endif - void onOpen(wspp::connection_hdl hdl) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - wsConnection.status = WsConnection::Status::OPEN; - } - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { - return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); - } - void prepareConnect(WsConnection& wsConnection) override { - auto now = UtilTime::now(); - http::request req; - req.set(http::field::host, this->hostRest); - req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); - req.method(http::verb::post); - req.target("/api/v1/bullet-private"); - auto credential = wsConnection.subscriptionList.at(0).getCredential(); - if (credential.empty()) { - credential = this->credentialDefault; - } - this->prepareReq(req, now, credential); - this->signRequest(req, "", credential); - this->sendRequest( - req, - [wsConnection, that = shared_from_base()](const beast::error_code& ec) { - WsConnection thisWsConnection = wsConnection; - that->onFail_(thisWsConnection); - }, - [wsConnection, that = shared_from_base()](const http::response& res) { - WsConnection thisWsConnection = wsConnection; - int statusCode = res.result_int(); - std::string body = res.body(); - if (statusCode / 100 == 2) { - std::string urlWebsocketBase; - try { - rj::Document document; - document.Parse(body.c_str()); - const rj::Value& instanceServer = document["data"]["instanceServers"][0]; - urlWebsocketBase += std::string(instanceServer["endpoint"].GetString()); - urlWebsocketBase += "?token="; - urlWebsocketBase += std::string(document["data"]["token"].GetString()); - thisWsConnection.url = urlWebsocketBase; - that->connect(thisWsConnection); - that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({ - {"pingInterval", std::string(instanceServer["pingInterval"].GetString())}, - {"pingTimeout", std::string(instanceServer["pingTimeout"].GetString())}, - }); - return; - } catch (const std::runtime_error& e) { - CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); - } - } - that->onFail_(thisWsConnection); - }, - this->sessionOptions.httpRequestTimeoutMilliSeconds); - } - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { - auto now = UtilTime::now(); - this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec); - } - void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, - std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, - const std::map& credential) override { - auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); - auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string(); - preSignedText += methodString; - auto target = path; - if (!queryString.empty()) { - target += queryString; - } - preSignedText += target; - preSignedText += body; - auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); - if (!headerString.empty()) { - headerString += "\r\n"; - } - headerString += "KC-API-SIGN:" + signature; - } - void signRequest(http::request& req, const std::string& body, const std::map& credential) { - auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); - auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string(); - preSignedText += std::string(req.method_string()); - preSignedText += req.target().to_string(); - preSignedText += body; - auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); - req.set("KC-API-SIGN", signature); - req.body() = body; - req.prepare_payload(); - } - void signApiPassphrase(http::request& req, const std::string& apiKeyVersion, const std::string& apiPassphrase, - const std::string& apiSecret) { - if (apiKeyVersion == "2") { - req.set("KC-API-PASSPHRASE", UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, apiPassphrase))); - } else { - req.set("KC-API-PASSPHRASE", apiPassphrase); - } - } - void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map& param, - const std::map standardizationMap = { - {CCAPI_EM_ORDER_SIDE, "side"}, - {CCAPI_EM_ORDER_QUANTITY, "size"}, - {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, - {CCAPI_EM_CLIENT_ORDER_ID, "clientOid"}, - }) { - for (const auto& kv : param) { - auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; - auto value = kv.second; - if (key == "side") { - value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell"; - } - if (key == "cancelAfter") { - document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(static_cast(std::stoll(value))), allocator); - } else if (value == "true" || value == "false") { - document.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator); - } else { - document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); - } - } - } - void appendParam(std::string& queryString, const std::map& param, - const std::map standardizationMap = {}) { - for (const auto& kv : param) { - queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; - queryString += "="; - queryString += Url::urlEncode(kv.second); - queryString += "&"; - } - } - void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) { - document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); - } - void prepareReq(http::request& req, const TimePoint& now, const std::map& credential) { - req.set(beast::http::field::content_type, "application/json"); - auto apiKey = mapGetWithDefault(credential, this->apiKeyName); - req.set("KC-API-KEY", apiKey); - req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); - auto apiKeyVersion = mapGetWithDefault(credential, this->apiKeyVersionName); - req.set("KC-API-KEY-VERSION", apiKeyVersion); - auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); - auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); - this->signApiPassphrase(req, apiKeyVersion, apiPassphrase, apiSecret); - } - void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, - const std::map& credential) override { - this->prepareReq(req, now, credential); - switch (request.getOperation()) { - case Request::Operation::GENERIC_PRIVATE_REQUEST: { - ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); - } break; - case Request::Operation::CREATE_ORDER: { - req.method(http::verb::post); - const std::map param = request.getFirstParamWithDefault(); - req.target(this->createOrderTarget); - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); - this->appendParam(document, allocator, param); - this->appendSymbolId(document, allocator, symbolId); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - auto body = stringBuffer.GetString(); - this->signRequest(req, body, credential); - } break; - case Request::Operation::CANCEL_ORDER: { - req.method(http::verb::delete_); - const std::map param = request.getFirstParamWithDefault(); - bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end(); - std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID) - : param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID) - : ""; - auto target = - useOrderId ? std::regex_replace(this->cancelOrderTarget, std::regex(""), id) : std::regex_replace("/api/v1/order/", std::regex(""), id); - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::GET_ORDER: { - req.method(http::verb::get); - const std::map param = request.getFirstParamWithDefault(); - bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end(); - std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID) - : param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID) - : ""; - auto target = - useOrderId ? std::regex_replace(this->getOrderTarget, std::regex(""), id) : std::regex_replace("/api/v1/order/", std::regex(""), id); - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::GET_OPEN_ORDERS: { - req.method(http::verb::get); - auto target = this->getOpenOrdersTarget; - target += "?status=active"; - if (!symbolId.empty()) { - target += "&symbol="; - target += symbolId; - } - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::CANCEL_OPEN_ORDERS: { - req.method(http::verb::delete_); - auto target = this->cancelOpenOrdersTarget; - if (!symbolId.empty()) { - target += "?symbol="; - target += symbolId; - } - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::GET_ACCOUNTS: { - req.method(http::verb::get); - std::string target = this->getAccountsTarget; - const std::map param = request.getFirstParamWithDefault(); - if (!param.empty()) { - std::string queryString; - this->appendParam(queryString, param, - { - {CCAPI_EM_ASSET, "currency"}, - {CCAPI_EM_ACCOUNT_TYPE, "type"}, - }); - target += "?" + queryString; - } - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::GET_ACCOUNT_BALANCES: { - req.method(http::verb::get); - const std::map param = request.getFirstParamWithDefault(); - auto target = this->getAccountBalancesTarget; - auto accountId = param.find(CCAPI_EM_ACCOUNT_ID) != param.end() ? param.at(CCAPI_EM_ACCOUNT_ID) : ""; - this->substituteParam(target, { - {"", accountId}, - }); - req.target(target); - this->signRequest(req, "", credential); - } break; - default: - this->convertRequestForRestCustom(req, request, now, symbolId, credential); - } - } - void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, - const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { - {CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)}, - {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}}; - const rj::Value& data = document["data"]; - if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) { - if (data.FindMember("cancelledOrderIds") != data.MemberEnd()) { - for (const auto& x : data["cancelledOrderIds"].GetArray()) { - Element element; - element.insert(CCAPI_EM_ORDER_ID, x.GetString()); - elementList.emplace_back(std::move(element)); - } - } else { - Element element; - element.insert(CCAPI_EM_ORDER_ID, data["cancelledOrderId"].GetString()); - element.insert(CCAPI_EM_CLIENT_ORDER_ID, data["clientOid"].GetString()); - elementList.emplace_back(std::move(element)); - } - } else if (operation == Request::Operation::CREATE_ORDER) { - Element element; - element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString()); - elementList.emplace_back(std::move(element)); - } else if (operation == Request::Operation::GET_OPEN_ORDERS) { - for (const auto& x : data["items"].GetArray()) { - Element element; - this->extractOrderInfo(element, x, extractionFieldNameMap); - elementList.emplace_back(std::move(element)); - } - } else if (operation == Request::Operation::GET_ORDER) { - Element element; - this->extractOrderInfo(element, data, extractionFieldNameMap); - elementList.emplace_back(std::move(element)); - } - } - void extractOrderInfo(Element& element, const rj::Value& x, - const std::map >& extractionFieldNameMap) override { - ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap); - { - auto it = x.FindMember("isActive"); - if (it != x.MemberEnd()) { - element.insert("isActive", it->value.GetBool() ? "true" : "false"); - } - } - } void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { const auto& data = document["data"]; @@ -349,133 +71,6 @@ class ExecutionManagementServiceKucoin : public ExecutionManagementService { CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } } - std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, - const std::map& credential) override { - std::string topic; - const auto& fieldSet = subscription.getFieldSet(); - if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { - topic = "/spotMarket/tradeOrders"; - } - std::vector sendStringList; - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); - static int nextRequestId = 1; - std::string requestId = std::to_string(nextRequestId); - nextRequestId += 1; - document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator); - document.AddMember("type", rj::Value("subscribe").Move(), allocator); - document.AddMember("privateChannel", true, allocator); - document.AddMember("response", true, allocator); - document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), allocator); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - std::string sendString = stringBuffer.GetString(); - sendStringList.push_back(sendString); - return sendStringList; - } - void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - auto subscription = wsConnection.subscriptionList.at(0); - rj::Document document; - document.Parse(textMessage.c_str()); - Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived); - if (!event.getMessageList().empty()) { - this->eventHandler(event, nullptr); - } - } - Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, - const rj::Document& document, const TimePoint& timeReceived) { - Event event; - std::vector messageList; - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - std::string type = document["type"].GetString(); - if (type == "message") { - event.setType(Event::Type::SUBSCRIPTION_DATA); - const auto& fieldSet = subscription.getFieldSet(); - const auto& instrumentSet = subscription.getInstrumentSet(); - std::string topic = document["topic"].GetString(); - if (topic == "/spotMarket/tradeOrders") { - const rj::Value& data = document["data"]; - std::string instrument = data["symbol"].GetString(); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - std::string ts = std::string(data["ts"].GetString()); - message.setTime(UtilTime::makeTimePoint({std::stoll(ts.substr(0, ts.length() - 9)), std::stoll(ts.substr(ts.length() - 9))})); - std::string dataType = data["type"].GetString(); - if (dataType == "match" && (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end() || fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end())) { - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); - std::vector elementList; - Element element; - element.insert(CCAPI_TRADE_ID, data["tradeId"].GetString()); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["matchPrice"].GetString()); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["matchSize"].GetString()); - element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); - element.insert(CCAPI_IS_MAKER, std::string(data["liquidity"].GetString()) == "taker" ? "0" : "1"); - element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString()); - element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - elementList.emplace_back(std::move(element)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } else if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); - std::map > extractionFieldNameMap = { - {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)}, - {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledSize", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("remainSize", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, - }; - extractionFieldNameMap.insert({CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}); - Element info; - this->extractOrderInfo(info, data, extractionFieldNameMap); - std::vector elementList; - elementList.emplace_back(std::move(info)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } - } - } - } else if (type == "ack") { - event.setType(Event::Type::SUBSCRIPTION_STATUS); - message.setType(Message::Type::SUBSCRIPTION_STARTED); - Element element; - element.insert(CCAPI_INFO_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); - } else if (type == "error") { - event.setType(Event::Type::SUBSCRIPTION_STATUS); - message.setType(Message::Type::SUBSCRIPTION_FAILURE); - Element element; - element.insert(CCAPI_ERROR_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); - } else if (type == "welcome") { - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = - std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval")); - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = - std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout")); - if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <= - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) { - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1; - } - ExecutionManagementService::onOpen(hdl); - } else if (type == "pong") { - auto now = UtilTime::now(); - this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now; - } - event.setMessageList(messageList); - return event; - } - std::string apiPassphraseName; - std::string apiKeyVersionName; }; } /* namespace ccapi */ #endif diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h new file mode 100644 index 000000000..c41173f11 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h @@ -0,0 +1,477 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_BASE_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_BASE_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#if defined(CCAPI_ENABLE_EXCHANGE_KUCOIN) || defined(CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES) +#include "ccapi_cpp/service/ccapi_execution_management_service.h" +namespace ccapi { +class ExecutionManagementServiceKucoinBase : public ExecutionManagementService { + public: + ExecutionManagementServiceKucoinBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) + : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {} + virtual ~ExecutionManagementServiceKucoinBase() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + void onOpen(wspp::connection_hdl hdl) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + wsConnection.status = WsConnection::Status::OPEN; + } + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); } + void prepareConnect(WsConnection& wsConnection) override { + auto now = UtilTime::now(); + http::request req; + req.set(http::field::host, this->hostRest); + req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); + req.method(http::verb::post); + req.target("/api/v1/bullet-private"); + auto credential = wsConnection.subscriptionList.at(0).getCredential(); + if (credential.empty()) { + credential = this->credentialDefault; + } + this->prepareReq(req, now, credential); + this->signRequest(req, "", credential); + this->sendRequest( + req, + [wsConnection, that = shared_from_base()](const beast::error_code& ec) { + WsConnection thisWsConnection = wsConnection; + that->onFail_(thisWsConnection); + }, + [wsConnection, that = shared_from_base()](const http::response& res) { + WsConnection thisWsConnection = wsConnection; + int statusCode = res.result_int(); + std::string body = res.body(); + if (statusCode / 100 == 2) { + std::string urlWebsocketBase; + try { + rj::Document document; + document.Parse(body.c_str()); + const rj::Value& instanceServer = document["data"]["instanceServers"][0]; + urlWebsocketBase += std::string(instanceServer["endpoint"].GetString()); + urlWebsocketBase += "?token="; + urlWebsocketBase += std::string(document["data"]["token"].GetString()); + thisWsConnection.url = urlWebsocketBase; + that->connect(thisWsConnection); + that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({ + {"pingInterval", std::string(instanceServer["pingInterval"].GetString())}, + {"pingTimeout", std::string(instanceServer["pingTimeout"].GetString())}, + }); + return; + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); + } + } + that->onFail_(thisWsConnection); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); + } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { + auto now = UtilTime::now(); + this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec); + } + void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, + std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, + const std::map& credential) override { + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string(); + preSignedText += methodString; + auto target = path; + if (!queryString.empty()) { + target += queryString; + } + preSignedText += target; + preSignedText += body; + auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); + if (!headerString.empty()) { + headerString += "\r\n"; + } + headerString += "KC-API-SIGN:" + signature; + } + void signRequestPartner(http::request& req, const std::string& body, const std::map& credential) { + req.set("KC-API-PARTNER", CCAPI_KUCOIN_API_PARTNER_PLATFORM_ID); + auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string(); + preSignedText += CCAPI_KUCOIN_API_PARTNER_PLATFORM_ID; + preSignedText += req.base().at("KC-API-KEY").to_string(); + auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, CCAPI_KUCOIN_API_PARTNER_PRIVATE_KEY, preSignedText)); + req.set("KC-API-PARTNER-SIGN", signature); + } + void signRequest(http::request& req, const std::string& body, const std::map& credential) { + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string(); + preSignedText += std::string(req.method_string()); + preSignedText += req.target().to_string(); + preSignedText += body; + auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); + req.set("KC-API-SIGN", signature); + req.body() = body; + req.prepare_payload(); + } + void signApiPassphrase(http::request& req, const std::string& apiPassphrase, const std::string& apiSecret) { + req.set("KC-API-PASSPHRASE", UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, apiPassphrase))); + } + void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_SIDE, "side"}, + {CCAPI_EM_ORDER_QUANTITY, "size"}, + {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, + {CCAPI_EM_CLIENT_ORDER_ID, "clientOid"}, + {CCAPI_EM_ORDER_LEVERAGE, "leverage"}, + }) { + for (const auto& kv : param) { + auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + auto value = kv.second; + if (key == "side") { + value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell"; + } + if (key == "cancelAfter") { + document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(static_cast(std::stoll(value))), allocator); + } else if (value == "true" || value == "false") { + document.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator); + } else { + document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); + } + } + } + void appendParam(std::string& queryString, const std::map& param, + const std::map standardizationMap = {}) { + for (const auto& kv : param) { + queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + queryString += "="; + queryString += Url::urlEncode(kv.second); + queryString += "&"; + } + } + void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) { + document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); + } + void prepareReq(http::request& req, const TimePoint& now, const std::map& credential) { + req.set(beast::http::field::content_type, "application/json"); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("KC-API-KEY", apiKey); + req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); + // auto apiKeyVersion = mapGetWithDefault(credential, this->apiKeyVersionName); + req.set("KC-API-KEY-VERSION", "2"); + auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + this->signApiPassphrase(req, apiPassphrase, apiSecret); + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + this->prepareReq(req, now, credential); + switch (request.getOperation()) { + case Request::Operation::GENERIC_PRIVATE_REQUEST: { + ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::CREATE_ORDER: { + req.method(http::verb::post); + const std::map param = request.getFirstParamWithDefault(); + req.target(request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN + ? this->createOrderMarginTarget + : this->createOrderTarget); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(document, allocator, param); + this->appendSymbolId(document, allocator, symbolId); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + this->signRequestPartner(req, body, credential); + this->signRequest(req, body, credential); + } break; + case Request::Operation::CANCEL_ORDER: { + req.method(http::verb::delete_); + const std::map param = request.getFirstParamWithDefault(); + bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end(); + std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID) + : param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID) + : ""; + auto target = + useOrderId ? std::regex_replace(this->cancelOrderTarget, std::regex(""), id) : std::regex_replace("/api/v1/order/", std::regex(""), id); + req.target(target); + this->signRequest(req, "", credential); + } break; + case Request::Operation::GET_ORDER: { + req.method(http::verb::get); + const std::map param = request.getFirstParamWithDefault(); + bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end(); + std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID) + : param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? param.at(CCAPI_EM_CLIENT_ORDER_ID) + : ""; + auto target = std::regex_replace(useOrderId ? this->getOrderTarget : this->getOrderByClientOrderIdTarget, std::regex(""), Url::urlEncode(id)); + req.target(target); + this->signRequest(req, "", credential); + } break; + case Request::Operation::GET_OPEN_ORDERS: { + req.method(http::verb::get); + auto target = this->getOpenOrdersTarget; + target += "?status=active"; + target += std::string("&tradeType=") + (request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN ? "MARGIN_TRADE" + : request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN ? "MARGIN_ISOLATED_TRADE" + : "TRADE"); + if (!symbolId.empty()) { + target += "&symbol="; + target += symbolId; + } + req.target(target); + this->signRequest(req, "", credential); + } break; + case Request::Operation::CANCEL_OPEN_ORDERS: { + req.method(http::verb::delete_); + auto target = this->cancelOpenOrdersTarget; + target += std::string("?tradeType=") + (request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN ? "MARGIN_TRADE" + : request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN ? "MARGIN_ISOLATED_TRADE" + : "TRADE"); + if (!symbolId.empty()) { + target += "&symbol="; + target += symbolId; + } + req.target(target); + this->signRequest(req, "", credential); + } break; + case Request::Operation::GET_ACCOUNTS: { + req.method(http::verb::get); + std::string target = this->getAccountsTarget; + const std::map param = request.getFirstParamWithDefault(); + if (!param.empty()) { + std::string queryString; + this->appendParam(queryString, param, + { + {CCAPI_EM_ASSET, "currency"}, + {CCAPI_EM_ACCOUNT_TYPE, "type"}, + }); + target += "?" + queryString; + } + req.target(target); + this->signRequest(req, "", credential); + } break; + case Request::Operation::GET_ACCOUNT_BALANCES: { + req.method(http::verb::get); + const std::map param = request.getFirstParamWithDefault(); + auto target = this->getAccountBalancesTarget; + if (this->isDerivatives) { + if (!param.empty()) { + std::string queryString; + this->appendParam(queryString, param, + { + {CCAPI_EM_ASSET, "currency"}, + }); + target += "?" + queryString; + } + } else { + auto accountId = param.find(CCAPI_EM_ACCOUNT_ID) != param.end() ? param.at(CCAPI_EM_ACCOUNT_ID) : ""; + this->substituteParam(target, { + {"", accountId}, + }); + } + req.target(target); + this->signRequest(req, "", credential); + } break; + case Request::Operation::GET_ACCOUNT_POSITIONS: { + req.method(http::verb::get); + const std::map param = request.getFirstParamWithDefault(); + req.target(this->getAccountPositionsTarget); + this->signRequest(req, "", credential); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("dealSize", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("dealFunds", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}}; + const rj::Value& data = document["data"]; + if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) { + if (data.FindMember("cancelledOrderIds") != data.MemberEnd()) { + for (const auto& x : data["cancelledOrderIds"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ORDER_ID, x.GetString()); + elementList.emplace_back(std::move(element)); + } + } else { + Element element; + element.insert(CCAPI_EM_ORDER_ID, data["cancelledOrderId"].GetString()); + element.insert(CCAPI_EM_CLIENT_ORDER_ID, data["clientOid"].GetString()); + elementList.emplace_back(std::move(element)); + } + } else if (operation == Request::Operation::CREATE_ORDER) { + Element element; + element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString()); + elementList.emplace_back(std::move(element)); + } else if (operation == Request::Operation::GET_OPEN_ORDERS) { + for (const auto& x : data["items"].GetArray()) { + Element element; + this->extractOrderInfo(element, x, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } else if (operation == Request::Operation::GET_ORDER) { + Element element; + this->extractOrderInfo(element, data, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } + void extractOrderInfo(Element& element, const rj::Value& x, + const std::map >& extractionFieldNameMap) override { + ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap); + { + auto it = x.FindMember("isActive"); + if (it != x.MemberEnd()) { + element.insert("isActive", it->value.GetBool() ? "true" : "false"); + } + } + } + std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, + const std::map& credential) override { + std::string topic; + const auto& fieldSet = subscription.getFieldSet(); + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + topic = this->topicTradeOrders; + } + std::vector sendStringList; + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + static int nextRequestId = 1; + std::string requestId = std::to_string(nextRequestId); + nextRequestId += 1; + document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator); + document.AddMember("type", rj::Value("subscribe").Move(), allocator); + document.AddMember("privateChannel", true, allocator); + document.AddMember("response", true, allocator); + document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + auto subscription = wsConnection.subscriptionList.at(0); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { + Event event; + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + std::string type = document["type"].GetString(); + if (type == "message") { + event.setType(Event::Type::SUBSCRIPTION_DATA); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + std::string topic = document["topic"].GetString(); + if (topic == this->topicTradeOrders) { + const rj::Value& data = document["data"]; + std::string instrument = data["symbol"].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + std::string ts = std::string(data["ts"].GetString()); + auto time = UtilTime::makeTimePoint({std::stoll(ts.substr(0, ts.length() - 9)), std::stoll(ts.substr(ts.length() - 9))}); + std::string dataType = data["type"].GetString(); + if (dataType == "match" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(time); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + element.insert(CCAPI_TRADE_ID, data["tradeId"].GetString()); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["matchPrice"].GetString()); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["matchSize"].GetString()); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_IS_MAKER, std::string(data["liquidity"].GetString()) == "taker" ? "0" : "1"); + element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString()); + element.insert(CCAPI_EM_CLIENT_ORDER_ID, data["clientOid"].GetString()); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(time); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + std::map > extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledSize", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("remainSize", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, + }; + extractionFieldNameMap.insert({CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}); + Element info; + this->extractOrderInfo(info, data, extractionFieldNameMap); + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + } else if (type == "ack") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } else if (type == "error") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } else if (type == "welcome") { + this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = + std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval")); + this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = + std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout")); + if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <= + this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) { + this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = + this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1; + } + ExecutionManagementService::onOpen(hdl); + } else if (type == "pong") { + auto now = UtilTime::now(); + this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now; + } + event.setMessageList(messageList); + return event; + } + std::string apiPassphraseName; + bool isDerivatives{}; + std::string topicTradeOrders; + std::string createOrderMarginTarget; + std::string getOrderByClientOrderIdTarget; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_BASE_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h index c13f11c97..5f9bde587 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h @@ -2,18 +2,14 @@ #define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_FUTURES_H_ #ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT #ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES - -#include "ccapi_cpp/service/ccapi_execution_management_service.h" -#include "openssl/evp.h" - +#include "ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h" namespace ccapi { -class ExecutionManagementServiceKucoinFutures : public ExecutionManagementService { +class ExecutionManagementServiceKucoinFutures : public ExecutionManagementServiceKucoinBase { public: ExecutionManagementServiceKucoinFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr) - : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + : ExecutionManagementServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); try { @@ -21,459 +17,63 @@ class ExecutionManagementServiceKucoinFutures : public ExecutionManagementServic } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_KUCOIN_FUTURES_API_KEY; this->apiSecretName = CCAPI_KUCOIN_FUTURES_API_SECRET; - this->setupCredential({this->apiKeyName, this->apiSecretName}); - std::string prefix("/api/v1"); - this->createOrderTarget = prefix + "/orders"; - this->cancelOrderTarget = prefix + "/orders/client-order/"; - this->getOpenOrdersTarget = prefix + "/orders"; - this->cancelOpenOrdersTarget = prefix + "/orders"; - this->getAccountsTarget = prefix + "/account-overview"; - this->getAccountPositionsTarget = prefix + "/positions"; + this->apiPassphraseName = CCAPI_KUCOIN_FUTURES_API_PASSPHRASE; + this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName}); + this->createOrderTarget = "/api/v1/orders"; + this->cancelOrderTarget = "/api/v1/orders/"; + this->getOrderTarget = "/api/v1/orders/"; + this->getOrderByClientOrderIdTarget = "/api/v1/orders/byClientOid?clientOid="; + this->getOpenOrdersTarget = "/api/v1/orders"; + this->cancelOpenOrdersTarget = "/api/v1/orders"; + this->getAccountBalancesTarget = "/api/v1/account-overview"; + this->getAccountPositionsTarget = "/api/v1/positions"; + this->topicTradeOrders = "/contractMarket/tradeOrders"; + this->isDerivatives = true; } - virtual ~ExecutionManagementServiceKrakenFutures() {} - + virtual ~ExecutionManagementServiceKucoinFutures() {} #ifndef CCAPI_EXPOSE_INTERNAL protected: #endif - - void onOpen(wspp::connection_hdl hdl) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - wsConnection.status = WsConnection::Status::OPEN; - } - - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { - return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); - } - - void prepareConnect(WsConnection& wsConnection) override { - auto now = UtilTime::now(); - http::request req; - req.set(http::field::host, this->hostRest); - req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); - req.method(http::verb::post); - req.target("/api/v1/bullet-private"); - auto credential = wsConnection.subscriptionList.at(0).getCredential(); - if (credential.empty()) { - credential = this->credentialDefault; - } - this->prepareReq(req, now, credential); - this->signRequest(req, "", credential); - this->sendRequest( - req, - [wsConnection, that = shared_from_base()](const beast::error_code& ec) { - WsConnection thisWsConnection = wsConnection; - that->onFail_(thisWsConnection); - }, - [wsConnection, that = shared_from_base()](const http::response& res) { - WsConnection thisWsConnection = wsConnection; - int statusCode = res.result_int(); - std::string body = res.body(); - if (statusCode / 100 == 2) { - std::string urlWebsocketBase; - try { - rj::Document document; - document.Parse(body.c_str()); - const rj::Value& instanceServer = document["data"]["instanceServers"][0]; - urlWebsocketBase += std::string(instanceServer["endpoint"].GetString()); - urlWebsocketBase += "?token="; - urlWebsocketBase += std::string(document["data"]["token"].GetString()); - thisWsConnection.url = urlWebsocketBase; - that->connect(thisWsConnection); - that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({ - {"pingInterval", std::string(instanceServer["pingInterval"].GetString())}, - {"pingTimeout", std::string(instanceServer["pingTimeout"].GetString())}, - }); - return; - } catch (const std::runtime_error& e) { - CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); - } - } - that->onFail_(thisWsConnection); - }, - this->sessionOptions.httpRequestTimeoutMilliSeconds); - } - - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { - auto now = UtilTime::now(); - this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec); - } - - void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, - std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, - const std::map& credential) override { - auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); - auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string(); - preSignedText += methodString; - auto target = path; - if (!queryString.empty()) { - target += queryString; - } - preSignedText += target; - preSignedText += body; - auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); - if (!headerString.empty()) { - headerString += "\r\n"; - } - headerString += "KC-API-SIGN:" + signature; - } - - void signRequest(http::request& req, const std::string& body, const std::map& credential) { - auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); - auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string(); - preSignedText += std::string(req.method_string()); - preSignedText += req.target().to_string(); - preSignedText += body; - auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); - req.set("KC-API-SIGN", signature); - req.body() = body; - req.prepare_payload(); - } - void signApiPassphrase(http::request& req, const std::string& apiKeyVersion, const std::string& apiPassphrase, - const std::string& apiSecret) { - if (apiKeyVersion == "2") { - req.set("KC-API-PASSPHRASE", UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, apiPassphrase))); - } else { - req.set("KC-API-PASSPHRASE", apiPassphrase); - } - } - - void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map& param, - const std::map standardizationMap = { - {CCAPI_EM_ORDER_SIDE, "side"}, - {CCAPI_EM_ORDER_QUANTITY, "size"}, - {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, - {CCAPI_EM_CLIENT_ORDER_ID, "clientOid"}, - }) { - for (const auto& kv : param) { - auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; - auto value = kv.second; - if (key == "side") { - value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell"; - } - if (key == "cancelAfter") { - document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(static_cast(std::stoll(value))), allocator); - } else if (value == "true" || value == "false") { - document.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator); - } else { - document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); - } - } - } - - void appendParam(std::string& queryString, const std::map& param, - const std::map standardizationMap = {}) { - for (const auto& kv : param) { - queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; - queryString += "="; - queryString += Url::urlEncode(kv.second); - queryString += "&"; - } - } - - void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) { - document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); - } - - void prepareReq(http::request& req, const TimePoint& now, const std::map& credential) { - req.set(beast::http::field::content_type, "application/json"); - auto apiKey = mapGetWithDefault(credential, this->apiKeyName); - req.set("KC-API-KEY", apiKey); - req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); - auto apiKeyVersion = mapGetWithDefault(credential, this->apiKeyVersionName); - req.set("KC-API-KEY-VERSION", apiKeyVersion); - auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); - auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); - this->signApiPassphrase(req, apiKeyVersion, apiPassphrase, apiSecret); - } - - void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, - const std::map& credential) override { - this->prepareReq(req, now, credential); - switch (request.getOperation()) { - case Request::Operation::GENERIC_PRIVATE_REQUEST: { - ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); - } break; - case Request::Operation::CREATE_ORDER: { - req.method(http::verb::post); - const std::map param = request.getFirstParamWithDefault(); - req.target(this->createOrderTarget); - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); - this->appendParam(document, allocator, param); - this->appendSymbolId(document, allocator, symbolId); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - auto body = stringBuffer.GetString(); - this->signRequest(req, body, credential); - } break; - case Request::Operation::CANCEL_ORDER: { - req.method(http::verb::delete_); - const std::map param = request.getFirstParamWithDefault(); - bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end(); - std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID) - : param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID) - : ""; - auto target = useOrderId ? std::regex_replace(this->cancelOrderTarget, std::regex(""), id) - : std::regex_replace("/api/v1/orders/", std::regex(""), id); - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::GET_ORDER: { - req.method(http::verb::get); - const std::map param = request.getFirstParamWithDefault(); - bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end(); - std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID) - : param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID) - : ""; - auto target = - useOrderId ? std::regex_replace(this->getOrderTarget, std::regex(""), id) : std::regex_replace("/api/v1/orders/", std::regex(""), id); - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::GET_OPEN_ORDERS: { - req.method(http::verb::get); - auto target = this->getOpenOrdersTarget; - target += "?status=active"; - if (!symbolId.empty()) { - target += "&symbol="; - target += symbolId; - } - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::CANCEL_OPEN_ORDERS: { - req.method(http::verb::delete_); - auto target = this->cancelOpenOrdersTarget; - if (!symbolId.empty()) { - target += "?symbol="; - target += symbolId; - } - req.target(target); - this->signRequest(req, "", credential); - } break; - case Request::Operation::GET_ACCOUNT_BALANCES: { - req.method(http::verb::get); - const std::map param = request.getFirstParamWithDefault(); - auto target = this->getAccountsTarget; - auto accountId = param.find(CCAPI_EM_ACCOUNT_ID) != param.end() ? param.at(CCAPI_EM_ACCOUNT_ID) : ""; - req.target(target); - this->signRequest(req, "", credential); - } break; - default: - this->convertRequestForRestCustom(req, request, now, symbolId, credential); - } - } - - void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, - const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { - {CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)}, - {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}}; - const rj::Value& data = document["data"]; - if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) { - if (data.FindMember("cancelledOrderIds") != data.MemberEnd()) { - for (const auto& x : data["cancelledOrderIds"].GetArray()) { - Element element; - element.insert(CCAPI_EM_ORDER_ID, x.GetString()); - elementList.emplace_back(std::move(element)); - } - } else { - Element element; - element.insert(CCAPI_EM_ORDER_ID, data["cancelledOrderId"].GetString()); - element.insert(CCAPI_EM_CLIENT_ORDER_ID, data["clientOid"].GetString()); - elementList.emplace_back(std::move(element)); - } - } else if (operation == Request::Operation::CREATE_ORDER) { - Element element; - element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString()); - elementList.emplace_back(std::move(element)); - } else if (operation == Request::Operation::GET_OPEN_ORDERS) { - for (const auto& x : data["items"].GetArray()) { - Element element; - this->extractOrderInfo(element, x, extractionFieldNameMap); - elementList.emplace_back(std::move(element)); - } - } else if (operation == Request::Operation::GET_ORDER) { - Element element; - this->extractOrderInfo(element, data, extractionFieldNameMap); - elementList.emplace_back(std::move(element)); - } - } - void extractOrderInfo(Element& element, const rj::Value& x, - const std::map >& extractionFieldNameMap) override { - ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap); - { - auto it = x.FindMember("isActive"); - if (it != x.MemberEnd()) { - element.insert("isActive", it->value.GetBool() ? "true" : "false"); - } - } - } - void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { const auto& data = document["data"]; switch (request.getOperation()) { - case Request::Operation::GET_ACCOUNTS: { - for (const auto& x : data.GetArray()) { - Element element; - element.insert(CCAPI_EM_ASSET, x["currency"].GetString()); - element.insert(CCAPI_EM_QUANTITY_TOTAL, x["marginBalance"].GetString()); - element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString()); - elementList.emplace_back(std::move(element)); - } - } break; case Request::Operation::GET_ACCOUNT_BALANCES: { Element element; element.insert(CCAPI_EM_ASSET, data["currency"].GetString()); - element.insert(CCAPI_EM_QUANTITY_TOTAL, data["marginBalance"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, data["accountEquity"].GetString()); element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, data["availableBalance"].GetString()); elementList.emplace_back(std::move(element)); } break; + case Request::Operation::GET_ACCOUNT_POSITIONS: { + for (const auto& x : data.GetArray()) { + Element element; + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_SETTLE_ASSET, x["settleCurrency"].GetString()); + element.insert(CCAPI_EM_POSITION_QUANTITY, x["currentQty"].GetString()); + element.insert(CCAPI_EM_POSITION_COST, x["posCost"].GetString()); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgEntryPrice"].GetString()); + element.insert(CCAPI_EM_POSITION_LEVERAGE, x["realLeverage"].GetString()); + elementList.emplace_back(std::move(element)); + } + } break; default: CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } } - - std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, - const std::map& credential) override { - std::string topic; - const auto& fieldSet = subscription.getFieldSet(); - if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { - topic = "/contractMarket/tradeOrders"; - } - std::vector sendStringList; - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); - static int nextRequestId = 1; - std::string requestId = std::to_string(nextRequestId); - nextRequestId += 1; - document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator); - document.AddMember("type", rj::Value("subscribe").Move(), allocator); - document.AddMember("privateChannel", true, allocator); - document.AddMember("response", true, allocator); - document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), allocator); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - std::string sendString = stringBuffer.GetString(); - sendStringList.push_back(sendString); - return sendStringList; - } - - void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - auto subscription = wsConnection.subscriptionList.at(0); - rj::Document document; - document.Parse(textMessage.c_str()); - Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived); - if (!event.getMessageList().empty()) { - this->eventHandler(event, nullptr); - } - } - Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, - const rj::Document& document, const TimePoint& timeReceived) { - Event event; - std::vector messageList; - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - std::string type = document["type"].GetString(); - if (type == "message") { - event.setType(Event::Type::SUBSCRIPTION_DATA); - const auto& fieldSet = subscription.getFieldSet(); - const auto& instrumentSet = subscription.getInstrumentSet(); - std::string topic = document["topic"].GetString(); - if (topic == "/contractMarket/tradeOrders") { - const rj::Value& data = document["data"]; - std::string instrument = data["symbol"].GetString(); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - std::string ts = std::string(data["ts"].GetString()); - message.setTime(UtilTime::makeTimePoint({std::stoll(ts.substr(0, ts.length() - 9)), std::stoll(ts.substr(ts.length() - 9))})); - std::string dataType = data["type"].GetString(); - if (dataType == "match" && (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end() || fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end())) { - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); - std::vector elementList; - Element element; - element.insert(CCAPI_TRADE_ID, data["tradeId"].GetString()); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["matchPrice"].GetString()); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["matchSize"].GetString()); - element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); - element.insert(CCAPI_IS_MAKER, std::string(data["liquidity"].GetString()) == "taker" ? "0" : "1"); - element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString()); - element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - elementList.emplace_back(std::move(element)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } else if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); - std::map > extractionFieldNameMap = { - {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)}, - {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledSize", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("remainSize", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, - }; - extractionFieldNameMap.insert({CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)}); - Element info; - this->extractOrderInfo(info, data, extractionFieldNameMap); - std::vector elementList; - elementList.emplace_back(std::move(info)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } - } - } - } else if (type == "ack") { - event.setType(Event::Type::SUBSCRIPTION_STATUS); - message.setType(Message::Type::SUBSCRIPTION_STARTED); - Element element; - element.insert(CCAPI_INFO_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); - } else if (type == "error") { - event.setType(Event::Type::SUBSCRIPTION_STATUS); - message.setType(Message::Type::SUBSCRIPTION_FAILURE); - Element element; - element.insert(CCAPI_ERROR_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); - } else if (type == "welcome") { - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = - std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval")); - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = - std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout")); - if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <= - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) { - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1; - } - ExecutionManagementService::onOpen(hdl); - } else if (type == "pong") { - auto now = UtilTime::now(); - this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now; - } - event.setMessageList(messageList); - return event; - } - std::string apiPassphraseName; - std::string apiKeyVersionName; }; } /* namespace ccapi */ #endif #endif -#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_H_ \ No newline at end of file +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_FUTURES_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h new file mode 100644 index 000000000..ca9199bef --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h @@ -0,0 +1,444 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC +#include "ccapi_cpp/service/ccapi_execution_management_service.h" +namespace ccapi { +class ExecutionManagementServiceMexc : public ExecutionManagementService { + public: + ExecutionManagementServiceMexc(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) + : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->pingListenKeyIntervalSeconds = 600; + this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_MEXC_API_KEY; + this->apiSecretName = CCAPI_MEXC_API_SECRET; + this->setupCredential({this->apiKeyName, this->apiSecretName}); + this->createOrderTarget = CCAPI_MEXC_CREATE_ORDER_PATH; + this->cancelOrderTarget = "/api/v3/order"; + this->getOrderTarget = "/api/v3/order"; + this->getOpenOrdersTarget = "/api/v3/openOrders"; + this->cancelOpenOrdersTarget = "/api/v3/openOrders"; + this->listenKeyTarget = CCAPI_MEXC_LISTEN_KEY_PATH; + this->getAccountBalancesTarget = "/api/v3/account"; + } + virtual ~ExecutionManagementServiceMexc() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + // bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"PING"})", wspp::frame::opcode::text, ec); } + void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, + std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, + const std::map& credential) override { + if (queryString.find("timestamp=") == std::string::npos) { + if (!queryString.empty()) { + queryString += "&"; + } + queryString += "timestamp="; + queryString += std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); + } + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, queryString, true); + queryString += "&signature="; + queryString += signature; + } + void signRequest(std::string& queryString, const std::map& param, const TimePoint& now, + const std::map& credential) { + if (param.find("timestamp") == param.end()) { + queryString += "timestamp="; + queryString += std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); + queryString += "&"; + } + if (queryString.back() == '&') { + queryString.pop_back(); + } + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, queryString, true); + queryString += "&signature="; + queryString += signature; + } + void appendParam(std::string& queryString, const std::map& param, + const std::map standardizationMap = {}) { + for (const auto& kv : param) { + queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + queryString += "="; + queryString += Url::urlEncode(kv.second); + queryString += "&"; + } + } + void appendSymbolId(std::string& queryString, const std::string& symbolId) { + queryString += "symbol="; + queryString += Url::urlEncode(symbolId); + queryString += "&"; + } + void prepareReq(http::request& req, const std::map& credential) { + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("X-MEXC-APIKEY", apiKey); + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + this->prepareReq(req, credential); + switch (request.getOperation()) { + case Request::Operation::GENERIC_PRIVATE_REQUEST: { + ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::CREATE_ORDER: { + req.set("source", CCAPI_MEXC_API_SOURCE); + req.method(http::verb::post); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_EM_ORDER_SIDE, "side"}, + {CCAPI_EM_ORDER_QUANTITY, "quantity"}, + {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, + {CCAPI_EM_CLIENT_ORDER_ID, "newClientOrderId"}, + }); + this->appendSymbolId(queryString, symbolId); + if (param.find("type") == param.end()) { + queryString += "type=LIMIT&"; + } + this->signRequest(queryString, param, now, credential); + req.target(std::string(this->createOrderTarget) + "?" + queryString); + } break; + case Request::Operation::CANCEL_ORDER: { + req.method(http::verb::delete_); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_EM_CLIENT_ORDER_ID, "origClientOrderId"}, + }); + this->appendSymbolId(queryString, symbolId); + this->signRequest(queryString, param, now, credential); + req.target(this->cancelOrderTarget + "?" + queryString); + } break; + case Request::Operation::GET_ORDER: { + req.method(http::verb::get); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_EM_CLIENT_ORDER_ID, "origClientOrderId"}, + }); + this->appendSymbolId(queryString, symbolId); + this->signRequest(queryString, param, now, credential); + req.target(this->getOrderTarget + "?" + queryString); + } break; + case Request::Operation::GET_OPEN_ORDERS: { + req.method(http::verb::get); + std::string queryString; + this->appendParam(queryString, {}); + if (!symbolId.empty()) { + this->appendSymbolId(queryString, symbolId); + } + this->signRequest(queryString, {}, now, credential); + req.target(this->getOpenOrdersTarget + "?" + queryString); + } break; + case Request::Operation::CANCEL_OPEN_ORDERS: { + req.method(http::verb::delete_); + std::string queryString; + this->appendParam(queryString, {}); + this->appendSymbolId(queryString, symbolId); + this->signRequest(queryString, {}, now, credential); + req.target(this->cancelOpenOrdersTarget + "?" + queryString); + } break; + case Request::Operation::GET_ACCOUNT_BALANCES: { + req.method(http::verb::get); + std::string queryString; + this->appendParam(queryString, {}); + this->signRequest(queryString, {}, now, credential); + req.target(this->getAccountBalancesTarget + "?" + queryString); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + std::map > extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::INTEGER)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("origQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("executedQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cummulativeQuoteQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, + }; + if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) { + extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("origClientOrderId", JsonDataType::STRING)}); + } else { + extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOrderId", JsonDataType::STRING)}); + } + if (document.IsObject()) { + Element element; + this->extractOrderInfo(element, document, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } else { + for (const auto& x : document.GetArray()) { + Element element; + this->extractOrderInfo(element, x, extractionFieldNameMap); + elementList.emplace_back(std::move(element)); + } + } + } + void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + switch (request.getOperation()) { + case Request::Operation::GET_ACCOUNT_BALANCES: { + for (const auto& x : document["balances"].GetArray()) { + Element element; + element.insert(CCAPI_EM_ASSET, x["asset"].GetString()); + element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString()); + element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString()); + elementList.emplace_back(std::move(element)); + } + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + void prepareConnect(WsConnection& wsConnection) override { + auto now = UtilTime::now(); + auto hostPort = this->extractHostFromUrl(this->baseUrlRest); + std::string host = hostPort.first; + std::string port = hostPort.second; + http::request req; + req.set(http::field::host, host); + req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); + req.method(http::verb::post); + auto credential = wsConnection.subscriptionList.at(0).getCredential(); + if (credential.empty()) { + credential = this->credentialDefault; + } + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("X-MEXC-APIKEY", apiKey); + std::string queryString; + this->signRequest(queryString, {}, now, credential); + req.target(this->listenKeyTarget + "?" + queryString); + this->sendRequest( + req, + [wsConnection, that = shared_from_base()](const beast::error_code& ec) { + WsConnection thisWsConnection = wsConnection; + that->onFail_(thisWsConnection); + }, + [wsConnection, that = shared_from_base()](const http::response& res) { + WsConnection thisWsConnection = wsConnection; + int statusCode = res.result_int(); + std::string body = res.body(); + if (statusCode / 100 == 2) { + std::string urlWebsocketBase; + try { + rj::Document document; + document.Parse(body.c_str()); + std::string listenKey = document["listenKey"].GetString(); + std::string url = that->baseUrlWs + "?listenKey=" + listenKey; + thisWsConnection.url = url; + that->connect(thisWsConnection); + that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({ + {"listenKey", listenKey}, + }); + return; + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); + } + } + that->onFail_(thisWsConnection); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); + } + void onOpen(wspp::connection_hdl hdl) override { + ExecutionManagementService::onOpen(hdl); + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->setPingListenKeyTimer(wsConnection); + } + std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, + const std::map& credential) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("method", rj::Value("SUBSCRIPTION").Move(), allocator); + rj::Value params(rj::kArrayType); + const auto& fieldSet = subscription.getFieldSet(); + for (const auto& field : subscription.getFieldSet()) { + std::string channelId; + if (field == CCAPI_EM_ORDER_UPDATE) { + channelId = "spot@private.orders.v3.api"; + } else if (field == CCAPI_EM_PRIVATE_TRADE) { + channelId = "spot@private.deals.v3.api"; + } + params.PushBack(rj::Value(channelId.c_str(), allocator).Move(), allocator); + } + document.AddMember("params", params, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + void setPingListenKeyTimer(const WsConnection& wsConnection) { + this->pingListenKeyTimerMapByConnectionIdMap[wsConnection.id] = this->serviceContextPtr->tlsClientPtr->set_timer( + this->pingListenKeyIntervalSeconds * 1000, [wsConnection, that = shared_from_base()](ErrorCode const& ec) { + if (ec) { + return; + } + auto now = UtilTime::now(); + that->setPingListenKeyTimer(wsConnection); + http::request req; + req.set(http::field::host, that->hostRest); + req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); + req.method(http::verb::put); + std::string queryString; + std::map params; + auto listenKey = that->extraPropertyByConnectionIdMap.at(wsConnection.id).at("listenKey"); + params.insert({"listenKey", listenKey}); + for (const auto& param : params) { + queryString += param.first + "=" + Url::urlEncode(param.second); + queryString += "&"; + } + auto credential = wsConnection.subscriptionList.at(0).getCredential(); + if (credential.empty()) { + credential = that->credentialDefault; + } + auto apiKey = mapGetWithDefault(credential, that->apiKeyName); + req.set("X-MEXC-APIKEY", apiKey); + that->signRequest(queryString, {}, now, credential); + req.target(that->listenKeyTarget + "?" + queryString); + that->sendRequest( + req, + [wsConnection, that_2 = that->shared_from_base()](const beast::error_code& ec) { + CCAPI_LOGGER_ERROR("ping listen key fail"); + that_2->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping listen key"); + }, + [wsConnection, that_2 = that->shared_from_base()](const http::response& res) { + CCAPI_LOGGER_DEBUG("ping listen key success"); + }, + that->sessionOptions.httpRequestTimeoutMilliSeconds); + }); + } + void onClose(wspp::connection_hdl hdl) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + if (this->pingListenKeyTimerMapByConnectionIdMap.find(wsConnection.id) != this->pingListenKeyTimerMapByConnectionIdMap.end()) { + this->pingListenKeyTimerMapByConnectionIdMap.at(wsConnection.id)->cancel(); + this->pingListenKeyTimerMapByConnectionIdMap.erase(wsConnection.id); + } + ExecutionManagementService::onClose(hdl); + } + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + const TimePoint& timeReceived) override { + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(subscription, textMessage, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } + Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const TimePoint& timeReceived) { + Event event; + std::vector messageList; + if (document.IsObject() && document.HasMember("code") && std::string(document["code"].GetString()) == "0") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::string msg = document["msg"].GetString(); + if (msg != "PONG") { + bool success = msg != "no subscription success"; + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + } else { + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + std::string c = std::string(document["c"].GetString()); + event.setType(Event::Type::SUBSCRIPTION_DATA); + const rj::Value& d = document["d"]; + std::string instrument = document["s"].GetString(); + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + if (c == "spot@private.deals.v3.api" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(d["T"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + element.insert(CCAPI_TRADE_ID, std::string(d["t"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(d["p"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(d["v"].GetString())); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(d["S"].GetString()) == "1" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_IS_MAKER, std::string(d["m"].GetString())); + element.insert(CCAPI_EM_ORDER_ID, std::string(d["i"].GetString())); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + { + auto it = d.FindMember("c"); + if (it != d.MemberEnd() && !it->value.IsNull()) { + element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(it->value.GetString())); + } + } + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } else if (c == "spot@private.orders.v3.api" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(document["t"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("i", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("c", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("v", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cv", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("ca", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE, std::make_pair("ap", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("V", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("s", JsonDataType::STRING)}, + }; + Element info; + info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + info.insert(CCAPI_EM_ORDER_SIDE, std::string(d["S"].GetString()) == "1" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + this->extractOrderInfo(info, d, extractionFieldNameMap); + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + event.setMessageList(messageList); + return event; + } + std::string listenKeyTarget; + int pingListenKeyIntervalSeconds; + std::map pingListenKeyTimerMapByConnectionIdMap; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc_futures.h new file mode 100644 index 000000000..149b6357b --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc_futures.h @@ -0,0 +1,531 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_FUTURES_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_FUTURES_H_ +#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES +#include "ccapi_cpp/service/ccapi_execution_management_service.h" +namespace ccapi { +class ExecutionManagementServiceMexcFutures : public ExecutionManagementService { + public: + ExecutionManagementServiceMexcFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) + : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC_FUTURES; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_MEXC_FUTURES_API_KEY; + this->apiSecretName = CCAPI_MEXC_FUTURES_API_SECRET; + this->setupCredential({this->apiKeyName, this->apiSecretName}); + this->createOrderTarget = "/api/v1/private/order/submit"; + this->cancelOrderTarget = "/api/v1/private/order/cancel"; + this->cancelOrderWithExternalOidTarget = "/api/v1/private/order/cancel_with_external"; + this->getOrderTarget = "/api/v1/private/order/get/{order_id}"; + this->getOrderWithExternalOidTarget = "/api/v1/private/order/external/{symbol}/{external_oid}"; + this->getOpenOrdersTarget = "/api/v1/private/order/list/open_orders/{symbol}"; + this->cancelOpenOrdersTarget = "/api/v1/private/order/cancel_all"; + this->getAccountBalancesTarget = "/api/v1/private/account/assets"; + this->getAccountPositionsTarget = "/api/v1/private/position/open_positions"; + } + virtual ~ExecutionManagementServiceMexcFutures() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + private: +#endif + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"ping"})", wspp::frame::opcode::text, ec); } + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); } + void createSignature(std::string& signature, std::string& queryString, const std::string& reqMethod, const std::string& host, const std::string& path, + const std::map& queryParamMap, const std::map& credential) { + std::string preSignedText; + preSignedText += reqMethod; + preSignedText += "\n"; + preSignedText += host; + preSignedText += "\n"; + preSignedText += path; + preSignedText += "\n"; + int i = 0; + for (const auto& kv : queryParamMap) { + queryString += kv.first; + queryString += "="; + queryString += kv.second; + if (i < queryParamMap.size() - 1) { + queryString += "&"; + } + i++; + } + preSignedText += queryString; + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); + } + void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, + std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, + const std::map& credential) override { + std::map queryParamMap; + if (!queryString.empty()) { + for (const auto& x : UtilString::split(queryString, "&")) { + auto y = UtilString::split(x, "="); + queryParamMap.insert(std::make_pair(y.at(0), y.at(1))); + } + } + std::string signature; + this->createSignature(signature, queryString, methodString, this->hostRest, path, queryParamMap, credential); + if (!queryString.empty()) { + queryString += "&"; + } + queryString += "Signature="; + queryString += Url::urlEncode(signature); + } + void signRequest(http::request& req, const std::string& path, const std::map& queryParamMap, + const std::map& credential) { + std::string signature; + std::string queryString; + this->createSignature(signature, queryString, std::string(req.method_string()), this->hostRest, path, queryParamMap, credential); + queryString += "&Signature="; + queryString += Url::urlEncode(signature); + req.target(path + "?" + queryString); + } + void signRequest(http::request& req, const std::string& paramString, const std::map& credential) { + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = apiKey; + preSignedText += req.base().at("Request-Time").to_string(); + preSignedText += paramString; + CCAPI_LOGGER_TRACE("preSignedText = " + preSignedText); + CCAPI_LOGGER_TRACE("apiSecret = " + apiSecret); + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true); + req.set("Signature", signature); + } + void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, + const std::map standardizationMap = { + {CCAPI_EM_ORDER_SIDE, "side"}, + {CCAPI_EM_ORDER_QUANTITY, "vol"}, + {CCAPI_EM_ORDER_LIMIT_PRICE, "price"}, + {CCAPI_EM_CLIENT_ORDER_ID, "externalOid"}, + {CCAPI_SYMBOL_ID, "symbol"}, + {CCAPI_EM_ORDER_ID, "orderId"}, + {CCAPI_EM_ORDER_LEVERAGE, "leverage"}, + }) { + for (const auto& kv : param) { + auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + auto value = kv.second; + if (key == CCAPI_EM_ORDER_SIDE || key == CCAPI_EM_ORDER_QUANTITY || key == CCAPI_EM_ORDER_LEVERAGE || key == "vol" || key == "vol" || key == "vol" || + key == "leverage" || key == "side" || key == "type" || key == "openType" || key == "positionId" || key == "positionMode") { + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), std::stoll(value), allocator); + } else if (key == "reduceOnly") { + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator); + } else { + rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); + } + } + } + void appendParam(std::string& queryString, const std::map& param, + const std::map standardizationMap = {}) { + for (const auto& kv : param) { + queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; + queryString += "="; + queryString += Url::urlEncode(kv.second); + queryString += "&"; + } + } + void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) { + rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); + } + void appendSymbolId(std::string& queryString, const std::string& symbolId) { + queryString += "symbol="; + queryString += Url::urlEncode(symbolId); + queryString += "&"; + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + req.set(beast::http::field::content_type, "application/json"); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("ApiKey", apiKey); + std::string timeStr = UtilTime::getISOTimestamp(now); + req.set("Request-Time", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); + Request::Operation operation = request.getOperation(); + switch (operation) { + case Request::Operation::GENERIC_PRIVATE_REQUEST: { + ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::CREATE_ORDER: { + req.method(http::verb::post); + req.target(this->createOrderTarget); + const std::map param = request.getFirstParamWithDefault(); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + this->appendParam(operation, document, allocator, param); + if (param.find("type") == param.end()) { + document.AddMember("type", rj::Value("1").Move(), allocator); + } + if (!symbolId.empty()) { + this->appendSymbolId(document, allocator, symbolId); + } + const auto& marginType = request.getMarginType(); + if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) { + document.AddMember("openType", 2, allocator); + } else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { + document.AddMember("openType", 1, allocator); + } + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + auto body = stringBuffer.GetString(); + req.body() = body; + req.prepare_payload(); + this->signRequest(req, body, credential); + } break; + // case Request::Operation::CANCEL_ORDER: { + // req.method(http::verb::post); + // req.target(this->cancelOrderTarget); + // const std::map param = request.getFirstParamWithDefault(); + // rj::Document document; + // document.SetObject(); + // rj::Document::AllocatorType& allocator = document.GetAllocator(); + // this->appendParam(operation, document, allocator, param); + // if (!symbolId.empty()) { + // this->appendSymbolId(document, allocator, symbolId); + // } + // rj::StringBuffer stringBuffer; + // rj::Writer writer(stringBuffer); + // document.Accept(writer); + // auto body = stringBuffer.GetString(); + // this->signRequest(req, body, credential); + // } break; + // case Request::Operation::GET_ORDER: { + // req.method(http::verb::get); + // std::string queryString; + // const std::map param = request.getFirstParamWithDefault(); + // this->appendParam(queryString, param, + // { + // {CCAPI_EM_ORDER_ID, "ordId"}, + // {CCAPI_EM_CLIENT_ORDER_ID, "clOrdId"}, + // {CCAPI_SYMBOL_ID, "symbol"}, + // }); + // if (!symbolId.empty()) { + // this->appendSymbolId(queryString, symbolId); + // } + // if (queryString.back() == '&') { + // queryString.pop_back(); + // } + // req.target(this->getOrderTarget + "?" + queryString); + // this->signRequest(req, "", credential); + // } break; + // case Request::Operation::GET_OPEN_ORDERS: { + // req.method(http::verb::get); + // std::string queryString; + // const std::map param = request.getFirstParamWithDefault(); + // this->appendParam(queryString, param, + // { + // {CCAPI_EM_ORDER_TYPE, "ordType"}, + // {CCAPI_SYMBOL_ID, "symbol"}, + // }); + // if (!symbolId.empty()) { + // this->appendSymbolId(queryString, symbolId); + // } + // if (queryString.back() == '&') { + // queryString.pop_back(); + // } + // req.target(queryString.empty() ? this->getOpenOrdersTarget : this->getOpenOrdersTarget + "?" + queryString); + // this->signRequest(req, "", credential); + // } break; + // case Request::Operation::GET_ACCOUNT_BALANCES: { + // req.method(http::verb::get); + // req.target(this->getAccountBalancesTarget); + // this->signRequest(req, "", credential); + // } break; + // case Request::Operation::GET_ACCOUNT_POSITIONS: { + // req.method(http::verb::get); + // req.target(this->getAccountPositionsTarget); + // this->signRequest(req, "", credential); + // } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + // this->extractOrderInfoFromRequest(elementList, document); + } + void extractOrderInfoFromRequest(std::vector& elementList, const rj::Document& document) { + // const std::map >& extractionFieldNameMap = { + // {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)}, + // {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}}; + // const rj::Value& data = document["data"]; + // if (data.IsObject()) { + // Element element; + // this->extractOrderInfo(element, data, extractionFieldNameMap); + // elementList.emplace_back(std::move(element)); + // } else { + // for (const auto& x : data.GetArray()) { + // Element element; + // this->extractOrderInfo(element, x, extractionFieldNameMap); + // elementList.emplace_back(std::move(element)); + // } + // } + } + void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, + const rj::Document& document) override { + // switch (request.getOperation()) { + // case Request::Operation::GET_ACCOUNT_BALANCES: { + // for (const auto& x : document["data"][0]["details"].GetArray()) { + // Element element; + // element.insert(CCAPI_EM_ASSET, x["ccy"].GetString()); + // std::string availEq = x["availEq"].GetString(); + // element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, availEq.empty() ? x["availBal"].GetString() : availEq); + // element.insert(CCAPI_EM_QUANTITY_TOTAL, x["eq"].GetString()); + // elementList.emplace_back(std::move(element)); + // } + // } break; + // case Request::Operation::GET_ACCOUNT_POSITIONS: { + // for (const auto& x : document["data"].GetArray()) { + // Element element; + // element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + // element.insert(CCAPI_EM_POSITION_SIDE, x["posSide"].GetString()); + // std::string availPos = x["availPos"].GetString(); + // std::string positionQuantity = availPos.empty() ? x["pos"].GetString() : availPos; + // element.insert(CCAPI_EM_POSITION_QUANTITY, positionQuantity); + // element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPx"].GetString()); + // element.insert(CCAPI_EM_POSITION_LEVERAGE, x["lever"].GetString()); + // elementList.emplace_back(std::move(element)); + // } + // } break; + // default: + // CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + // } + } + void extractOrderInfo(Element& element, const rj::Value& x, + const std::map >& extractionFieldNameMap) override { + // ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap); + // { + // auto it1 = x.FindMember("accFillSz"); + // auto it2 = x.FindMember("avgPx"); + // if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) { + // auto it1Str = std::string(it1->value.GetString()); + // auto it2Str = std::string(it2->value.GetString()); + // if (!it1Str.empty() && !it2Str.empty()) { + // element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))); + // } + // } + // } + } + std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, + const std::map& credential) override { + std::vector sendStringList; + // rj::Document document; + // document.SetObject(); + // auto& allocator = document.GetAllocator(); + // document.AddMember("op", rj::Value("login").Move(), allocator); + // rj::Value arg(rj::kObjectType); + // auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + // auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + // auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); + // std::string ts = std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); + // arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator); + // arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator); + // arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator); + // std::string signData = ts + "GET" + "/users/self/verify"; + // std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData)); + // arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator); + // rj::Value args(rj::kArrayType); + // args.PushBack(arg, allocator); + // document.AddMember("args", args, allocator); + // rj::StringBuffer stringBuffer; + // rj::Writer writer(stringBuffer); + // document.Accept(writer); + // std::string sendString = stringBuffer.GetString(); + // sendStringList.push_back(sendString); + return sendStringList; + } + void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + const TimePoint& timeReceived) override { + // if (textMessage != "pong") { + // rj::Document document; + // document.Parse(textMessage.c_str()); + // auto it = document.FindMember("event"); + // std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; + // if (eventStr == "login") { + // rj::Document document; + // document.SetObject(); + // auto& allocator = document.GetAllocator(); + // document.AddMember("op", rj::Value("subscribe").Move(), allocator); + // rj::Value args(rj::kArrayType); + // const auto& fieldSet = subscription.getFieldSet(); + // const auto& instrumentSet = subscription.getInstrumentSet(); + // for (const auto& field : fieldSet) { + // std::string channel; + // if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + // channel = "orders"; + // } + // for (const auto& instrument : instrumentSet) { + // rj::Value arg(rj::kObjectType); + // arg.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator); + // arg.AddMember("symbol", rj::Value(instrument.c_str(), allocator).Move(), allocator); + // arg.AddMember("instType", rj::Value("ANY").Move(), allocator); + // args.PushBack(arg, allocator); + // } + // } + // document.AddMember("args", args, allocator); + // rj::StringBuffer stringBufferSubscribe; + // rj::Writer writerSubscribe(stringBufferSubscribe); + // document.Accept(writerSubscribe); + // std::string sendString = stringBufferSubscribe.GetString(); + // ErrorCode ec; + // this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); + // if (ec) { + // this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + // } + // } else { + // Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived); + // if (!event.getMessageList().empty()) { + // this->eventHandler(event, nullptr); + // } + // } + // } + } + Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr, + const TimePoint& timeReceived) { + Event event; + // std::vector messageList; + // Message message; + // message.setTimeReceived(timeReceived); + // const auto& correlationId = subscription.getCorrelationId(); + // message.setCorrelationIdList({correlationId}); + // const auto& fieldSet = subscription.getFieldSet(); + // const auto& instrumentSet = subscription.getInstrumentSet(); + // if (eventStr.empty()) { + // auto it = document.FindMember("op"); + // std::string op = it != document.MemberEnd() ? it->value.GetString() : ""; + // if (op == "order" || op == "cancel-order") { + // event.setType(Event::Type::RESPONSE); + // std::string code = document["code"].GetString(); + // if (code != "0") { + // message.setType(Message::Type::RESPONSE_ERROR); + // Element element; + // element.insert(CCAPI_ERROR_MESSAGE, textMessage); + // message.setElementList({element}); + // message.setSecondaryCorrelationIdMap({ + // {correlationId, document["id"].GetString()}, + // }); + // messageList.emplace_back(std::move(message)); + // } else { + // std::vector elementList; + // if (op == "order") { + // message.setType(Message::Type::CREATE_ORDER); + // } else if (op == "cancel-order") { + // message.setType(Message::Type::CANCEL_ORDER); + // } + // this->extractOrderInfoFromRequest(elementList, document); + // message.setElementList(elementList); + // message.setSecondaryCorrelationIdMap({ + // {correlationId, document["id"].GetString()}, + // }); + // messageList.emplace_back(std::move(message)); + // } + // } else { + // const rj::Value& arg = document["arg"]; + // const rj::Value& data = document["data"]; + // std::string channel = std::string(arg["channel"].GetString()); + // event.setType(Event::Type::SUBSCRIPTION_DATA); + // std::string instrument = arg["symbol"].GetString(); + // if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + // if (channel == "orders") { + // if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + // for (const auto& x : data.GetArray()) { + // std::string tradeId = x["tradeId"].GetString(); + // if (!tradeId.empty()) { + // Message message; + // message.setTimeReceived(timeReceived); + // message.setCorrelationIdList({subscription.getCorrelationId()}); + // message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString())))); + // message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + // std::vector elementList; + // Element element; + // element.insert(CCAPI_TRADE_ID, tradeId); + // element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString())); + // element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString())); + // element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + // element.insert(CCAPI_EM_POSITION_SIDE, std::string(x["posSide"].GetString())); + // element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0"); + // element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString())); + // element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString())); + // element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + // element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString())); + // element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString())); + // elementList.emplace_back(std::move(element)); + // message.setElementList(elementList); + // messageList.emplace_back(std::move(message)); + // } + // } + // } + // if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + // for (const auto& x : data.GetArray()) { + // Message message; + // message.setTimeReceived(timeReceived); + // message.setCorrelationIdList({subscription.getCorrelationId()}); + // message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString())))); + // message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + // const std::map >& extractionFieldNameMap = { + // {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)}, + // {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)}, + // {CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)}, + // }; + // Element info; + // this->extractOrderInfo(info, x, extractionFieldNameMap); + // info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + // std::vector elementList; + // elementList.emplace_back(std::move(info)); + // message.setElementList(elementList); + // messageList.emplace_back(std::move(message)); + // } + // } + // } + // } + // } + // } else if (eventStr == "subscribe") { + // event.setType(Event::Type::SUBSCRIPTION_STATUS); + // message.setType(Message::Type::SUBSCRIPTION_STARTED); + // Element element; + // element.insert(CCAPI_INFO_MESSAGE, textMessage); + // message.setElementList({element}); + // messageList.emplace_back(std::move(message)); + // } else if (eventStr == "error") { + // event.setType(Event::Type::SUBSCRIPTION_STATUS); + // message.setType(Message::Type::SUBSCRIPTION_FAILURE); + // Element element; + // element.insert(CCAPI_ERROR_MESSAGE, textMessage); + // message.setElementList({element}); + // messageList.emplace_back(std::move(message)); + // } + // event.setMessageList(messageList); + return event; + } + std::string cancelOrderWithExternalOidTarget, getOrderWithExternalOidTarget; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_FUTURES_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okex.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h similarity index 71% rename from linux/include/ccapi_cpp/service/ccapi_execution_management_service_okex.h rename to linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h index 115ea5648..5c426dece 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okex.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h @@ -1,27 +1,36 @@ -#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_ -#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKX_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKX_H_ #ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT -#ifdef CCAPI_ENABLE_EXCHANGE_OKEX +#ifdef CCAPI_ENABLE_EXCHANGE_OKX #include "ccapi_cpp/service/ccapi_execution_management_service.h" namespace ccapi { -class ExecutionManagementServiceOkex : public ExecutionManagementService { +class ExecutionManagementServiceOkx : public ExecutionManagementService { public: - ExecutionManagementServiceOkex(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - ServiceContextPtr serviceContextPtr) + ExecutionManagementServiceOkx(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + ServiceContextPtr serviceContextPtr) : ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { - this->exchangeName = CCAPI_EXCHANGE_NAME_OKEX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKEX_PRIVATE_WS_PATH; + this->exchangeName = CCAPI_EXCHANGE_NAME_OKX; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKX_PRIVATE_WS_PATH; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } - this->apiKeyName = CCAPI_OKEX_API_KEY; - this->apiSecretName = CCAPI_OKEX_API_SECRET; - this->apiPassphraseName = CCAPI_OKEX_API_PASSPHRASE; - this->apiXSimulatedTradingName = CCAPI_OKEX_API_X_SIMULATED_TRADING; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_OKX_API_KEY; + this->apiSecretName = CCAPI_OKX_API_SECRET; + this->apiPassphraseName = CCAPI_OKX_API_PASSPHRASE; + this->apiXSimulatedTradingName = CCAPI_OKX_API_X_SIMULATED_TRADING; this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName, this->apiXSimulatedTradingName}); this->createOrderTarget = "/api/v5/trade/order"; this->cancelOrderTarget = "/api/v5/trade/cancel-order"; @@ -30,13 +39,17 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { this->getAccountBalancesTarget = "/api/v5/account/balance"; this->getAccountPositionsTarget = "/api/v5/account/positions"; } - virtual ~ExecutionManagementServiceOkex() {} + virtual ~ExecutionManagementServiceOkx() {} #ifndef CCAPI_EXPOSE_INTERNAL private: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); } +#endif + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); } void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, const std::map& credential) override { @@ -66,7 +79,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { req.body() = body; req.prepare_payload(); } - void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, + void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, const std::map standardizationMap = { {CCAPI_EM_ORDER_SIDE, "side"}, {CCAPI_EM_ORDER_QUANTITY, "sz"}, @@ -83,6 +96,9 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { } rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator); } + if (operation == Request::Operation::CREATE_ORDER && param.find("tag") == param.end()) { + rjValue.AddMember("tag", CCAPI_OKX_API_BROKER_CODE, allocator); + } } void appendParam(std::string& queryString, const std::map& param, const std::map standardizationMap = {}) { @@ -114,7 +130,8 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { if (apiXSimulatedTrading == "1") { req.set("x-simulated-trading", "1"); } - switch (request.getOperation()) { + Request::Operation operation = request.getOperation(); + switch (operation) { case Request::Operation::GENERIC_PRIVATE_REQUEST: { ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential); } break; @@ -125,7 +142,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { rj::Document document; document.SetObject(); rj::Document::AllocatorType& allocator = document.GetAllocator(); - this->appendParam(document, allocator, param); + this->appendParam(operation, document, allocator, param); if (param.find("tdMode") == param.end()) { document.AddMember("tdMode", rj::Value("cash").Move(), allocator); } @@ -148,7 +165,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { rj::Document document; document.SetObject(); rj::Document::AllocatorType& allocator = document.GetAllocator(); - this->appendParam(document, allocator, param); + this->appendParam(operation, document, allocator, param); if (!symbolId.empty()) { this->appendSymbolId(document, allocator, symbolId); } @@ -213,14 +230,17 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { int wsRequestId, const TimePoint& now, const std::string& symbolId, const std::map& credential) override { document.SetObject(); - document.AddMember("id", rj::Value(std::to_string(wsRequestId).c_str(), allocator).Move(), allocator); - switch (request.getOperation()) { + const auto& secondaryCorrelationId = request.getSecondaryCorrelationId(); + document.AddMember("id", rj::Value((secondaryCorrelationId.empty() ? std::to_string(wsRequestId) : secondaryCorrelationId).c_str(), allocator).Move(), + allocator); + Request::Operation operation = request.getOperation(); + switch (operation) { case Request::Operation::CREATE_ORDER: { document.AddMember("op", rj::Value("order").Move(), allocator); rj::Value args(rj::kArrayType); const std::map param = request.getFirstParamWithDefault(); rj::Value arg(rj::kObjectType); - this->appendParam(arg, allocator, param); + this->appendParam(operation, arg, allocator, param); if (param.find("tdMode") == param.end()) { arg.AddMember("tdMode", rj::Value("cash").Move(), allocator); } @@ -238,7 +258,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { rj::Value args(rj::kArrayType); const std::map param = request.getFirstParamWithDefault(); rj::Value arg(rj::kObjectType); - this->appendParam(arg, allocator, param); + this->appendParam(operation, arg, allocator, param); if (!symbolId.empty()) { this->appendSymbolId(arg, allocator, symbolId); } @@ -297,7 +317,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { std::string availPos = x["availPos"].GetString(); std::string positionQuantity = availPos.empty() ? x["pos"].GetString() : availPos; element.insert(CCAPI_EM_POSITION_QUANTITY, positionQuantity); - element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["avgPx"].GetString()) * std::stod(positionQuantity))); + element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPx"].GetString()); element.insert(CCAPI_EM_POSITION_LEVERAGE, x["lever"].GetString()); elementList.emplace_back(std::move(element)); } @@ -316,7 +336,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { auto it1Str = std::string(it1->value.GetString()); auto it2Str = std::string(it2->value.GetString()); if (!it1Str.empty() && !it2Str.empty()) { - element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::to_string(std::stod(it1Str) * std::stod(it2Str))); + element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))); } } } @@ -349,19 +369,31 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, - const TimePoint& timeReceived) override { - auto it = document.FindMember("event"); - std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; - if (eventStr == "login") { + void onTextMessage( +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage +#else + std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView +#endif + , + const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + std::string textMessage(textMessageView); +#endif + if (textMessage != "pong") { rj::Document document; - document.SetObject(); - auto& allocator = document.GetAllocator(); - document.AddMember("op", rj::Value("subscribe").Move(), allocator); - rj::Value args(rj::kArrayType); - const auto& fieldSet = subscription.getFieldSet(); - const auto& instrumentSet = subscription.getInstrumentSet(); - for (const auto& field : fieldSet) { + document.Parse(textMessage.c_str()); + auto it = document.FindMember("event"); + std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; + if (eventStr == "login") { + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); std::string channel; if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { channel = "orders"; @@ -373,21 +405,25 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { arg.AddMember("instType", rj::Value("ANY").Move(), allocator); args.PushBack(arg, allocator); } - } - document.AddMember("args", args, allocator); - rj::StringBuffer stringBufferSubscribe; - rj::Writer writerSubscribe(stringBufferSubscribe); - document.Accept(writerSubscribe); - std::string sendString = stringBufferSubscribe.GetString(); - ErrorCode ec; - this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); - if (ec) { - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); - } - } else { - Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived); - if (!event.getMessageList().empty()) { - this->eventHandler(event, nullptr); + document.AddMember("args", args, allocator); + rj::StringBuffer stringBufferSubscribe; + rj::Writer writerSubscribe(stringBufferSubscribe); + document.Accept(writerSubscribe); + std::string sendString = stringBufferSubscribe.GetString(); + ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, sendString, ec); +#endif + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } else { + Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } } } } @@ -397,7 +433,8 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { std::vector messageList; Message message; message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); + const auto& correlationId = subscription.getCorrelationId(); + message.setCorrelationIdList({correlationId}); const auto& fieldSet = subscription.getFieldSet(); const auto& instrumentSet = subscription.getInstrumentSet(); if (eventStr.empty()) { @@ -411,6 +448,9 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { Element element; element.insert(CCAPI_ERROR_MESSAGE, textMessage); message.setElementList({element}); + message.setSecondaryCorrelationIdMap({ + {correlationId, document["id"].GetString()}, + }); messageList.emplace_back(std::move(message)); } else { std::vector elementList; @@ -421,6 +461,9 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { } this->extractOrderInfoFromRequest(elementList, document); message.setElementList(elementList); + message.setSecondaryCorrelationIdMap({ + {correlationId, document["id"].GetString()}, + }); messageList.emplace_back(std::move(message)); } } else { @@ -430,57 +473,61 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { event.setType(Event::Type::SUBSCRIPTION_DATA); std::string instrument = arg["instId"].GetString(); if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - if (channel == "orders" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { - for (const auto& x : data.GetArray()) { - std::string tradeId = x["tradeId"].GetString(); - if (!tradeId.empty()) { + if (channel == "orders") { + if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + for (const auto& x : data.GetArray()) { + std::string tradeId = x["tradeId"].GetString(); + if (!tradeId.empty()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({subscription.getCorrelationId()}); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + element.insert(CCAPI_TRADE_ID, tradeId); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString())); + element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_EM_POSITION_SIDE, std::string(x["posSide"].GetString())); + element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0"); + element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString())); + element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString())); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); + element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString())); + element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString())); + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } + if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + for (const auto& x : data.GetArray()) { Message message; message.setTimeReceived(timeReceived); message.setCorrelationIdList({subscription.getCorrelationId()}); - message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString())))); - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + const std::map >& extractionFieldNameMap = { + {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)}, + {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE, std::make_pair("avgPx", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)}, + }; + Element info; + this->extractOrderInfo(info, x, extractionFieldNameMap); + info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); std::vector elementList; - Element element; - element.insert(CCAPI_TRADE_ID, tradeId); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString())); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString())); - element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); - element.insert(CCAPI_EM_POSITION_SIDE, std::string(x["posSide"].GetString())); - element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0"); - element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString())); - element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString())); - element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString())); - element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString())); - elementList.emplace_back(std::move(element)); + elementList.emplace_back(std::move(info)); message.setElementList(elementList); messageList.emplace_back(std::move(message)); } } - } else if (channel == "orders" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { - for (const auto& x : data.GetArray()) { - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString())))); - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); - const std::map >& extractionFieldNameMap = { - {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)}, - {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)}, - }; - Element info; - this->extractOrderInfo(info, x, extractionFieldNameMap); - info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - std::vector elementList; - elementList.emplace_back(std::move(info)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } } } } @@ -508,4 +555,4 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService { } /* namespace ccapi */ #endif #endif -#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_ +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKX_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_whitebit.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_whitebit.h new file mode 100644 index 000000000..e69de29bb diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service.h index fcd5f15cd..761600108 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service.h @@ -6,6 +6,7 @@ #include #include +#include "ccapi_cpp/ccapi_hmac.h" #include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_util_private.h" #include "ccapi_cpp/service/ccapi_service.h" @@ -35,17 +36,23 @@ class MarketDataService : public Service { } } } + for (const auto& x : this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap) { + for (const auto& y : x.second) { + y.second->cancel(); + } + } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET // subscriptions are grouped and each group creates a unique websocket connection void subscribe(std::vector& subscriptionList) override { CCAPI_LOGGER_FUNCTION_ENTER; - CCAPI_LOGGER_DEBUG("this->baseUrl = " + this->baseUrl); + CCAPI_LOGGER_DEBUG("this->baseUrlWs = " + this->baseUrlWs); if (this->shouldContinue.load()) { for (auto& x : this->groupSubscriptionListByInstrumentGroup(subscriptionList)) { auto instrumentGroup = x.first; auto subscriptionListGivenInstrumentGroup = x.second; - wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [that = shared_from_base(), instrumentGroup, - subscriptionListGivenInstrumentGroup]() mutable { + boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base(), instrumentGroup, + subscriptionListGivenInstrumentGroup]() mutable { auto now = UtilTime::now(); for (auto& subscription : subscriptionListGivenInstrumentGroup) { subscription.setTimeSent(now); @@ -70,7 +77,11 @@ class MarketDataService : public Service { that->subscribeToExchange(wsConnection); } else { auto url = UtilString::split(instrumentGroup, "|").at(0); - WsConnection wsConnection(url, instrumentGroup, subscriptionListGivenInstrumentGroup); + auto credential = subscriptionListGivenInstrumentGroup.at(0).getCredential(); + if (credential.empty()) { + credential = that->credentialDefault; + } + WsConnection wsConnection(url, instrumentGroup, subscriptionListGivenInstrumentGroup, credential); that->prepareConnect(wsConnection); } }); @@ -78,12 +89,79 @@ class MarketDataService : public Service { } CCAPI_LOGGER_FUNCTION_EXIT; } +#else + // subscriptions are grouped and each group creates a unique websocket connection + void subscribe(std::vector& subscriptionList) override { + CCAPI_LOGGER_FUNCTION_ENTER; + CCAPI_LOGGER_DEBUG("this->baseUrlWs = " + this->baseUrlWs); + if (this->shouldContinue.load()) { + for (auto& x : this->groupSubscriptionListByInstrumentGroup(subscriptionList)) { + auto instrumentGroup = x.first; + auto subscriptionListGivenInstrumentGroup = x.second; + boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base(), instrumentGroup, + subscriptionListGivenInstrumentGroup]() mutable { + auto now = UtilTime::now(); + for (auto& subscription : subscriptionListGivenInstrumentGroup) { + subscription.setTimeSent(now); + } + std::map> wsConnectionIdListByInstrumentGroupMap = invertMapMulti(that->instrumentGroupByWsConnectionIdMap); + if (wsConnectionIdListByInstrumentGroupMap.find(instrumentGroup) != wsConnectionIdListByInstrumentGroupMap.end() && + that->subscriptionStatusByInstrumentGroupInstrumentMap.find(instrumentGroup) != that->subscriptionStatusByInstrumentGroupInstrumentMap.end()) { + auto wsConnectionId = wsConnectionIdListByInstrumentGroupMap.at(instrumentGroup).at(0); + auto wsConnectionPtr = that->wsConnectionByIdMap.at(wsConnectionId); + WsConnection& wsConnection = *wsConnectionPtr; + for (const auto& subscription : subscriptionListGivenInstrumentGroup) { + auto instrument = subscription.getInstrument(); + if (that->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup].find(instrument) != + that->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup].end()) { + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "already subscribed: " + toString(subscription)); + return; + } + wsConnection.subscriptionList.push_back(subscription); + that->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING; + that->prepareSubscription(wsConnection, subscription); + } + CCAPI_LOGGER_INFO("about to subscribe to exchange"); + that->subscribeToExchange(wsConnectionPtr); + } else { + auto url = UtilString::split(instrumentGroup, "|").at(0); + auto credential = subscriptionListGivenInstrumentGroup.at(0).getCredential(); + if (credential.empty()) { + credential = that->credentialDefault; + } + std::shared_ptr>> streamPtr(nullptr); + try { + streamPtr = that->createStream>>( + that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs); + } catch (const beast::error_code& ec) { + CCAPI_LOGGER_TRACE("fail"); + std::vector correlationIdList; + correlationIdList.reserve(subscriptionListGivenInstrumentGroup.size()); + std::transform(subscriptionListGivenInstrumentGroup.cbegin(), subscriptionListGivenInstrumentGroup.cend(), correlationIdList.begin(), + [](Subscription subscription) { return subscription.getCorrelationId(); }); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", correlationIdList); + return; + } + std::shared_ptr wsConnectionPtr(new WsConnection(url, instrumentGroup, subscriptionListGivenInstrumentGroup, credential, streamPtr)); + CCAPI_LOGGER_WARN("about to subscribe with new wsConnectionPtr " + toString(*wsConnectionPtr)); + that->prepareConnect(wsConnectionPtr); + } + }); + } + } + CCAPI_LOGGER_FUNCTION_EXIT; + } +#endif #ifndef CCAPI_EXPOSE_INTERNAL protected: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET typedef wspp::lib::error_code ErrorCode; typedef wspp::lib::function TimerHandler; +#else + typedef boost::system::error_code ErrorCode; +#endif std::map> groupSubscriptionListByInstrumentGroup(const std::vector& subscriptionList) { std::map> groups; for (const auto& subscription : subscriptionList) { @@ -93,7 +171,7 @@ class MarketDataService : public Service { return groups; } virtual std::string getInstrumentGroup(const Subscription& subscription) { - return this->baseUrl + "|" + subscription.getField() + "|" + subscription.getSerializedOptions(); + return this->baseUrlWs + "|" + subscription.getField() + "|" + subscription.getSerializedOptions() + "|" + subscription.getSerializedCredential(); } void prepareSubscription(const WsConnection& wsConnection, const Subscription& subscription) { auto instrument = subscription.getInstrument(); @@ -107,7 +185,7 @@ class MarketDataService : public Service { std::string channelId = this->sessionConfigs.getExchangeFieldWebsocketChannelMap().at(this->exchangeName).at(field); CCAPI_LOGGER_TRACE("channelId = " + channelId); CCAPI_LOGGER_TRACE("this->exchangeName = " + this->exchangeName); - this->prepareSubscriptionDetail(channelId, symbolId, field, wsConnection, optionMap); + this->prepareSubscriptionDetail(channelId, symbolId, field, wsConnection, subscription, optionMap); CCAPI_LOGGER_TRACE("channelId = " + channelId); this->correlationIdListByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].push_back(subscription.getCorrelationId()); this->subscriptionListByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].push_back(subscription); @@ -118,6 +196,7 @@ class MarketDataService : public Service { CCAPI_LOGGER_TRACE("this->correlationIdListByConnectionIdChannelSymbolIdMap = " + toString(this->correlationIdListByConnectionIdChannelIdSymbolIdMap)); CCAPI_LOGGER_FUNCTION_EXIT; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void processMarketDataMessageList(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) { CCAPI_LOGGER_TRACE("marketDataMessageList = " + toString(marketDataMessageList)); @@ -198,7 +277,8 @@ class MarketDataService : public Service { correlationIdList, isSolicited); } } else { - CCAPI_LOGGER_WARN("websocket event type is unknown!"); + CCAPI_LOGGER_WARN("websocket event type is unknown for " + toString(marketDataMessage)); + CCAPI_LOGGER_WARN("textMessage is " + textMessage); } } } @@ -231,7 +311,395 @@ class MarketDataService : public Service { this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived); CCAPI_LOGGER_FUNCTION_EXIT; } - void updateOrderBook(std::map& snapshot, Decimal& price, std::string& size, bool sizeMayHaveTrailingZero = false) { + virtual void onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, + const std::string& exchangeSubscriptionId, std::string const& reason) { + std::string errorMessage = "incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + textMessage + + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId + + ", reason = " + reason; + CCAPI_LOGGER_ERROR(errorMessage); + ErrorCode ec; + this->close(wsConnection, hdl, websocketpp::close::status::normal, "incorrect states found: " + reason, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, "shutdown"); + } + this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, errorMessage); + } + void connect(WsConnection& wsConnection) override { + CCAPI_LOGGER_FUNCTION_ENTER; + Service::connect(wsConnection); + this->instrumentGroupByWsConnectionIdMap.insert(std::pair(wsConnection.id, wsConnection.group)); + CCAPI_LOGGER_DEBUG("this->instrumentGroupByWsConnectionIdMap = " + toString(this->instrumentGroupByWsConnectionIdMap)); + CCAPI_LOGGER_FUNCTION_EXIT; + } + void onOpen(wspp::connection_hdl hdl) override { + CCAPI_LOGGER_FUNCTION_ENTER; + auto now = UtilTime::now(); + Service::onOpen(hdl); + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + auto credential = wsConnection.credential; + if (!credential.empty()) { + this->logonToExchange(wsConnection, now, credential); + } else { + this->startSubscribe(wsConnection); + } + } + void onFail_(WsConnection& wsConnection) override { + WsConnection thisWsConnection = wsConnection; + Service::onFail_(wsConnection); + this->instrumentGroupByWsConnectionIdMap.erase(thisWsConnection.id); + } + void clearStates(WsConnection& wsConnection) override { + Service::clearStates(wsConnection); + this->fieldByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->optionMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->subscriptionListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id); + this->snapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->snapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->previousConflateSnapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->previousConflateSnapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->processedInitialTradeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + if (this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.end()) { + for (const auto& x : this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { + for (const auto& y : x.second) { + y.second->cancel(); + } + } + this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + } + this->openByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->highByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->lowByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->closeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->orderBookChecksumByConnectionIdSymbolIdMap.erase(wsConnection.id); + this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.erase(wsConnection.id); + if (this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.find(wsConnection.id) != + this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.end()) { + for (const auto& x : this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id)) { + x.second->cancel(); + } + this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id); + } + this->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id); + } + void onClose(wspp::connection_hdl hdl) override { + CCAPI_LOGGER_FUNCTION_ENTER; + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id); + this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id); + this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id); + this->correlationIdByConnectionIdMap.erase(wsConnection.id); + Service::onClose(hdl); + } + virtual void subscribeToExchange(const WsConnection& wsConnection) { + CCAPI_LOGGER_INFO("exchange is " + this->exchangeName); + std::vector sendStringList; + if (this->correlationIdByConnectionIdMap.find(wsConnection.id) == this->correlationIdByConnectionIdMap.end()) { + sendStringList = this->createSendStringList(wsConnection); + } else { + auto subscription = wsConnection.subscriptionList.at(0); + sendStringList = std::vector(1, subscription.getRawOptions()); + } + for (const auto& sendString : sendStringList) { + CCAPI_LOGGER_INFO("sendString = " + sendString); + ErrorCode ec; + this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } + } + void startSubscribe(WsConnection& wsConnection) { + auto instrumentGroup = wsConnection.group; + for (const auto& subscription : wsConnection.subscriptionList) { + auto instrument = subscription.getInstrument(); + this->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING; + if (subscription.getRawOptions().empty()) { + this->prepareSubscription(wsConnection, subscription); + } else { + this->correlationIdByConnectionIdMap.insert({wsConnection.id, subscription.getCorrelationId()}); + } + } + CCAPI_LOGGER_INFO("about to subscribe to exchange"); + this->subscribeToExchange(wsConnection); + } + virtual void logonToExchange(const WsConnection& wsConnection, const TimePoint& now, const std::map& credential) { + CCAPI_LOGGER_INFO("about to logon to exchange"); + CCAPI_LOGGER_INFO("exchange is " + this->exchangeName); + auto subscriptionList = wsConnection.subscriptionList; + std::vector sendStringList = this->createSendStringListFromSubscriptionList(wsConnection, subscriptionList, now, credential); + for (const auto& sendString : sendStringList) { + CCAPI_LOGGER_INFO("sendString = " + sendString); + ErrorCode ec; + this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } + } +#else + void processMarketDataMessageList(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived, + Event& event, std::vector& marketDataMessageList) { + CCAPI_LOGGER_TRACE("marketDataMessageList = " + toString(marketDataMessageList)); + WsConnection& wsConnection = *wsConnectionPtr; + event.setType(Event::Type::SUBSCRIPTION_DATA); + for (auto& marketDataMessage : marketDataMessageList) { + if (marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH || + marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE || + marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE) { + if (this->sessionOptions.warnLateEventMaxMilliSeconds > 0 && + std::chrono::duration_cast(timeReceived - marketDataMessage.tp).count() > + this->sessionOptions.warnLateEventMaxMilliSeconds && + marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) { + CCAPI_LOGGER_WARN("late websocket message: timeReceived = " + toString(timeReceived) + ", marketDataMessage.tp = " + toString(marketDataMessage.tp) + + ", wsConnection = " + toString(wsConnection)); + } + + std::string& exchangeSubscriptionId = marketDataMessage.exchangeSubscriptionId; + CCAPI_LOGGER_TRACE("this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap = " + + toString(this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap)); + std::string& channelId = + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID); + std::string& symbolId = + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID); + auto& field = this->fieldByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + CCAPI_LOGGER_TRACE("this->optionMapByConnectionIdChannelIdSymbolIdMap = " + toString(this->optionMapByConnectionIdChannelIdSymbolIdMap)); + CCAPI_LOGGER_TRACE("wsConnection = " + toString(wsConnection)); + CCAPI_LOGGER_TRACE("channelId = " + toString(channelId)); + CCAPI_LOGGER_TRACE("symbolId = " + toString(symbolId)); + auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + CCAPI_LOGGER_TRACE("optionMap = " + toString(optionMap)); + auto& correlationIdList = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + CCAPI_LOGGER_TRACE("correlationIdList = " + toString(correlationIdList)); + if (marketDataMessage.data.find(MarketDataMessage::DataType::BID) != marketDataMessage.data.end() || + marketDataMessage.data.find(MarketDataMessage::DataType::ASK) != marketDataMessage.data.end()) { + std::map& snapshotBid = this->snapshotBidByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + std::map& snapshotAsk = this->snapshotAskByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] && + marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) { + this->processOrderBookUpdate(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field, optionMap, + correlationIdList, snapshotBid, snapshotAsk); + if (this->sessionOptions.enableCheckOrderBookChecksum && + this->orderBookChecksumByConnectionIdSymbolIdMap.find(wsConnection.id) != this->orderBookChecksumByConnectionIdSymbolIdMap.end() && + this->orderBookChecksumByConnectionIdSymbolIdMap.at(wsConnection.id).find(symbolId) != + this->orderBookChecksumByConnectionIdSymbolIdMap.at(wsConnection.id).end()) { + bool shouldProcessRemainingMessage = true; + std::string receivedOrderBookChecksumStr = this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId]; + if (!this->checkOrderBookChecksum(snapshotBid, snapshotAsk, receivedOrderBookChecksumStr, shouldProcessRemainingMessage)) { + CCAPI_LOGGER_ERROR("snapshotBid = " + toString(snapshotBid)); + CCAPI_LOGGER_ERROR("snapshotAsk = " + toString(snapshotAsk)); + this->onIncorrectStatesFound(wsConnectionPtr, textMessage, timeReceived, exchangeSubscriptionId, "order book incorrect checksum found"); + } + if (!shouldProcessRemainingMessage) { + return; + } + } + if (this->sessionOptions.enableCheckOrderBookCrossed) { + bool shouldProcessRemainingMessage = true; + if (!this->checkOrderBookCrossed(snapshotBid, snapshotAsk, shouldProcessRemainingMessage)) { + CCAPI_LOGGER_ERROR("lastNToString(snapshotBid, 1) = " + lastNToString(snapshotBid, 1)); + CCAPI_LOGGER_ERROR("firstNToString(snapshotAsk, 1) = " + firstNToString(snapshotAsk, 1)); + this->onIncorrectStatesFound(wsConnectionPtr, textMessage, timeReceived, exchangeSubscriptionId, "order book crossed market found"); + } + if (!shouldProcessRemainingMessage) { + return; + } + } + } else if (marketDataMessage.recapType == MarketDataMessage::RecapType::SOLICITED) { + this->processOrderBookInitial(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field, + optionMap, correlationIdList, snapshotBid, snapshotAsk); + } + CCAPI_LOGGER_TRACE("snapshotBid.size() = " + toString(snapshotBid.size())); + CCAPI_LOGGER_TRACE("snapshotAsk.size() = " + toString(snapshotAsk.size())); + } + if (marketDataMessage.data.find(MarketDataMessage::DataType::TRADE) != marketDataMessage.data.end() || + marketDataMessage.data.find(MarketDataMessage::DataType::AGG_TRADE) != marketDataMessage.data.end()) { + bool isSolicited = marketDataMessage.recapType == MarketDataMessage::RecapType::SOLICITED; + this->processTrade(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field, optionMap, + correlationIdList, isSolicited); + } + } else { + CCAPI_LOGGER_WARN("websocket event type is unknown for " + toString(marketDataMessage)); + CCAPI_LOGGER_WARN("textMessage is " + std::string(textMessage)); + } + } + } + void onTextMessage(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived) override { + CCAPI_LOGGER_FUNCTION_ENTER; + if (this->correlationIdByConnectionIdMap.find(wsConnectionPtr->id) == this->correlationIdByConnectionIdMap.end()) { + Event event; + std::vector marketDataMessageList; + this->processTextMessage(wsConnectionPtr, textMessage, timeReceived, event, marketDataMessageList); + if (!marketDataMessageList.empty()) { + this->processMarketDataMessageList(wsConnectionPtr, textMessage, timeReceived, event, marketDataMessageList); + } + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } else { + Event event; + event.setType(Event::Type::SUBSCRIPTION_DATA); + Message message; + message.setType(Message::Type::GENERIC_PUBLIC_SUBSCRIPTION); + message.setTimeReceived(timeReceived); + message.setCorrelationIdList({this->correlationIdByConnectionIdMap.at(wsConnectionPtr->id)}); + Element element; + element.insert(CCAPI_WEBSOCKET_MESSAGE_PAYLOAD, std::string(textMessage)); + message.setElementList({element}); + event.setMessageList({message}); + this->eventHandler(event, nullptr); + } + this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived); + CCAPI_LOGGER_FUNCTION_EXIT; + } + virtual void onIncorrectStatesFound(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived, + const std::string& exchangeSubscriptionId, std::string const& reason) { + WsConnection& wsConnection = *wsConnectionPtr; + std::string errorMessage = "incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + std::string(textMessage) + + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId + + ", reason = " + reason; + CCAPI_LOGGER_ERROR(errorMessage); + ErrorCode ec; + this->close(wsConnectionPtr, beast::websocket::close_code::normal, + beast::websocket::close_reason(beast::websocket::close_code::normal, "incorrect states found: " + reason), ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, "shutdown"); + } + this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, errorMessage); + } + void connect(std::shared_ptr wsConnectionPtr) override { + CCAPI_LOGGER_FUNCTION_ENTER; + Service::connect(wsConnectionPtr); + this->instrumentGroupByWsConnectionIdMap.insert(std::pair(wsConnectionPtr->id, wsConnectionPtr->group)); + CCAPI_LOGGER_DEBUG("this->instrumentGroupByWsConnectionIdMap = " + toString(this->instrumentGroupByWsConnectionIdMap)); + CCAPI_LOGGER_FUNCTION_EXIT; + } + void onOpen(std::shared_ptr wsConnectionPtr) override { + CCAPI_LOGGER_FUNCTION_ENTER; + WsConnection& wsConnection = *wsConnectionPtr; + auto now = UtilTime::now(); + Service::onOpen(wsConnectionPtr); + WsConnection thisWsConnection = wsConnection; + auto credential = wsConnection.credential; + if (!credential.empty()) { + this->logonToExchange(wsConnectionPtr, now, credential); + } else { + this->startSubscribe(wsConnectionPtr); + } + } + void onFail_(std::shared_ptr wsConnectionPtr) override { + WsConnection& wsConnection = *wsConnectionPtr; + WsConnection thisWsConnection = wsConnection; + Service::onFail_(wsConnectionPtr); + this->instrumentGroupByWsConnectionIdMap.erase(thisWsConnection.id); + } + void clearStates(std::shared_ptr wsConnectionPtr) override { + WsConnection& wsConnection = *wsConnectionPtr; + Service::clearStates(wsConnectionPtr); + this->fieldByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->optionMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->subscriptionListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id); + this->snapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->snapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->previousConflateSnapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->previousConflateSnapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->processedInitialTradeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + if (this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.end()) { + for (const auto& x : this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { + for (const auto& y : x.second) { + y.second->cancel(); + } + } + this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + } + this->openByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->highByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->lowByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->closeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + this->orderBookChecksumByConnectionIdSymbolIdMap.erase(wsConnection.id); + this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.erase(wsConnection.id); + if (this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.find(wsConnection.id) != + this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.end()) { + for (const auto& x : this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id)) { + x.second->cancel(); + } + this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id); + } + this->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id); + } + virtual void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + CCAPI_LOGGER_FUNCTION_ENTER; + WsConnection& wsConnection = *wsConnectionPtr; + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id); + this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id); + this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id); + this->correlationIdByConnectionIdMap.erase(wsConnection.id); + Service::onClose(wsConnectionPtr, ec); + } + virtual void subscribeToExchange(std::shared_ptr wsConnectionPtr) { + WsConnection& wsConnection = *wsConnectionPtr; + CCAPI_LOGGER_INFO("exchange is " + this->exchangeName); + std::vector sendStringList; + if (this->correlationIdByConnectionIdMap.find(wsConnection.id) == this->correlationIdByConnectionIdMap.end()) { + sendStringList = this->createSendStringList(wsConnection); + } else { + auto subscription = wsConnection.subscriptionList.at(0); + sendStringList = std::vector(1, subscription.getRawOptions()); + } + for (const auto& sendString : sendStringList) { + CCAPI_LOGGER_INFO("sendString = " + sendString); + ErrorCode ec; + this->send(wsConnectionPtr, sendString, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } + } + void startSubscribe(std::shared_ptr wsConnectionPtr) { + WsConnection& wsConnection = *wsConnectionPtr; + auto instrumentGroup = wsConnection.group; + for (const auto& subscription : wsConnection.subscriptionList) { + auto instrument = subscription.getInstrument(); + this->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING; + if (subscription.getRawOptions().empty()) { + this->prepareSubscription(wsConnection, subscription); + } else { + this->correlationIdByConnectionIdMap.insert({wsConnection.id, subscription.getCorrelationId()}); + } + } + CCAPI_LOGGER_INFO("about to subscribe to exchange"); + this->subscribeToExchange(wsConnectionPtr); + } + virtual void logonToExchange(std::shared_ptr wsConnectionPtr, const TimePoint& now, const std::map& credential) { + WsConnection& wsConnection = *wsConnectionPtr; + CCAPI_LOGGER_INFO("about to logon to exchange"); + CCAPI_LOGGER_INFO("exchange is " + this->exchangeName); + auto subscriptionList = wsConnection.subscriptionList; + std::vector sendStringList = this->createSendStringListFromSubscriptionList(wsConnection, subscriptionList, now, credential); + for (const auto& sendString : sendStringList) { + CCAPI_LOGGER_INFO("sendString = " + sendString); + ErrorCode ec; + this->send(wsConnectionPtr, sendString, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } + } +#endif + void updateOrderBook(std::map& snapshot, const Decimal& price, const std::string& size, bool sizeMayHaveTrailingZero = false) { auto it = snapshot.find(price); if (it == snapshot.end()) { if ((!sizeMayHaveTrailingZero && size != "0") || @@ -308,11 +776,11 @@ class MarketDataService : public Service { int i2 = 0; std::map output; while (i1 < maxMarketDepth && i2 < maxMarketDepth && it1 != c1.rend() && it2 != c2.rend()) { - if (it1->first < it2->first) { + if (it1->first > it2->first) { output.insert(std::make_pair(it1->first, it1->second)); ++it1; ++i1; - } else if (it1->first > it2->first) { + } else if (it1->first < it2->first) { output.insert(std::make_pair(it2->first, "0")); ++it2; ++i2; @@ -851,20 +1319,6 @@ class MarketDataService : public Service { } return true; } - virtual void onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, - const std::string& exchangeSubscriptionId, std::string const& reason) { - std::string errorMessage = "incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + textMessage + - ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId + - ", reason = " + reason; - CCAPI_LOGGER_ERROR(errorMessage); - ErrorCode ec; - this->close(wsConnection, hdl, websocketpp::close::status::normal, "incorrect states found: " + reason, ec); - if (ec) { - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, "shutdown"); - } - this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, errorMessage); - } int calculateMarketDepthSubscribedToExchange(int depthWanted, std::vector availableMarketDepth) { int i = ceilSearch(availableMarketDepth, 0, availableMarketDepth.size(), depthWanted); if (i < 0) { @@ -903,15 +1357,21 @@ class MarketDataService : public Service { } } if (waitMilliseconds > 0) { - this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = this->serviceContextPtr->tlsClientPtr->set_timer( - waitMilliseconds, + TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(waitMilliseconds))); + timerPtr->async_wait( [wsConnection, channelId, symbolId, field, optionMap, correlationIdList, previousConflateTp, interval, gracePeriod, this](ErrorCode const& ec) { if (this->wsConnectionByIdMap.find(wsConnection.id) != this->wsConnectionByIdMap.end()) { if (ec) { CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", conflate timer error: " + ec.message()); this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); } else { - if (this->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN) { + if ( +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + this->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN +#else + this->wsConnectionByIdMap.at(wsConnection.id)->status == WsConnection::Status::OPEN +#endif + ) { auto conflateTp = previousConflateTp + interval; if (conflateTp > this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId)) { Event event; @@ -953,33 +1413,16 @@ class MarketDataService : public Service { } } }); + this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = timerPtr; } } CCAPI_LOGGER_FUNCTION_EXIT; } - virtual void subscribeToExchange(const WsConnection& wsConnection) { - CCAPI_LOGGER_INFO("exchange is " + this->exchangeName); - std::vector sendStringList; - if (this->correlationIdByConnectionIdMap.find(wsConnection.id) == this->correlationIdByConnectionIdMap.end()) { - sendStringList = this->createSendStringList(wsConnection); - } else { - auto subscription = wsConnection.subscriptionList.at(0); - sendStringList = std::vector(1, subscription.getRawOptions()); - } - for (const auto& sendString : sendStringList) { - CCAPI_LOGGER_INFO("sendString = " + sendString); - ErrorCode ec; - this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); - if (ec) { - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); - } - } - } void processSuccessfulTextMessageRest(int statusCode, const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Queue* eventQueuePtr) override { CCAPI_LOGGER_FUNCTION_ENTER; Event event; - if (this->doesHttpBodyContainError(request, textMessage)) { + if (this->doesHttpBodyContainError(textMessage)) { event.setType(Event::Type::RESPONSE); Message message; message.setType(Message::Type::RESPONSE_ERROR); @@ -1052,74 +1495,6 @@ class MarketDataService : public Service { messageList.emplace_back(std::move(message)); event.addMessages(messageList); } - void connect(WsConnection& wsConnection) override { - CCAPI_LOGGER_FUNCTION_ENTER; - Service::connect(wsConnection); - this->instrumentGroupByWsConnectionIdMap.insert(std::pair(wsConnection.id, wsConnection.group)); - CCAPI_LOGGER_DEBUG("this->instrumentGroupByWsConnectionIdMap = " + toString(this->instrumentGroupByWsConnectionIdMap)); - CCAPI_LOGGER_FUNCTION_EXIT; - } - void onOpen(wspp::connection_hdl hdl) override { - CCAPI_LOGGER_FUNCTION_ENTER; - Service::onOpen(hdl); - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - auto instrumentGroup = wsConnection.group; - for (const auto& subscription : wsConnection.subscriptionList) { - auto instrument = subscription.getInstrument(); - this->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING; - if (subscription.getRawOptions().empty()) { - this->prepareSubscription(wsConnection, subscription); - } else { - this->correlationIdByConnectionIdMap.insert({wsConnection.id, subscription.getCorrelationId()}); - } - } - CCAPI_LOGGER_INFO("about to subscribe to exchange"); - this->subscribeToExchange(wsConnection); - } - void onFail_(WsConnection& wsConnection) override { - WsConnection thisWsConnection = wsConnection; - Service::onFail_(wsConnection); - this->instrumentGroupByWsConnectionIdMap.erase(thisWsConnection.id); - } - void clearStates(WsConnection& wsConnection) override { - Service::clearStates(wsConnection); - this->fieldByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->optionMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->subscriptionListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->correlationIdListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id); - this->snapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->snapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->previousConflateSnapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->previousConflateSnapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->processedInitialTradeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - if (this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.end()) { - for (const auto& x : this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { - for (const auto& y : x.second) { - y.second->cancel(); - } - } - this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - } - this->openByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->highByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->lowByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->closeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); - this->orderBookChecksumByConnectionIdSymbolIdMap.erase(wsConnection.id); - } - void onClose(wspp::connection_hdl hdl) override { - CCAPI_LOGGER_FUNCTION_ENTER; - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.erase(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]); - this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id); - this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id); - this->correlationIdByConnectionIdMap.erase(wsConnection.id); - Service::onClose(hdl); - } void convertRequestForRestGenericPublicRequest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& credential) { const std::map param = request.getFirstParamWithDefault(); @@ -1142,16 +1517,240 @@ class MarketDataService : public Service { req.prepare_payload(); } } + void processOrderBookWithVersionId(int64_t versionId, const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, + const std::string& exchangeSubscriptionId, const std::map& optionMap, + std::vector& marketDataMessageList, const MarketDataMessage& marketDataMessage) { + if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) { + if (versionId > this->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId)) { + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + this->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = versionId; + } + } else { + if (this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId].empty()) { + int delayMilliSeconds = std::stoi(optionMap.at(CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS)); + if (delayMilliSeconds > 0) { + TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliSeconds))); + timerPtr->async_wait([wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = this](ErrorCode const& ec) { + auto now = UtilTime::now(); + if (ec) { + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds); + } + }); + this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = timerPtr; + } else { + this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds); + } + } + this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId][versionId] = + marketDataMessage.data; + } + } + void buildOrderBookInitialOnFail(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliSeconds) { + auto thisDelayMilliSeconds = delayMilliSeconds * 2; + if (thisDelayMilliSeconds > 0) { + TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(thisDelayMilliSeconds))); + timerPtr->async_wait([wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds, that = this](ErrorCode const& ec) { + if (ec) { + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds); + } + }); + this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = timerPtr; + } else { + this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds); + } + } + void buildOrderBookInitial(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliSeconds) { + auto now = UtilTime::now(); + http::request req; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + auto credential = wsConnection.credential; + if (credential.empty()) { + credential = this->credentialDefault; + } + this->createFetchOrderBookInitialReq(req, symbolId, now, credential); + this->sendRequest( + req, + [wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = shared_from_base()](const beast::error_code& ec) { + that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds); + }, + [wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = shared_from_base()](const http::response& res) { + auto timeReceived = UtilTime::now(); + int statusCode = res.result_int(); + std::string body = res.body(); + if (statusCode / 100 == 2 && !that->doesHttpBodyContainError(body)) { + try { + rj::Document document; + document.Parse(body.c_str()); + int64_t versionId; + that->extractOrderBookInitialVersionId(versionId, document); + if (versionId >= + that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId].begin()->first) { + const auto& channelId = + that->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + const auto& symbolId = that->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + const auto& optionMap = that->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + that->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = versionId; + const auto& correlationIdList = that->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + std::map& snapshotBid = that->snapshotBidByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + std::map& snapshotAsk = that->snapshotAskByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + snapshotBid.clear(); + snapshotAsk.clear(); + MarketDataMessage::TypeForData input; + that->extractOrderBookInitialData(input, document); + for (const auto& x : input) { + const auto& type = x.first; + const auto& detail = x.second; + if (type == MarketDataMessage::DataType::BID) { + for (const auto& y : detail) { + const auto& price = y.at(MarketDataMessage::DataFieldType::PRICE); + const auto& size = y.at(MarketDataMessage::DataFieldType::SIZE); + Decimal decimalPrice(price, that->sessionOptions.enableCheckOrderBookChecksum); + snapshotBid.emplace(std::move(decimalPrice), std::move(size)); + } + } else if (type == MarketDataMessage::DataType::ASK) { + for (const auto& y : detail) { + const auto& price = y.at(MarketDataMessage::DataFieldType::PRICE); + const auto& size = y.at(MarketDataMessage::DataFieldType::SIZE); + Decimal decimalPrice(price, that->sessionOptions.enableCheckOrderBookChecksum); + snapshotAsk.emplace(std::move(decimalPrice), std::move(size)); + } + } + } + if (that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id).find(exchangeSubscriptionId) != + that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id).end()) { + auto it = that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id) + .at(exchangeSubscriptionId) + .upper_bound(versionId); + while ( + it != + that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).end()) { + const auto& input = it->second; + for (const auto& x : input) { + const auto& type = x.first; + const auto& detail = x.second; + if (type == MarketDataMessage::DataType::BID) { + for (const auto& y : detail) { + const auto& price = y.at(MarketDataMessage::DataFieldType::PRICE); + const auto& size = y.at(MarketDataMessage::DataFieldType::SIZE); + Decimal decimalPrice(price, that->sessionOptions.enableCheckOrderBookChecksum); + that->updateOrderBook(snapshotBid, decimalPrice, size, that->sessionOptions.enableCheckOrderBookChecksum); + } + } else if (type == MarketDataMessage::DataType::ASK) { + for (const auto& y : detail) { + const auto& price = y.at(MarketDataMessage::DataFieldType::PRICE); + const auto& size = y.at(MarketDataMessage::DataFieldType::SIZE); + Decimal decimalPrice(price, that->sessionOptions.enableCheckOrderBookChecksum); + that->updateOrderBook(snapshotAsk, decimalPrice, size, that->sessionOptions.enableCheckOrderBookChecksum); + } + } + } + that->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = it->first; + it++; + } + that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id).erase(exchangeSubscriptionId); + } + Event event; + event.setType(Event::Type::SUBSCRIPTION_DATA); + std::vector elementList; + int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + int bidIndex = 0; + for (auto iter = snapshotBid.rbegin(); iter != snapshotBid.rend(); iter++) { + if (bidIndex < maxMarketDepth) { + Element element; + element.insert(CCAPI_BEST_BID_N_PRICE, iter->first.toString()); + element.insert(CCAPI_BEST_BID_N_SIZE, iter->second); + elementList.emplace_back(std::move(element)); + } + ++bidIndex; + } + if (snapshotBid.empty()) { + Element element; + element.insert(CCAPI_BEST_BID_N_PRICE, CCAPI_BEST_BID_N_PRICE_EMPTY); + element.insert(CCAPI_BEST_BID_N_SIZE, CCAPI_BEST_BID_N_SIZE_EMPTY); + elementList.emplace_back(std::move(element)); + } + int askIndex = 0; + for (auto iter = snapshotAsk.begin(); iter != snapshotAsk.end(); iter++) { + if (askIndex < maxMarketDepth) { + Element element; + element.insert(CCAPI_BEST_ASK_N_PRICE, iter->first.toString()); + element.insert(CCAPI_BEST_ASK_N_SIZE, iter->second); + elementList.emplace_back(std::move(element)); + } + ++askIndex; + } + if (snapshotAsk.empty()) { + Element element; + element.insert(CCAPI_BEST_ASK_N_PRICE, CCAPI_BEST_ASK_N_PRICE_EMPTY); + element.insert(CCAPI_BEST_ASK_N_SIZE, CCAPI_BEST_ASK_N_SIZE_EMPTY); + elementList.emplace_back(std::move(element)); + } + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + message.setType(Message::Type::MARKET_DATA_EVENTS_MARKET_DEPTH); + message.setRecapType(Message::RecapType::SOLICITED); + message.setTime(timeReceived); + message.setElementList(elementList); + message.setCorrelationIdList(correlationIdList); + messageList.emplace_back(std::move(message)); + event.addMessages(messageList); + that->eventHandler(event, nullptr); + that->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true; + } else { + that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds); + // if (delayMilliSeconds > 0) { + // that->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = + // that->serviceContextPtr->tlsClientPtr->set_timer( + // delayMilliSeconds, [wsConnection, exchangeSubscriptionId, delayMilliSeconds, that](ErrorCode const& ec) { + // if (ec) { + // that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + // } else { + // that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds); + // } + // }); + // } else { + // that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds); + // } + } + return; + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); + } + } + that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds); + // WsConnection thisWsConnection = wsConnection; + // that->onFail_(thisWsConnection); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); + } + virtual std::vector createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector& subscriptionList, + const TimePoint& now, const std::map& credential) { + return {}; + } virtual void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) {} +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET virtual void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) {} +#else + virtual void processTextMessage(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived, + Event& event, std::vector& marketDataMessageList) {} +#endif virtual std::string calculateOrderBookChecksum(const std::map& snapshotBid, const std::map& snapshotAsk) { return {}; } virtual std::vector createSendStringList(const WsConnection& wsConnection) { return {}; } virtual void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) {} + const Subscription& subscription, const std::map optionMap) {} + virtual void createFetchOrderBookInitialReq(http::request& req, const std::string& symbolId, const TimePoint& now, + const std::map& credential) {} + virtual void extractOrderBookInitialVersionId(int64_t& versionId, const rj::Document& document) {} + virtual void extractOrderBookInitialData(MarketDataMessage::TypeForData& input, const rj::Document& document) {} std::map>> fieldByConnectionIdChannelIdSymbolIdMap; std::map>>> optionMapByConnectionIdChannelIdSymbolIdMap; std::map>> marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap; @@ -1181,9 +1780,13 @@ class MarketDataService : public Service { std::string getInstrumentTarget; std::string getInstrumentsTarget; std::map exchangeJsonPayloadIdByConnectionIdMap; - std::map> exchangeSubscriptionIdListByExchangeJsonPayloadIdMap; + std::map>> exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap; // only needed for generic public subscription std::map correlationIdByConnectionIdMap; + std::map>> + marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap; + std::map> orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap; + std::map> fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap; }; } /* namespace ccapi */ #endif diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ascendex.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ascendex.h index 75a13d280..d6f6e3bc2 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ascendex.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ascendex.h @@ -10,14 +10,23 @@ class MarketDataServiceAscendex : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_ASCENDEX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api/pro/v1/stream"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api/pro/v1/stream"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/api/pro/v1/trades"; this->getInstrumentTarget = "/api/pro/v1/products"; this->getInstrumentsTarget = "/api/pro/v1/products"; @@ -27,9 +36,9 @@ class MarketDataServiceAscendex : public MarketDataService { private: #endif - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); if (field == CCAPI_MARKET_DEPTH) { if (marketDepthRequested == 1) { @@ -37,7 +46,7 @@ class MarketDataServiceAscendex : public MarketDataService { } } } - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({ "op": "ping" })", wspp::frame::opcode::text, ec); } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance.h index 5ae4d6a86..371f790c4 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance.h @@ -10,14 +10,23 @@ class MarketDataServiceBinance : public MarketDataServiceBinanceBase { std::shared_ptr serviceContextPtr) : MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BINANCE_API_KEY; this->setupCredential({this->apiKeyName}); this->getRecentTradesTarget = "/api/v3/trades"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_base.h index 4b3815fd7..761f65cb3 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_base.h @@ -16,9 +16,25 @@ class MarketDataServiceBinanceBase : public MarketDataService { #ifndef CCAPI_EXPOSE_INTERNAL protected: +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + void onOpen(wspp::connection_hdl hdl) override { + CCAPI_LOGGER_FUNCTION_ENTER; + auto now = UtilTime::now(); + Service::onOpen(hdl); + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->startSubscribe(wsConnection); + } +#else + void onOpen(std::shared_ptr wsConnectionPtr) override { + CCAPI_LOGGER_FUNCTION_ENTER; + auto now = UtilTime::now(); + Service::onOpen(wsConnectionPtr); + this->startSubscribe(wsConnectionPtr); + } #endif void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { @@ -78,7 +94,8 @@ class MarketDataServiceBinanceBase : public MarketDataService { } document.AddMember("params", params, allocator); document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator); - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList; + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + exchangeSubscriptionIdList; this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; rj::StringBuffer stringBuffer; rj::Writer writer(stringBuffer); @@ -87,8 +104,19 @@ class MarketDataServiceBinanceBase : public MarketDataService { sendStringList.push_back(sendString); return sendStringList; } - void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, - std::vector& marketDataMessageList) override { + void processTextMessage( +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage +#else + std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView +#endif + , + const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + WsConnection& wsConnection = *wsConnectionPtr; + std::string textMessage(textMessageView); +#endif rj::Document document; document.Parse(textMessage.c_str()); if (document.IsObject() && document.HasMember("result") && document["result"].IsNull()) { @@ -99,8 +127,11 @@ class MarketDataServiceBinanceBase : public MarketDataService { std::vector correlationIdList; if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { int id = std::stoi(document["id"].GetString()); - if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.find(id) != this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.end()) { - for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.at(id)) { + if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { + for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) { std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h index bfd122ebe..e03e9e6f6 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h @@ -10,14 +10,23 @@ class MarketDataServiceBinanceCoinFutures : public MarketDataServiceBinanceDeriv std::shared_ptr serviceContextPtr) : MarketDataServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY; this->setupCredential({this->apiKeyName}); this->getRecentTradesTarget = "/dapi/v1/trades"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h index 1369137ad..053a4469a 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h @@ -17,7 +17,7 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB protected: #endif void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { @@ -51,6 +51,8 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB } else if (filterType == "LOT_SIZE") { element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, y["stepSize"].GetString()); element.insert(CCAPI_ORDER_QUANTITY_MIN, y["minQty"].GetString()); + } else if (filterType == "MIN_NOTIONAL") { + element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, y["notional"].GetString()); } } } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_us.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_us.h index bd3845dce..10de42af9 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_us.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_us.h @@ -10,14 +10,23 @@ class MarketDataServiceBinanceUs : public MarketDataServiceBinanceBase { std::shared_ptr serviceContextPtr) : MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_US; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BINANCE_US_API_KEY; this->setupCredential({this->apiKeyName}); this->getRecentTradesTarget = "/api/v3/trades"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h index a7b8ea4a6..76e9559f9 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h @@ -10,14 +10,23 @@ class MarketDataServiceBinanceUsdsFutures : public MarketDataServiceBinanceDeriv std::shared_ptr serviceContextPtr) : MarketDataServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY; this->setupCredential({this->apiKeyName}); this->getRecentTradesTarget = "/fapi/v1/trades"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitfinex.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitfinex.h index 43fe14b6d..3998c8483 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitfinex.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitfinex.h @@ -10,14 +10,23 @@ class MarketDataServiceBitfinex : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BITFINEX; - this->baseUrl = std::string(CCAPI_BITFINEX_PUBLIC_URL_WS_BASE) + "/ws/2"; + this->baseUrlWs = std::string(CCAPI_BITFINEX_PUBLIC_URL_WS_BASE) + "/ws/2"; this->baseUrlRest = CCAPI_BITFINEX_PUBLIC_URL_REST_BASE; this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/v2/trades/{Symbol}/hist"; this->getInstrumentsTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH; this->getInstrumentTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH; @@ -32,7 +41,7 @@ class MarketDataServiceBitfinex : public MarketDataService { this->send(hdl, "{\"cid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec); } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget.h new file mode 100644 index 000000000..0cc60f347 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget.h @@ -0,0 +1,39 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET +#include "ccapi_cpp/service/ccapi_market_data_service_bitget_base.h" +namespace ccapi { +class MarketDataServiceBitget : public MarketDataServiceBitgetBase { + public: + MarketDataServiceBitget(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/v1/stream"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->getRecentTradesTarget = "/api/spot/v1/market/fills"; + this->getInstrumentTarget = "/api/spot/v1/public/product"; + this->getInstrumentsTarget = "/api/spot/v1/public/products"; + } + virtual ~MarketDataServiceBitget() {} +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_base.h new file mode 100644 index 000000000..f958f72b9 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_base.h @@ -0,0 +1,377 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_BASE_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_BASE_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#if defined(CCAPI_ENABLE_EXCHANGE_BITGET) || defined(CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES) +#include "ccapi_cpp/service/ccapi_market_data_service.h" +namespace ccapi { +class MarketDataServiceBitgetBase : public MarketDataService { + public: + MarketDataServiceBitgetBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {} + virtual ~MarketDataServiceBitgetBase() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"00000\"")); } + void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, + const Subscription& subscription, const std::map optionMap) override { + auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); + if (field == CCAPI_MARKET_DEPTH) { + if (this->isDerivatives) { + if (conflateIntervalMilliSeconds < 200) { + channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS; + } else { + if (marketDepthRequested <= 1) { + channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1; + } else if (marketDepthRequested <= 5) { + channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5; + } else if (marketDepthRequested <= 15) { + channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15; + } else { + channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS; + } + } + } else { + if (marketDepthRequested <= 5) { + channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5; + } else if (marketDepthRequested <= 15) { + channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15; + } else { + channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS; + } + } + } + } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } + std::vector createSendStringList(const WsConnection& wsConnection) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { + auto channelId = subscriptionListByChannelIdSymbolId.first; + for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) { + std::string symbolId = subscriptionListBySymbolId.first; + if (channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1 || channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5 || + channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15) { + this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true; + } + std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId; + rj::Value arg(rj::kObjectType); + std::string instType = this->isDerivatives ? "mc" : "sp"; + arg.AddMember("instType", rj::Value(instType.c_str(), allocator).Move(), allocator); + arg.AddMember("channel", rj::Value(channelId.c_str(), allocator).Move(), allocator); + arg.AddMember("instId", rj::Value(symbolId.c_str(), allocator).Move(), allocator); + args.PushBack(arg, allocator); + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; + } + } + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + std::string calculateOrderBookChecksum(const std::map& snapshotBid, const std::map& snapshotAsk) override { + auto i = 0; + auto i1 = snapshotBid.rbegin(); + auto i2 = snapshotAsk.begin(); + std::vector csData; + while (i < 25 && (i1 != snapshotBid.rend() || i2 != snapshotAsk.end())) { + if (i1 != snapshotBid.rend()) { + csData.push_back(toString(i1->first)); + csData.push_back(i1->second); + ++i1; + } + if (i2 != snapshotAsk.end()) { + csData.push_back(toString(i2->first)); + csData.push_back(i2->second); + ++i2; + } + ++i; + } + std::string csStr = UtilString::join(csData, ":"); + uint_fast32_t csCalc = UtilAlgorithm::crc(csStr.begin(), csStr.end()); + return intToHex(csCalc); + } + void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + if (textMessage != "pong") { + rj::Document document; + document.Parse(textMessage.c_str()); + auto it = document.FindMember("event"); + std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; + // if (eventStr == "login") { + // this->startSubscribe(wsConnection); + // } else { + if (!eventStr.empty()) { + if (eventStr == "subscribe") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + std::vector correlationIdList; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { + const rj::Value& arg = document["arg"]; + std::string channelId = arg["channel"].GetString(); + std::string symbolId = arg["instId"].GetString(); + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) { + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) { + std::vector correlationIdList_2 = + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end()); + } + } + } + message.setCorrelationIdList(correlationIdList); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); + } else if (eventStr == "error") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); + } + } else if (document.HasMember("arg")) { + const rj::Value& arg = document["arg"]; + std::string channelId = arg["channel"].GetString(); + std::string symbolId = arg["instId"].GetString(); + std::string exchangeSubscriptionId = channelId + ":" + symbolId; + if (channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS || channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1 || + channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5 || channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15) { + std::string action = document["action"].GetString(); + for (const auto& datum : document["data"].GetArray()) { + if (this->sessionOptions.enableCheckOrderBookChecksum) { + auto it = datum.FindMember("checksum"); + if (it != datum.MemberEnd()) { + this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] = + intToHex(static_cast(static_cast(std::stoi(it->value.GetString())))); + } + } + MarketDataMessage marketDataMessage; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + if (channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1 || channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5 || + channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15) { + if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) { + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + } else { + marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED; + } + } else { + marketDataMessage.recapType = action == "update" ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED; + } + for (const auto& x : datum["bids"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + if (this->sessionOptions.enableCheckOrderBookChecksum) { + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()}); + } else { + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + } + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : datum["asks"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + if (this->sessionOptions.enableCheckOrderBookChecksum) { + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()}); + } else { + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + } + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } else if (channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES) { + std::string action = document["action"].GetString(); + MarketDataMessage::RecapType recapType = action == "update" ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED; + for (const auto& datum : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.recapType = recapType; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[0].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum[1].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum[2].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum[3].GetString()) == "sell" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } + } + // } + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + switch (request.getOperation()) { + case Request::Operation::GENERIC_PUBLIC_REQUEST: { + MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::GET_RECENT_TRADES: { + req.method(http::verb::get); + auto target = this->getRecentTradesTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_LIMIT, "limit"}, + }); + this->appendSymbolId(queryString, symbolId, "symbol"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENT: { + req.method(http::verb::get); + std::string target; + std::string queryString; + if (this->isDerivatives) { + target = this->getInstrumentsTarget; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_INSTRUMENT_TYPE, "productType"}, + }); + } else { + target = this->getInstrumentTarget; + const std::map param = request.getFirstParamWithDefault(); + this->appendSymbolId(queryString, symbolId, "symbol"); + } + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENTS: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + if (this->isDerivatives) { + this->appendParam(queryString, param, + { + {CCAPI_INSTRUMENT_TYPE, "productType"}, + }); + req.target(target + "?" + queryString); + } else { + req.target(target); + } + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractInstrumentInfo(Element& element, const rj::Value& x) { + if (this->isDerivatives) { + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString()); + element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString()); + int pricePlace = std::stoi(x["pricePlace"].GetString()); + if (pricePlace > 0) { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(pricePlace - 1, '0') + x["priceEndStep"].GetString()); + } else { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceEndStep"].GetString()); + } + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["sizeMultiplier"].GetString()); + element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeNum"].GetString()); + } else { + element.insert(CCAPI_INSTRUMENT, x["symbolName"].GetString()); + element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString()); + element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString()); + int priceScale = std::stoi(x["priceScale"].GetString()); + if (priceScale > 0) { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(priceScale - 1, '0') + "1"); + } else { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1"); + } + int quantityScale = std::stoi(x["quantityScale"].GetString()); + if (quantityScale > 0) { + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(quantityScale - 1, '0') + "1"); + } else { + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "1"); + } + element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeAmount"].GetString()); + } + } + void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + switch (request.getOperation()) { + case Request::Operation::GET_RECENT_TRADES: { + for (const auto& datum : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[this->isDerivatives ? "timestamp" : "fillTime"].GetString()))); + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert( + {MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum[this->isDerivatives ? "price" : "fillPrice"].GetString())}); + dataPoint.insert( + {MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum[this->isDerivatives ? "size" : "fillQuantity"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, datum["tradeId"].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "sell" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_INSTRUMENT: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + for (const auto& x : document["data"].GetArray()) { + if (std::string(x["symbol"].GetString()) == request.getInstrument()) { + Element element; + this->extractInstrumentInfo(element, x); + message.setElementList({element}); + break; + } + } + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + case Request::Operation::GET_INSTRUMENTS: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + std::vector elementList; + for (const auto& x : document["data"].GetArray()) { + Element element; + this->extractInstrumentInfo(element, x); + elementList.push_back(element); + } + message.setElementList(elementList); + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + bool isDerivatives{}; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_BASE_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_futures.h new file mode 100644 index 000000000..62f036979 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_futures.h @@ -0,0 +1,40 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_FUTURES_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_FUTURES_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES +#include "ccapi_cpp/service/ccapi_market_data_service_bitget_base.h" +namespace ccapi { +class MarketDataServiceBitgetFutures : public MarketDataServiceBitgetBase { + public: + MarketDataServiceBitgetFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET_FUTURES; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/mix/v1/stream"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->getRecentTradesTarget = "/api/mix/v1/market/fills"; + this->getInstrumentTarget = "/api/mix/v1/market/contracts"; + this->getInstrumentsTarget = "/api/mix/v1/market/contracts"; + this->isDerivatives = true; + } + virtual ~MarketDataServiceBitgetFutures() {} +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_FUTURES_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h new file mode 100644 index 000000000..3974c3713 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h @@ -0,0 +1,328 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMART_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMART_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#ifdef CCAPI_ENABLE_EXCHANGE_BITMART +#include "ccapi_cpp/service/ccapi_market_data_service.h" +namespace ccapi { +class MarketDataServiceBitmart : public MarketDataService { + public: + MarketDataServiceBitmart(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_BITMART; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api?protocol=1.1"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_BITMART_API_KEY; + this->apiSecretName = CCAPI_BITMART_API_SECRET; + this->apiMemo = CCAPI_BITMART_API_MEMO; + this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiMemo}); + this->getRecentTradesTarget = "/spot/v1/symbols/trades"; + this->getInstrumentsTarget = "/spot/v1/symbols/details"; + } + virtual ~MarketDataServiceBitmart() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + private: +#endif + void onClose(wspp::connection_hdl hdl) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id); + MarketDataService::onClose(hdl); + } + void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, + const Subscription& subscription, const std::map optionMap) override { + auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + if (field == CCAPI_MARKET_DEPTH) { + if (marketDepthRequested <= 5) { + channelId = CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5; + } else if (marketDepthRequested <= 20) { + channelId = CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH20; + } else { + channelId = CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH50; + } + } + } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*1000")); } + std::vector createSendStringList(const WsConnection& wsConnection) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { + auto channelId = subscriptionListByChannelIdSymbolId.first; + for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) { + std::string symbolId = subscriptionListBySymbolId.first; + if (channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5 || channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH20 || + channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH50) { + this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true; + } + std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId; + args.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator); + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; + } + } + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + if (textMessage != "pong") { + rj::Document document; + document.Parse(textMessage.c_str()); + auto it = document.FindMember("errorCode"); + std::string errorCode = it != document.MemberEnd() ? it->value.GetString() : ""; + if (errorCode.empty()) { + std::string channelId = document["table"].GetString(); + std::string symbolId = document["data"][0]["symbol"].GetString(); + std::string exchangeSubscriptionId = channelId + ":" + symbolId; + if (!this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) { + const auto& subscriptionList = this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + std::vector correlationIdList; + for (const auto& subscription : subscriptionList) { + correlationIdList.push_back(subscription.getCorrelationId()); + } + Event event; + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList(correlationIdList); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + event.addMessages(messageList); + this->eventHandler(event, nullptr); + } + if (channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5 || channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH20 || + channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH50) { + for (const auto& datum : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ms_t"].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) { + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + } else { + marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED; + } + for (const auto& x : datum["bids"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : datum["asks"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } else if (channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_TRADE) { + MarketDataMessage::RecapType recapType = MarketDataMessage::RecapType::NONE; + if (!this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) { + recapType = MarketDataMessage::RecapType::SOLICITED; + } + for (const auto& datum : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.recapType = recapType; + marketDataMessage.tp = TimePoint(std::chrono::seconds(std::stoll(datum["s_t"].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["price"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["size"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "buy" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } + if (!this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) { + this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true; + } + } else { + std::string eventStr = document["event"].GetString(); + const auto& splitted = UtilString::split(eventStr, ':'); + if (splitted.at(0) == "subscribe") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + const auto& channelId = splitted.at(1); + const auto& symbolId = splitted.at(2); + const auto& subscriptionList = this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + std::vector correlationIdList; + for (const auto& subscription : subscriptionList) { + correlationIdList.push_back(subscription.getCorrelationId()); + } + message.setCorrelationIdList(correlationIdList); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); + } + } + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + switch (request.getOperation()) { + case Request::Operation::GENERIC_PUBLIC_REQUEST: { + MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::GET_RECENT_TRADES: { + req.method(http::verb::get); + auto target = this->getRecentTradesTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_LIMIT, "N"}, + }); + this->appendSymbolId(queryString, symbolId, "symbol"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENT: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + req.target(target); + } break; + case Request::Operation::GET_INSTRUMENTS: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + req.target(target); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractInstrumentInfo(Element& element, const rj::Value& x) { + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_BASE_ASSET, x["base_currency"].GetString()); + element.insert(CCAPI_QUOTE_ASSET, x["quote_currency"].GetString()); + int priceMaxPrecision = std::stoi(x["price_max_precision"].GetString()); + if (priceMaxPrecision > 0) { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(priceMaxPrecision - 1, '0') + "1"); + } else { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1" + std::string(-priceMaxPrecision, '0')); + } + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, UtilString::normalizeDecimalString(x["quote_increment"].GetString())); + element.insert(CCAPI_ORDER_QUANTITY_MIN, UtilString::normalizeDecimalString(x["base_min_size"].GetString())); + element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, + std::max(Decimal(x["min_buy_amount"].GetString()), Decimal(x["min_sell_amount"].GetString())).toString()); + } + void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + switch (request.getOperation()) { + case Request::Operation::GET_RECENT_TRADES: { + for (const auto& datum : document["data"]["trades"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["order_time"].GetString()))); + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["price"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["count"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["type"].GetString()) == "buy" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_INSTRUMENT: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + for (const auto& x : document["data"]["symbols"].GetArray()) { + if (std::string(x["symbol"].GetString()) == request.getInstrument()) { + Element element; + this->extractInstrumentInfo(element, x); + message.setElementList({element}); + break; + } + } + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + case Request::Operation::GET_INSTRUMENTS: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + std::vector elementList; + for (const auto& x : document["data"]["symbols"].GetArray()) { + Element element; + this->extractInstrumentInfo(element, x); + elementList.push_back(element); + } + message.setElementList(elementList); + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + std::vector createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector& subscriptionList, + const TimePoint& now, const std::map& credential) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("login").Move(), allocator); + rj::Value arg(rj::kObjectType); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto apiPassphrase = mapGetWithDefault(credential, this->apiMemo); + std::string ts = std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); + arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator); + arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator); + arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator); + std::string signData = ts + "GET" + "/users/self/verify"; + std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData)); + arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator); + rj::Value args(rj::kArrayType); + args.PushBack(arg, allocator); + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + std::string apiMemo; + std::map>> subscriptionStartedByConnectionIdChannelIdSymbolIdMap; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMART_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmex.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmex.h index 31fd9eaae..5e2534d43 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmex.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmex.h @@ -10,14 +10,23 @@ class MarketDataServiceBitmex : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BITMEX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/api/v1/trade"; this->getInstrumentTarget = "/api/v1/instrument"; this->getInstrumentsTarget = "/api/v1/instrument"; @@ -29,15 +38,19 @@ class MarketDataServiceBitmex : public MarketDataService { private: #endif void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); if (field == CCAPI_MARKET_DEPTH) { - if (marketDepthRequested == 1) { - channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_QUOTE; - } else if (marketDepthRequested <= 10) { - channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_10; - } else if (marketDepthRequested <= 25) { - channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2_25; + if (optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS) == CCAPI_CONFLATE_INTERVAL_MILLISECONDS_DEFAULT) { + channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2; + } else { + if (marketDepthRequested == 1) { + channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_QUOTE; + } else if (marketDepthRequested <= 10) { + channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_10; + } else if (marketDepthRequested <= 25) { + channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2_25; + } } } } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitstamp.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitstamp.h index 3771062b7..3791479ef 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitstamp.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitstamp.h @@ -10,15 +10,24 @@ class MarketDataServiceBitstamp : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BITSTAMP; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->enableCheckPingPongWebsocketApplicationLevel = false; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/api/v2/transactions/{currency_pair}/"; // must have trailing slash this->getInstrumentTarget = "/api/v2/trading-pairs-info/"; this->getInstrumentsTarget = "/api/v2/trading-pairs-info/"; @@ -31,7 +40,7 @@ class MarketDataServiceBitstamp : public MarketDataService { void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec); } - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("status": "error")") != std::string::npos || body.find(R"("status":"error")") != std::string::npos; } std::vector createSendStringList(const WsConnection& wsConnection) override { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit.h index 1079d5afa..9e537d6fc 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit.h @@ -2,36 +2,42 @@ #define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_H_ #ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA #ifdef CCAPI_ENABLE_EXCHANGE_BYBIT -#include "ccapi_cpp/service/ccapi_market_data_service.h" +#include "ccapi_cpp/service/ccapi_market_data_service_bybit_base.h" namespace ccapi { -class MarketDataServiceBybit : public MarketDataService { +class MarketDataServiceBybit : public MarketDataServiceBybitBase { public: MarketDataServiceBybit(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, std::shared_ptr serviceContextPtr) - : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + : MarketDataServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/quote/ws/v2"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/public/v3"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } - this->getRecentTradesTarget = "/spot/quote/v1/trades"; - this->getInstrumentTarget = "/spot/v1/symbols"; - this->getInstrumentsTarget = "/spot/v1/symbols"; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->getRecentTradesTarget = "/spot/v3/public/quote/trades"; + this->getInstrumentsTarget = "/spot/v3/public/symbols"; } virtual ~MarketDataServiceBybit() {} #ifndef CCAPI_EXPOSE_INTERNAL protected: #endif - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); - auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { if (marketDepthRequested == 1) { channelId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER; @@ -42,6 +48,12 @@ class MarketDataServiceBybit : public MarketDataService { } std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; + std::vector exchangeSubscriptionIdList; + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { auto channelId = subscriptionListByChannelIdSymbolId.first; for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) { @@ -50,83 +62,93 @@ class MarketDataServiceBybit : public MarketDataService { if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER || channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH) { this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true; } - exchangeSubscriptionId += "|"; - exchangeSubscriptionId += symbolId; - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); + std::string toReplace = "{symbol}"; + exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), symbolId); this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; - document.AddMember("topic", rj::Value(channelId.c_str(), allocator).Move(), allocator); - document.AddMember("event", rj::Value("sub").Move(), allocator); - rj::Value params(rj::kObjectType); - params.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); - params.AddMember("binary", rj::Value(false), allocator); - document.AddMember("params", params, allocator); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - std::string sendString = stringBuffer.GetString(); - sendStringList.push_back(sendString); + args.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator); + exchangeSubscriptionIdList.push_back(exchangeSubscriptionId); } } + document.AddMember("args", args, allocator); + document.AddMember("req_id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(), allocator); + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + exchangeSubscriptionIdList; + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); return sendStringList; } void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { rj::Document document; document.Parse(textMessage.c_str()); - if (document.IsObject() && document.HasMember("code")) { - std::string code = document["code"].GetString(); - event.setType(Event::Type::SUBSCRIPTION_STATUS); - std::vector messageList; - Message message; - message.setTimeReceived(timeReceived); - std::vector correlationIdList; - if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { - std::string channelId = document["topic"].GetString(); - std::string symbolId = document["params"]["symbol"].GetString(); - if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != - this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) { - if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) != - this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) { - std::vector correlationIdList_2 = - this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); - correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end()); + if (document.IsObject() && document.HasMember("op")) { + std::string op = document["op"].GetString(); + if (op == "subscribe") { + bool success = document["success"].GetBool(); + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + std::vector correlationIdList; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { + int id = std::stoi(document["req_id"].GetString()); + if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { + for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) { + std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) { + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) { + std::vector correlationIdList_2 = + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end()); + } + } + } } } + message.setCorrelationIdList(correlationIdList); + message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); } - message.setCorrelationIdList(correlationIdList); - message.setType(code == "0" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); - Element element; - element.insert(code == "0" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); - event.setMessageList(messageList); } else if (document.IsObject() && document.HasMember("data")) { MarketDataMessage marketDataMessage; - std::string channelId = document["topic"].GetString(); - std::string symbolId = document["params"]["symbol"].GetString(); + std::string exchangeSubscriptionId = document["topic"].GetString(); + std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; - std::string exchangeSubscriptionId = channelId + "|" + symbolId; const rj::Value& data = document["data"]; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER) { marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED; - marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["time"].GetString()))); - marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; { MarketDataMessage::TypeForDataPoint dataPoint; - dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["bidPrice"].GetString())}); - dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bidQty"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["bp"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bq"].GetString())}); marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); } { MarketDataMessage::TypeForDataPoint dataPoint; - dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["askPrice"].GetString())}); - dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["askQty"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["ap"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["aq"].GetString())}); marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); } marketDataMessageList.emplace_back(std::move(marketDataMessage)); @@ -135,8 +157,6 @@ class MarketDataServiceBybit : public MarketDataService { marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED; - marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString()))); - marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; const char* bidsName = "b"; int bidIndex = 0; int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); @@ -164,16 +184,13 @@ class MarketDataServiceBybit : public MarketDataService { } marketDataMessageList.emplace_back(std::move(marketDataMessage)); } else if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE) { - MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; - marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; - marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["t"].GetString())); marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; MarketDataMessage::TypeForDataPoint dataPoint; dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(data["p"].GetString()))}); dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(data["q"].GetString()))}); dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(data["v"].GetString())}); - dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "1" : "0"}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "0" : "1"}); marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); marketDataMessageList.emplace_back(std::move(marketDataMessage)); } @@ -199,12 +216,12 @@ class MarketDataServiceBybit : public MarketDataService { } break; case Request::Operation::GET_INSTRUMENT: { req.method(http::verb::get); - auto target = this->getInstrumentTarget; + auto target = this->getInstrumentsTarget; req.target(target); } break; case Request::Operation::GET_INSTRUMENTS: { req.method(http::verb::get); - auto target = this->getInstrumentTarget; + auto target = this->getInstrumentsTarget; req.target(target); } break; default: @@ -213,12 +230,12 @@ class MarketDataServiceBybit : public MarketDataService { } void extractInstrumentInfo(Element& element, const rj::Value& x) { element.insert(CCAPI_INSTRUMENT, x["name"].GetString()); - element.insert(CCAPI_BASE_ASSET, x["baseCurrency"].GetString()); - element.insert(CCAPI_QUOTE_ASSET, x["quoteCurrency"].GetString()); + element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString()); + element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString()); element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["minPricePrecision"].GetString()); element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["basePrecision"].GetString()); - element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeQuantity"].GetString()); - element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minTradeAmount"].GetString()); + element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeQty"].GetString()); + element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minTradeAmt"].GetString()); } void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { @@ -226,14 +243,14 @@ class MarketDataServiceBybit : public MarketDataService { document.Parse(textMessage.c_str()); switch (request.getOperation()) { case Request::Operation::GET_RECENT_TRADES: { - for (const auto& x : document["result"].GetArray()) { + for (const auto& x : document["result"]["list"].GetArray()) { MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString())); MarketDataMessage::TypeForDataPoint dataPoint; dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))}); dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["qty"].GetString()))}); - dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["isBuyerMaker"].GetBool() ? "1" : "0"}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["isBuyerMaker"].GetString() ? "0" : "1"}); marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); marketDataMessageList.emplace_back(std::move(marketDataMessage)); } @@ -242,7 +259,7 @@ class MarketDataServiceBybit : public MarketDataService { Message message; message.setTimeReceived(timeReceived); message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); - for (const auto& x : document["result"].GetArray()) { + for (const auto& x : document["result"]["list"].GetArray()) { if (std::string(x["name"].GetString()) == request.getInstrument()) { Element element; this->extractInstrumentInfo(element, x); @@ -258,7 +275,7 @@ class MarketDataServiceBybit : public MarketDataService { message.setTimeReceived(timeReceived); message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); std::vector elementList; - for (const auto& x : document["result"].GetArray()) { + for (const auto& x : document["result"]["list"].GetArray()) { Element element; this->extractInstrumentInfo(element, x); elementList.push_back(element); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_base.h new file mode 100644 index 000000000..f1abd7ddc --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_base.h @@ -0,0 +1,23 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#if defined(CCAPI_ENABLE_EXCHANGE_BYBIT) || defined(CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES) +#include "ccapi_cpp/service/ccapi_market_data_service.h" +namespace ccapi { +class MarketDataServiceBybitBase : public MarketDataService { + public: + MarketDataServiceBybitBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {} + virtual ~MarketDataServiceBybitBase() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_derivatives.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_derivatives.h new file mode 100644 index 000000000..9b7461ac9 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_derivatives.h @@ -0,0 +1,315 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES +#include "ccapi_cpp/service/ccapi_market_data_service_bybit_base.h" +namespace ccapi { +class MarketDataServiceBybitDerivatives : public MarketDataServiceBybitBase { + public: + MarketDataServiceBybitDerivatives(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/{instrumentTypeSubstitute}/public/v3"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->getRecentTradesTarget = "/derivatives/v3/public/recent-trade"; + this->getInstrumentTarget = "/derivatives/v3/public/instruments-info"; + this->getInstrumentsTarget = "/derivatives/v3/public/instruments-info"; + } + virtual ~MarketDataServiceBybitDerivatives() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + std::string getInstrumentGroup(const Subscription& subscription) override { + const auto& instrumentType = subscription.getInstrumentType(); + std::string instrumentTypeSubstitute; + if (instrumentType == "usdt-contract") { + instrumentTypeSubstitute = "contract/usdt"; + } else if (instrumentType == "usdc-contract") { + instrumentTypeSubstitute = "contract/usdc"; + } else if (instrumentType == "usdc-options") { + instrumentTypeSubstitute = "option/usdc"; + } + std::string url = MarketDataService::getInstrumentGroup(subscription); + std::string toReplace("{instrumentTypeSubstitute}"); + url.replace(url.find(toReplace), toReplace.length(), instrumentTypeSubstitute); + return url; + } + void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, + const Subscription& subscription, const std::map optionMap) override { + const auto& marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + const auto& instrumentType = subscription.getInstrumentType(); + if (field == CCAPI_MARKET_DEPTH) { + std::vector depths; + if (instrumentType == "usdc-options") { + depths = {25, 100}; + } else { + depths = {1, 50, 200}; + } + int marketDepthSubscribedToExchange = 1; + marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, depths); + channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange); + this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange; + } + } + std::vector createSendStringList(const WsConnection& wsConnection) override { + std::vector sendStringList; + std::vector exchangeSubscriptionIdList; + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { + auto channelId = subscriptionListByChannelIdSymbolId.first; + for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) { + auto symbolId = subscriptionListByInstrument.first; + std::string exchangeSubscriptionId; + if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK, 0) == 0) { + int marketDepthSubscribedToExchange = + this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + exchangeSubscriptionId = CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK; + std::string toReplace = "{depth}"; + exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), std::to_string(marketDepthSubscribedToExchange)); + } else if (channelId == CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE) { + exchangeSubscriptionId = CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE; + } + std::string toReplace = "{symbol}"; + exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), symbolId); + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; + args.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator); + exchangeSubscriptionIdList.push_back(exchangeSubscriptionId); + } + } + document.AddMember("args", args, allocator); + document.AddMember("req_id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(), allocator); + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + exchangeSubscriptionIdList; + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + if (document.IsObject() && document.HasMember("op")) { + std::string op = document["op"].GetString(); + if (op == "subscribe") { + bool success = document["success"].GetBool(); + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + std::vector correlationIdList; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { + int id = std::stoi(document["req_id"].GetString()); + if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { + for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) { + std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) { + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) { + std::vector correlationIdList_2 = + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end()); + } + } + } + } + } + message.setCorrelationIdList(correlationIdList); + message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); + } + } else if (document.IsObject() && document.HasMember("data")) { + std::string exchangeSubscriptionId = document["topic"].GetString(); + std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + const rj::Value& data = document["data"]; + if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK, 0) == 0) { + MarketDataMessage marketDataMessage; + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(document["ts"].GetString()))); + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + std::string type = document["type"].GetString(); + marketDataMessage.recapType = type == "snapshot" ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE; + for (const auto& x : data["b"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : data["a"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } else if (channelId == CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE) { + for (const auto& x : data.GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["T"].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["i"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["S"].GetString()) == "Buy" ? "0" : "1"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + switch (request.getOperation()) { + case Request::Operation::GENERIC_PUBLIC_REQUEST: { + MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::GET_RECENT_TRADES: { + req.method(http::verb::get); + auto target = this->getRecentTradesTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_LIMIT, "limit"}, + }); + this->appendSymbolId(queryString, symbolId, "symbol"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENT: { + req.method(http::verb::get); + auto target = this->getInstrumentTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_INSTRUMENT_TYPE, "category"}, + }); + if (!symbolId.empty()) { + this->appendSymbolId(queryString, symbolId, "symbol"); + } + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENTS: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_INSTRUMENT_TYPE, "category"}, + }); + req.target(target + "?" + queryString); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractInstrumentInfo(Element& element, const rj::Value& x) { + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString()); + element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString()); + auto it = x.FindMember("settleCoin"); + if (it != x.MemberEnd()) { + element.insert(CCAPI_MARGIN_ASSET, it->value.GetString()); + } + element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceFilter"]["tickSize"].GetString()); + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["qtyStep"].GetString()); + element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minTradingQty"].GetString()); + } + void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + switch (request.getOperation()) { + case Request::Operation::GET_RECENT_TRADES: { + for (const auto& x : document["result"]["list"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString())); + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["size"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "sell" ? "0" : "1"}); + dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, x["execId"].GetString()}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_INSTRUMENT: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + for (const auto& x : document["result"]["list"].GetArray()) { + if (std::string(x["symbol"].GetString()) == request.getInstrument()) { + Element element; + this->extractInstrumentInfo(element, x); + message.setElementList({element}); + break; + } + } + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + case Request::Operation::GET_INSTRUMENTS: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + std::vector elementList; + for (const auto& x : document["result"]["list"].GetArray()) { + Element element; + this->extractInstrumentInfo(element, x); + elementList.push_back(element); + } + message.setElementList(elementList); + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_coinbase.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_coinbase.h index 369ae519b..e7e409d99 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_coinbase.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_coinbase.h @@ -10,14 +10,23 @@ class MarketDataServiceCoinbase : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_COINBASE; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/products//trades"; this->getInstrumentTarget = "/products/"; this->getInstrumentsTarget = "/products"; @@ -65,8 +74,19 @@ class MarketDataServiceCoinbase : public MarketDataService { sendStringList.push_back(sendString); return sendStringList; } - void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, - std::vector& marketDataMessageList) override { + void processTextMessage( +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage +#else + std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView +#endif + , + const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + WsConnection& wsConnection = *wsConnectionPtr; + std::string textMessage(textMessageView); +#endif rj::Document document; document.Parse(textMessage.c_str()); auto type = std::string(document["type"].GetString()); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_cryptocom.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_cryptocom.h index fbfffdb47..93ed67140 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_cryptocom.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_cryptocom.h @@ -10,14 +10,23 @@ class MarketDataServiceCryptocom : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_CRYPTOCOM; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/market"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/market"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/v2/public/get-trades"; this->getInstrumentTarget = "/v2/public/get-instruments"; this->getInstrumentsTarget = "/v2/public/get-instruments"; @@ -28,7 +37,7 @@ class MarketDataServiceCryptocom : public MarketDataService { private: #endif void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); if (field == CCAPI_MARKET_DEPTH) { int marketDepthSubscribedToExchange = 1; @@ -162,6 +171,7 @@ class MarketDataServiceCryptocom : public MarketDataService { } } } else { + std::string id = it->value.GetString(); std::string method = document["method"].GetString(); if (method == "subscribe") { if (std::string(document["code"].GetString()) != "0") { @@ -196,18 +206,9 @@ class MarketDataServiceCryptocom : public MarketDataService { event.setMessageList(messageList); } } else if (method == "public/heartbeat") { - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); - auto now = UtilTime::now(); - this->appendParam(document, allocator, std::chrono::duration_cast(now.time_since_epoch()).count(), "public/respond-heartbeat", - {}); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - std::string msg = stringBuffer.GetString(); + std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})"; ErrorCode ec; - this->send(hdl, msg, wspp::frame::opcode::text, ec); + this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec); if (ec) { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_deribit.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_deribit.h index eaafbfd85..1a777e94f 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_deribit.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_deribit.h @@ -10,14 +10,23 @@ class MarketDataServiceDeribit : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_DERIBIT; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->restTarget = "/api/v2"; this->getRecentTradesTarget = "/public/get_last_trades_by_instrument"; this->getInstrumentTarget = "/public/get_instrument"; @@ -50,7 +59,7 @@ class MarketDataServiceDeribit : public MarketDataService { } } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); if (field == CCAPI_MARKET_DEPTH) { if (marketDepthRequested == 1) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_erisx.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_erisx.h index a61d17efd..7759f6c58 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_erisx.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_erisx.h @@ -10,7 +10,7 @@ class MarketDataServiceErisx : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_ERISX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); // this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)(-?\\d+\\.?\\d*)"); } virtual ~MarketDataServiceErisx() {} @@ -19,7 +19,7 @@ class MarketDataServiceErisx : public MarketDataService { private: #endif void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); if (field == CCAPI_MARKET_DEPTH) { if (marketDepthRequested <= 20) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx.h index e8980574a..236216716 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx.h @@ -10,14 +10,23 @@ class MarketDataServiceFtx : public MarketDataServiceFtxBase { std::shared_ptr serviceContextPtr) : MarketDataServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_FTX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif } virtual ~MarketDataServiceFtx() {} }; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_base.h index db5795f90..40bd73de2 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_base.h @@ -21,7 +21,7 @@ class MarketDataServiceFtxBase : public MarketDataService { private: #endif void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); if (field == CCAPI_MARKET_DEPTH) { if (marketDepthRequested == 1) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_us.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_us.h index dbbc92e18..31708a705 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_us.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_us.h @@ -10,14 +10,23 @@ class MarketDataServiceFtxUs : public MarketDataServiceFtxBase { std::shared_ptr serviceContextPtr) : MarketDataServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_FTX_US; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif } virtual ~MarketDataServiceFtxUs() {} }; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio.h index c6444ec9e..13786e57f 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio.h @@ -10,14 +10,23 @@ class MarketDataServiceGateio : public MarketDataServiceGateioBase { std::shared_ptr serviceContextPtr) : MarketDataServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_GATEIO_API_KEY; this->setupCredential({this->apiKeyName}); std::string prefix = "/api/v4"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h index 1b4dda520..47a9d9d3d 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h @@ -21,7 +21,7 @@ class MarketDataServiceGateioBase : public MarketDataService { wspp::frame::opcode::text, ec); } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { @@ -76,7 +76,8 @@ class MarketDataServiceGateioBase : public MarketDataService { document.AddMember("payload", payload, allocator); if (!this->isDerivatives) { document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator); - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] + [this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList; this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; } @@ -115,7 +116,8 @@ class MarketDataServiceGateioBase : public MarketDataService { std::vector exchangeSubscriptionIdList; exchangeSubscriptionIdList.push_back(exchangeSubscriptionId); document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator); - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] + [this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList; this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; } @@ -143,8 +145,11 @@ class MarketDataServiceGateioBase : public MarketDataService { if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { int id = std::stoi(document["id"].GetString()); - if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.find(id) != this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.end()) { - for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.at(id)) { + if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { + for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) { auto splitted = UtilString::split(exchangeSubscriptionId, '|'); std::string channelId = splitted.at(0); std::string symbolId = splitted.at(1); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h index 10840458b..f7023214c 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h @@ -10,14 +10,23 @@ class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBa std::shared_ptr serviceContextPtr) : MarketDataServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY; this->setupCredential({this->apiKeyName}); std::string prefix = "/api/v4"; @@ -33,7 +42,7 @@ class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBa virtual ~MarketDataServiceGateioPerpetualFutures() {} std::string getInstrumentGroup(const Subscription& subscription) override { auto instrument = subscription.getInstrument(); - std::string url(this->baseUrl); + std::string url(this->baseUrlWs); if (UtilString::endsWith(instrument, "_USD")) { url += "btc"; } else if (UtilString::endsWith(instrument, "_USDT")) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gemini.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gemini.h index d84a3e553..5de73f6b4 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gemini.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gemini.h @@ -10,14 +10,23 @@ class MarketDataServiceGemini : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_GEMINI; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/marketdata"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/marketdata"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/v1/trades/:symbol"; this->getInstrumentTarget = "/v1/symbols/details/:symbol"; this->getInstrumentsTarget = "/v1/symbols"; @@ -28,7 +37,7 @@ class MarketDataServiceGemini : public MarketDataService { private: #endif void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { @@ -88,7 +97,7 @@ class MarketDataServiceGemini : public MarketDataService { return; } } - if (type == "update") { + if (type == "update" && !document["events"].GetArray().Empty()) { MarketDataMessage marketDataMessage; marketDataMessage.exchangeSubscriptionId = wsConnection.url; TimePoint time = timeReceived; @@ -154,7 +163,7 @@ class MarketDataServiceGemini : public MarketDataService { auto field = subscription.getField(); auto parameterList = UtilString::split(this->sessionConfigs.getExchangeFieldWebsocketChannelMap().at(this->exchangeName).at(field), ","); std::set parameterSet(parameterList.begin(), parameterList.end()); - std::string url = this->baseUrl + "/" + symbolId; + std::string url = this->baseUrlWs + "/" + symbolId; url += "?"; if ((parameterSet.find(CCAPI_WEBSOCKET_GEMINI_PARAMETER_BIDS) != parameterSet.end() || parameterSet.find(CCAPI_WEBSOCKET_GEMINI_PARAMETER_OFFERS) != parameterSet.end())) { @@ -238,12 +247,19 @@ class MarketDataServiceGemini : public MarketDataService { } break; case Request::Operation::GET_INSTRUMENTS: { req.method(http::verb::get); - req.target(this->getInstrumentTarget); + req.target(this->getInstrumentsTarget); } break; default: this->convertRequestForRestCustom(req, request, now, symbolId, credential); } } + void extractInstrumentInfo(Element& element, const rj::Value& x) { + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_BASE_ASSET, x["base_currency"].GetString()); + element.insert(CCAPI_QUOTE_ASSET, x["quote_currency"].GetString()); + element.insert(CCAPI_ORDER_PRICE_INCREMENT, Decimal(x["quote_increment"].GetString()).toString()); + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, Decimal(x["tick_size"].GetString()).toString()); + } void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { rj::Document document; @@ -268,11 +284,7 @@ class MarketDataServiceGemini : public MarketDataService { message.setTimeReceived(timeReceived); message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); Element element; - element.insert(CCAPI_INSTRUMENT, document["symbol"].GetString()); - element.insert(CCAPI_BASE_ASSET, document["base_currency"].GetString()); - element.insert(CCAPI_QUOTE_ASSET, document["quote_currency"].GetString()); - element.insert(CCAPI_ORDER_PRICE_INCREMENT, Decimal(document["quote_increment"].GetString()).toString()); - element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, Decimal(document["tick_size"].GetString()).toString()); + this->extractInstrumentInfo(element, document); message.setElementList({element}); message.setCorrelationIdList({request.getCorrelationId()}); event.addMessages({message}); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi.h index a8ca898aa..8e33a9ac6 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi.h @@ -10,20 +10,60 @@ class MarketDataServiceHuobi : public MarketDataServiceHuobiBase { std::shared_ptr serviceContextPtr) : MarketDataServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/market/history/trade"; this->getInstrumentTarget = "/v1/common/symbols"; this->getInstrumentsTarget = "/v1/common/symbols"; } virtual ~MarketDataServiceHuobi() {} - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find("err-code") != std::string::npos; } + void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, + const Subscription& subscription, const std::map optionMap) override { + auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); + CCAPI_LOGGER_TRACE(""); + if (field == CCAPI_MARKET_DEPTH) { + CCAPI_LOGGER_TRACE(""); + if (conflateIntervalMilliSeconds < 100) { + CCAPI_LOGGER_TRACE(""); + if (marketDepthRequested == 1) { + CCAPI_LOGGER_TRACE(""); + channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO; + } else { + CCAPI_LOGGER_TRACE(""); + channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE; + int marketDepthSubscribedToExchange = 1; + marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector({5, 10, 20})); + channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange); + this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange; + } + } else if (conflateIntervalMilliSeconds < 1000) { + if (marketDepthRequested == 1) { + channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO; + } else { + channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH; + } + } else { + channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH; + } + } + } + bool doesHttpBodyContainError(const std::string& body) override { return body.find("err-code") != std::string::npos; } void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& credential) override { switch (request.getOperation()) { @@ -41,23 +81,6 @@ class MarketDataServiceHuobi : public MarketDataServiceHuobiBase { MarketDataServiceHuobiBase::convertRequestForRest(req, request, now, symbolId, credential); } } - void extractInstrumentInfo(Element& element, const rj::Value& x) { - element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); - element.insert(CCAPI_BASE_ASSET, x["base-currency"].GetString()); - element.insert(CCAPI_QUOTE_ASSET, x["quote-currency"].GetString()); - int pricePrecision = std::stoi(x["price-precision"].GetString()); - if (pricePrecision > 0) { - element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(pricePrecision - 1, '0') + "1"); - } else { - element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1"); - } - int amountPrecision = std::stoi(x["amount-precision"].GetString()); - if (amountPrecision > 0) { - element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(amountPrecision - 1, '0') + "1"); - } else { - element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "1"); - } - } void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { switch (request.getOperation()) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_base.h index fe5424d68..b57417d62 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_base.h @@ -10,7 +10,12 @@ class MarketDataServiceHuobiBase : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->needDecompressWebsocketMessage = true; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET ErrorCode ec = this->inflater.init(false, 31); +#else + this->inflater.setWindowBitsOverride(31); + ErrorCode ec = this->inflater.init(); +#endif if (ec) { CCAPI_LOGGER_FATAL(ec.message()); } @@ -21,26 +26,17 @@ class MarketDataServiceHuobiBase : public MarketDataService { protected: #endif - void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { - auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); - auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); - if (field == CCAPI_MARKET_DEPTH) { - if (conflateIntervalMilliSeconds < 1000) { - if (marketDepthRequested == 1) { - channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO; - } else { - channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH; - } - } else { - channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH; - } - } - } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { auto now = UtilTime::now(); this->send(hdl, "{\"ping\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + "}", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + auto now = UtilTime::now(); + this->send(wsConnectionPtr, "{\"ping\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + "}", ec); + } +#endif std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { @@ -59,13 +55,28 @@ class MarketDataServiceHuobiBase : public MarketDataService { exchangeSubscriptionId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH; } else if (channelId.rfind(CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL, 0) == 0) { exchangeSubscriptionId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL; + } else if (channelId.rfind(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE, 0) == 0) { + this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true; + exchangeSubscriptionId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE; } - std::string toReplace("$symbol"); - std::string replacement(symbolId); - if (this->exchangeName == CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP) { - replacement = UtilString::toUpper(replacement); + { + std::string toReplace("$symbol"); + std::string replacement(symbolId); + if (this->exchangeName == CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP) { + replacement = UtilString::toUpper(replacement); + } + exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), replacement); + } + if (channelId.rfind(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE, 0) == 0) { + std::string toReplace("$levels"); + + CCAPI_LOGGER_TRACE("marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap=" + + toString(marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap)); + std::string replacement( + std::to_string(this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId))); + + exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), replacement); } - exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), replacement); document.AddMember("sub", rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator); if (this->isDerivatives) { document.AddMember("id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(), @@ -87,17 +98,28 @@ class MarketDataServiceHuobiBase : public MarketDataService { return sendStringList; } std::string getInstrumentGroup(const Subscription& subscription) override { - auto url = this->baseUrl; + auto url = this->baseUrlWs; auto field = subscription.getField(); if (!this->isDerivatives) { - if (field == CCAPI_TRADE || field == CCAPI_MARKET_DEPTH) { + if (field == CCAPI_TRADE || field == CCAPI_MARKET_DEPTH || field == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) { url += "/ws"; } } return url + "|" + field + "|" + subscription.getSerializedOptions(); } - void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, - std::vector& marketDataMessageList) override { + void processTextMessage( +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage +#else + std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView +#endif + , + const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + WsConnection& wsConnection = *wsConnectionPtr; + std::string textMessage(textMessageView); +#endif rj::Document document; document.Parse(textMessage.c_str()); if (document.IsObject() && document.HasMember("ch") && document.HasMember("tick")) { @@ -145,6 +167,41 @@ class MarketDataServiceHuobiBase : public MarketDataService { marketDataMessageList.emplace_back(std::move(marketDataMessage)); } } + } else if (std::regex_search(channelId, std::regex(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE_REGEX))) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] + ? MarketDataMessage::RecapType::NONE + : MarketDataMessage::RecapType::SOLICITED; + const rj::Value& tick = document["tick"]; + std::string ts = document["ts"].GetString(); + ts.insert(ts.size() - 3, "."); + marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(ts)); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + int bidIndex = 0; + int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + for (const auto& x : tick["bids"].GetArray()) { + if (bidIndex >= maxMarketDepth) { + break; + } + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + ++bidIndex; + } + int askIndex = 0; + for (const auto& x : tick["asks"].GetArray()) { + if (askIndex >= maxMarketDepth) { + break; + } + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + ++askIndex; + } + marketDataMessageList.emplace_back(std::move(marketDataMessage)); } else if (std::regex_search(channelId, std::regex(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH_REGEX))) { MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; @@ -209,7 +266,11 @@ class MarketDataServiceHuobiBase : public MarketDataService { payload += document["ping"].GetString(); payload += "}"; ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(hdl, payload, wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, payload, ec); +#endif if (ec) { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "pong"); } @@ -266,6 +327,7 @@ class MarketDataServiceHuobiBase : public MarketDataService { } } void extractInstrumentInfo(Element& element, const rj::Value& x) { + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); element.insert(CCAPI_BASE_ASSET, x["base-currency"].GetString()); element.insert(CCAPI_QUOTE_ASSET, x["quote-currency"].GetString()); int pricePrecision = std::stoi(x["price-precision"].GetString()); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h index 3bdd73675..c0af9922d 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h @@ -10,14 +10,23 @@ class MarketDataServiceHuobiCoinSwap : public MarketDataServiceHuobiDerivativesB std::shared_ptr serviceContextPtr) : MarketDataServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH; this->getInstrumentTarget = "/swap-api/v1/swap_contract_info"; this->getInstrumentsTarget = "/swap-api/v1/swap_contract_info"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h index f08d6d2b7..b6d5224b0 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h @@ -12,7 +12,23 @@ class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase this->isDerivatives = true; } virtual ~MarketDataServiceHuobiDerivativesBase() {} - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find("err_code") != std::string::npos; } + void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, + const Subscription& subscription, const std::map optionMap) override { + auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); + if (field == CCAPI_MARKET_DEPTH) { + if (conflateIntervalMilliSeconds < 1000) { + if (marketDepthRequested == 1) { + channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO; + } else { + channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH; + } + } else { + channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH; + } + } + } + bool doesHttpBodyContainError(const std::string& body) override { return body.find("err_code") != std::string::npos; } void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& credential) override { switch (request.getOperation()) { @@ -35,7 +51,7 @@ class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase void extractInstrumentInfo(Element& element, const rj::Value& x) { element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); element.insert(CCAPI_ORDER_PRICE_INCREMENT, UtilString::normalizeDecimalString(x["price_tick"].GetString())); - element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, UtilString::normalizeDecimalString(x["contract_size"].GetString())); + element.insert(CCAPI_CONTRACT_SIZE, UtilString::normalizeDecimalString(x["contract_size"].GetString())); } void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h index 700219668..3b2820c34 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h @@ -10,14 +10,23 @@ class MarketDataServiceHuobiUsdtSwap : public MarketDataServiceHuobiDerivativesB std::shared_ptr serviceContextPtr) : MarketDataServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-ws"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = CCAPI_HUOBI_USDT_SWAP_GET_RECENT_TRADES_PATH; this->getInstrumentTarget = "/linear-swap-api/v1/swap_contract_info"; this->getInstrumentsTarget = "/linear-swap-api/v1/swap_contract_info"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken.h index a3b5a8435..e85048731 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken.h @@ -10,18 +10,27 @@ class MarketDataServiceKraken : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); - this->shouldAlignSnapshot = true; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/0/public/Trades"; this->getInstrumentTarget = "/0/public/AssetPairs"; this->getInstrumentsTarget = "/0/public/AssetPairs"; + this->shouldAlignSnapshot = true; } virtual ~MarketDataServiceKraken() {} #ifndef CCAPI_EXPOSE_INTERNAL @@ -32,9 +41,9 @@ class MarketDataServiceKraken : public MarketDataService { auto now = UtilTime::now(); this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec); } - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("error":[])") == std::string::npos; } + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("error":[])") == std::string::npos; } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h index 68e46c752..4a1525fae 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h @@ -10,14 +10,23 @@ class MarketDataServiceKrakenFutures : public MarketDataService { std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1"; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif std::string prefix("/derivatives/api/v3"); this->getRecentTradesTarget = prefix + "/history"; this->getInstrumentTarget = prefix + "/instruments"; @@ -29,7 +38,7 @@ class MarketDataServiceKrakenFutures : public MarketDataService { private: #endif void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { symbolId = UtilString::toUpper(symbolId); } std::vector createSendStringList(const WsConnection& wsConnection) override { @@ -56,6 +65,18 @@ class MarketDataServiceKrakenFutures : public MarketDataService { std::string sendString = stringBuffer.GetString(); sendStringList.push_back(sendString); } + { + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("event", rj::Value("subscribe").Move(), allocator); + document.AddMember("feed", rj::Value("heartbeat").Move(), allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + } return sendStringList; } void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, @@ -104,8 +125,8 @@ class MarketDataServiceKrakenFutures : public MarketDataService { } } else { std::string feed = document["feed"].GetString(); - std::string productId = document["product_id"].GetString(); if (feed == "book" || feed == "book_snapshot") { + std::string productId = document["product_id"].GetString(); if (feed == "book") { MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; @@ -139,6 +160,7 @@ class MarketDataServiceKrakenFutures : public MarketDataService { marketDataMessageList.emplace_back(std::move(marketDataMessage)); } } else if (feed == "trade" || feed == "trade_snapshot") { + std::string productId = document["product_id"].GetString(); if (feed == "trade") { MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin.h index e0aa2b668..731118c1b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin.h @@ -10,24 +10,39 @@ class MarketDataServiceKucoin : public MarketDataServiceKucoinBase { std::shared_ptr serviceContextPtr) : MarketDataServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + // this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_KUCOIN_API_KEY; + this->apiSecretName = CCAPI_KUCOIN_API_SECRET; + this->apiPassphraseName = CCAPI_KUCOIN_API_PASSPHRASE; + this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName}); this->getRecentTradesTarget = "/api/v1/market/histories"; this->getInstrumentTarget = "/api/v1/symbols"; this->getInstrumentsTarget = "/api/v1/symbols"; this->channelMarketTicker = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_TICKER; this->channelMarketLevel2Depth5 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH5; this->channelMarketLevel2Depth50 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH50; + this->channelMarketLevel2 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2; this->tickerSubject = "trade.ticker"; this->tickerBestBidPriceKey = "bestBid"; this->tickerBestAskPriceKey = "bestAsk"; this->matchSubject = "trade.l3match"; + this->level2Subject = "level2"; this->recentTradesTimeKey = "time"; } virtual ~MarketDataServiceKucoin() {} @@ -42,6 +57,7 @@ class MarketDataServiceKucoin : public MarketDataServiceKucoinBase { element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceIncrement"].GetString()); element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["baseIncrement"].GetString()); element.insert(CCAPI_ORDER_QUANTITY_MIN, x["baseMinSize"].GetString()); + element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["quoteMinSize"].GetString()); } }; } /* namespace ccapi */ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h index a10379b7b..b82c94579 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h @@ -14,19 +14,32 @@ class MarketDataServiceKucoinBase : public MarketDataService { protected: #endif - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { - return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); - } + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { - if (marketDepthRequested == 1) { - channelId = this->channelMarketTicker; - } else if (marketDepthRequested <= 5) { - channelId = this->channelMarketLevel2Depth5; + if (this->isDerivatives) { + if (marketDepthRequested == 1) { + channelId = this->channelMarketTicker; + } else if (marketDepthRequested <= 5) { + channelId = this->channelMarketLevel2Depth5; + } else { + channelId = this->channelMarketLevel2Depth50; + } } else { - channelId = this->channelMarketLevel2Depth50; + // if (conflateIntervalMilliSeconds < 100) { + // channelId = this->channelMarketLevel2; + // }else{ + if (marketDepthRequested == 1) { + channelId = this->channelMarketTicker; + } else if (marketDepthRequested <= 5) { + channelId = this->channelMarketLevel2Depth5; + } else { + channelId = this->channelMarketLevel2Depth50; + } + // } } } } @@ -115,7 +128,8 @@ class MarketDataServiceKucoinBase : public MarketDataService { for (const auto& symbol : symbolList) { exchangeSubscriptionIdList.push_back(topic + ":" + symbol); } - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList; + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + exchangeSubscriptionIdList; this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator); rj::StringBuffer stringBuffer; @@ -126,6 +140,55 @@ class MarketDataServiceKucoinBase : public MarketDataService { } return sendStringList; } + void createFetchOrderBookInitialReq(http::request& req, const std::string& symbolId, const TimePoint& now, + const std::map& credential) override { + req.set(http::field::host, this->hostRest); + req.method(http::verb::get); + req.target("/api/v3/market/orderbook/level2?symbol=" + Url::urlEncode(symbolId)); + this->prepareReq(req, now, credential); + this->signRequest(req, "", credential); + } + void prepareReq(http::request& req, const TimePoint& now, const std::map& credential) { + req.set(beast::http::field::content_type, "application/json"); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("KC-API-KEY", apiKey); + req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); + req.set("KC-API-KEY-VERSION", "2"); + auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + this->signApiPassphrase(req, apiPassphrase, apiSecret); + } + void signRequest(http::request& req, const std::string& body, const std::map& credential) { + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string(); + preSignedText += std::string(req.method_string()); + preSignedText += req.target().to_string(); + preSignedText += body; + auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText)); + req.set("KC-API-SIGN", signature); + req.body() = body; + req.prepare_payload(); + } + void signApiPassphrase(http::request& req, const std::string& apiPassphrase, const std::string& apiSecret) { + req.set("KC-API-PASSPHRASE", UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, apiPassphrase))); + } + void extractOrderBookInitialVersionId(int64_t& versionId, const rj::Document& document) override { + versionId = std::stoll(document["data"]["sequence"].GetString()); + } + void extractOrderBookInitialData(MarketDataMessage::TypeForData& input, const rj::Document& document) override { + for (const auto& x : document["data"]["bids"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + input[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : document["data"]["asks"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + input[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + } void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { rj::Document document; @@ -135,7 +198,42 @@ class MarketDataServiceKucoinBase : public MarketDataService { if (it != document.MemberEnd()) { std::string type = it->value.GetString(); if (type == "message") { - if (std::string(document["subject"].GetString()) == this->tickerSubject) { + if (std::string(document["subject"].GetString()) == "trade.l2update") { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + std::string exchangeSubscriptionId = document["topic"].GetString(); + std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + const auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + const auto& data = document["data"]; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["time"].GetString())); + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + const auto& changes = data["changes"]; + const auto& itAsks = changes.FindMember("asks"); + if (itAsks != changes.MemberEnd()) { + const rj::Value& asks = itAsks->value; + for (auto& x : asks.GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + } + const auto& itBids = data.FindMember("changes"); + if (itBids != changes.MemberEnd()) { + const rj::Value& bids = itBids->value; + for (auto& x : bids.GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + } + int64_t versionId = std::stoll(data["sequenceEnd"].GetString()); + this->processOrderBookWithVersionId(versionId, wsConnection, channelId, symbolId, exchangeSubscriptionId, optionMap, marketDataMessageList, + marketDataMessage); + } else if (std::string(document["subject"].GetString()) == this->tickerSubject) { MarketDataMessage marketDataMessage; std::string exchangeSubscriptionId = document["topic"].GetString(); std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; @@ -163,7 +261,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); } marketDataMessageList.emplace_back(std::move(marketDataMessage)); - } else if (std::string(document["subject"].GetString()) == "level2") { + } else if (std::string(document["subject"].GetString()) == this->level2Subject) { MarketDataMessage marketDataMessage; std::string exchangeSubscriptionId = document["topic"].GetString(); std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; @@ -223,7 +321,9 @@ class MarketDataServiceKucoinBase : public MarketDataService { this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1; } - MarketDataService::onOpen(hdl); + Service::onOpen(hdl); + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->startSubscribe(wsConnection); } else if (type == "pong") { auto now = UtilTime::now(); this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now; @@ -236,8 +336,11 @@ class MarketDataServiceKucoinBase : public MarketDataService { if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { int id = std::stoi(document["id"].GetString()); - if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.find(id) != this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.end()) { - auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.at(id); + if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { + auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id); for (const auto& exchangeSubscriptionId : exchangeSubscriptionIdList) { auto splitted = UtilString::split(exchangeSubscriptionId, ":"); auto channelId = splitted.at(0); @@ -361,11 +464,14 @@ class MarketDataServiceKucoinBase : public MarketDataService { std::string channelMarketTicker; std::string channelMarketLevel2Depth5; std::string channelMarketLevel2Depth50; + std::string channelMarketLevel2; std::string tickerSubject; std::string tickerBestBidPriceKey; std::string tickerBestAskPriceKey; std::string matchSubject; std::string recentTradesTimeKey; + std::string level2Subject; + std::string apiPassphraseName; }; } /* namespace ccapi */ #endif diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h index 327c87190..95b4f8c16 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h @@ -10,14 +10,23 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase { std::shared_ptr serviceContextPtr) : MarketDataServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + // this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif this->getRecentTradesTarget = "/api/v1/trade/history"; this->getInstrumentTarget = "/api/v1/contracts/active"; this->getInstrumentsTarget = "/api/v1/contracts/active"; @@ -29,6 +38,7 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase { this->tickerBestBidPriceKey = "bestBidPrice"; this->tickerBestAskPriceKey = "bestAskPrice"; this->matchSubject = "match"; + this->level2Subject = "level2"; this->recentTradesTimeKey = "ts"; } virtual ~MarketDataServiceKucoinFutures() {} @@ -41,6 +51,7 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase { element.insert(CCAPI_UNDERLYING_SYMBOL, x["indexSymbol"].GetString()); element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["tickSize"].GetString()); element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSize"].GetString()); + element.insert(CCAPI_CONTRACT_MULTIPLIER, x["multiplier"].GetString()); } }; } /* namespace ccapi */ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h new file mode 100644 index 000000000..3bbb1d694 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h @@ -0,0 +1,347 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC +#include "ccapi_cpp/service/ccapi_market_data_service.h" +namespace ccapi { +class MarketDataServiceMexc : public MarketDataService { + public: + MarketDataServiceMexc(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC; + this->baseUrlWs = std::string(CCAPI_MEXC_URL_WS_BASE) + "/ws"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->getRecentTradesTarget = "/api/v3/trades"; + this->getRecentAggTradesTarget = "/api/v3/aggTrades"; + this->getInstrumentsTarget = "/api/v3/exchangeInfo"; + } + virtual ~MarketDataServiceMexc() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + // bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->send(hdl, R"({"id":)" + std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]) + R"(,"method":"PING"})", + wspp::frame::opcode::text, ec); + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + } + std::vector createSendStringList(const WsConnection& wsConnection) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("method", rj::Value("SUBSCRIPTION").Move(), allocator); + rj::Value params(rj::kArrayType); + std::vector exchangeSubscriptionIdList; + for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { + auto channelId = subscriptionListByChannelIdSymbolId.first; + for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) { + auto symbolId = subscriptionListByInstrument.first; + auto exchangeSubscriptionId = channelId + "@" + subscriptionListByInstrument.first; + params.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator); + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; + exchangeSubscriptionIdList.push_back(exchangeSubscriptionId); + } + } + document.AddMember("params", params, allocator); + document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator); + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + exchangeSubscriptionIdList; + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + void createFetchOrderBookInitialReq(http::request& req, const std::string& symbolId, const TimePoint& now, + const std::map& credential) override { + req.set(http::field::host, this->hostRest); + req.method(http::verb::get); + req.target("/api/v3/depth?symbol=" + Url::urlEncode(symbolId) + "&limit=5000"); + } + void extractOrderBookInitialVersionId(int64_t& versionId, const rj::Document& document) override { + versionId = std::stoll(document["lastUpdateId"].GetString()); + } + void extractOrderBookInitialData(MarketDataMessage::TypeForData& input, const rj::Document& document) override { + for (const auto& x : document["bids"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + input[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : document["asks"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + input[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + } + void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + if (document.IsObject() && document.HasMember("code") && std::string(document["code"].GetString()) == "0") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + std::vector correlationIdListSuccess, correlationIdListFailure; + std::string msg = document["msg"].GetString(); + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { + int id = std::stoi(document["id"].GetString()); + if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { + for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) { + std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) { + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) { + std::vector correlationIdList_2 = + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + for (const auto& correlationId : correlationIdList_2) { + if (exchangeSubscriptionId == msg) { + correlationIdListSuccess.push_back(correlationId); + } else { + correlationIdListFailure.push_back(correlationId); + } + } + } + } + } + } + } + if (!correlationIdListSuccess.empty()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList(correlationIdListSuccess); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + if (!correlationIdListFailure.empty()) { + Message message; + message.setTimeReceived(timeReceived); + message.setCorrelationIdList(correlationIdListFailure); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + event.setMessageList(messageList); + } else if (document.IsObject() && document.HasMember("c") && document.HasMember("d")) { + std::string exchangeSubscriptionId = document["c"].GetString(); + std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + const auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + const auto& correlationIdList = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + const rj::Value& data = document["d"]; + if (channelId == CCAPI_WEBSOCKET_MEXC_CHANNEL_DIFF_DEPTH) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["t"].GetString())); + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + const auto& itAsks = data.FindMember("asks"); + if (itAsks != data.MemberEnd()) { + const rj::Value& asks = itAsks->value; + for (auto& x : asks.GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["p"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x["v"].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + } + const auto& itBids = data.FindMember("bids"); + if (itBids != data.MemberEnd()) { + const rj::Value& bids = itBids->value; + for (auto& x : bids.GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["p"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x["v"].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + } + int64_t versionId = std::stoll(document["d"]["r"].GetString()); + this->processOrderBookWithVersionId(versionId, wsConnection, channelId, symbolId, exchangeSubscriptionId, optionMap, marketDataMessageList, + marketDataMessage); + } else if (channelId == CCAPI_WEBSOCKET_MEXC_CHANNEL_TRADE) { + for (const auto& x : data["deals"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["t"].GetString())); + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["S"].GetString()) == "2" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + switch (request.getOperation()) { + case Request::Operation::GENERIC_PUBLIC_REQUEST: { + MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::GET_RECENT_TRADES: { + req.method(http::verb::get); + auto target = this->getRecentTradesTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_LIMIT, "limit"}, + }); + this->appendSymbolId(queryString, symbolId, "symbol"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_RECENT_AGG_TRADES: { + req.method(http::verb::get); + auto target = this->getRecentAggTradesTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_LIMIT, "limit"}, + }); + this->appendSymbolId(queryString, symbolId, "symbol"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENT: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + std::string queryString; + this->appendSymbolId(queryString, symbolId, "symbol"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENTS: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + req.target(target); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractInstrumentInfo(Element& element, const rj::Value& x) { + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_BASE_ASSET, x["baseAsset"].GetString()); + element.insert(CCAPI_QUOTE_ASSET, x["quoteAsset"].GetString()); + int quotePrecision = std::stoi(x["quotePrecision"].GetString()); + if (quotePrecision > 0) { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(quotePrecision - 1, '0') + "1"); + } else { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1" + std::string(-quotePrecision, '0')); + } + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["baseSizePrecision"].GetString()); + element.insert(CCAPI_ORDER_QUANTITY_MIN, x["baseSizePrecision"].GetString()); + element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["quoteAmountPrecision"].GetString()); + } + void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + switch (request.getOperation()) { + case Request::Operation::GET_RECENT_TRADES: { + for (const auto& x : document.GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString())); + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["qty"].GetString()))}); + const auto& it = x.FindMember("id"); + if (it != x.MemberEnd() && !it->value.IsNull()) { + dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, it->value.GetString()}); + } + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["isBuyerMaker"].GetBool() ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_RECENT_AGG_TRADES: { + for (const auto& x : document.GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["T"].GetString())); + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["q"].GetString()))}); + const auto& it = x.FindMember("a"); + if (it != x.MemberEnd() && !it->value.IsNull()) { + dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, it->value.GetString()}); + } + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["m"].GetBool() ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::AGG_TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_INSTRUMENT: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + for (const auto& x : document["symbols"].GetArray()) { + if (std::string(x["symbol"].GetString()) == request.getInstrument()) { + Element element; + this->extractInstrumentInfo(element, x); + message.setElementList({element}); + break; + } + } + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + case Request::Operation::GET_INSTRUMENTS: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + std::vector elementList; + for (const auto& x : document["symbols"].GetArray()) { + Element element; + this->extractInstrumentInfo(element, x); + elementList.push_back(element); + } + message.setElementList(elementList); + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + std::string getRecentAggTradesTarget; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc_futures.h new file mode 100644 index 000000000..eba85b604 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc_futures.h @@ -0,0 +1,260 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_FUTURES_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_FUTURES_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES +#include "ccapi_cpp/service/ccapi_market_data_service.h" +namespace ccapi { +class MarketDataServiceMexcFutures : public MarketDataService { + public: + MarketDataServiceMexcFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC_FUTURES; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->getRecentTradesTarget = "/api/v1/contract/deals/{symbol}"; + this->getInstrumentsTarget = "/api/v1/contract/detail"; + } + virtual ~MarketDataServiceMexcFutures() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + protected: +#endif + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"ping"})", wspp::frame::opcode::text, ec); } + std::vector createSendStringList(const WsConnection& wsConnection) override { + std::vector sendStringList; + for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { + auto channelId = subscriptionListByChannelIdSymbolId.first; + for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) { + auto symbolId = subscriptionListByInstrument.first; + auto exchangeSubscriptionId = channelId + subscriptionListByInstrument.first; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("method", rj::Value(("sub." + channelId).c_str(), allocator).Move(), allocator); + rj::Value param(rj::kObjectType); + param.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator); + document.AddMember("param", param, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + } + } + return sendStringList; + } + void createFetchOrderBookInitialReq(http::request& req, const std::string& symbolId, const TimePoint& now, + const std::map& credential) override { + req.set(http::field::host, this->hostRest); + req.method(http::verb::get); + req.target("/api/v1/contract/depth/" + Url::urlEncode(symbolId)); + } + void extractOrderBookInitialVersionId(int64_t& versionId, const rj::Document& document) override { + versionId = std::stoll(document["data"]["version"].GetString()); + } + void extractOrderBookInitialData(MarketDataMessage::TypeForData& input, const rj::Document& document) override { + for (const auto& x : document["data"]["bids"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + input[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : document["data"]["asks"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + input[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + } + void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + if (document.IsObject() && document.HasMember("channel")) { + std::string channel = document["channel"].GetString(); + if (channel.rfind("push.", 0) == 0) { + std::string channelId = channel.substr(5); + std::string symbolId = document["symbol"].GetString(); + auto exchangeSubscriptionId = channelId + symbolId; + MarketDataMessage marketDataMessage; + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + const rj::Value& data = document["data"]; + if (channelId == CCAPI_WEBSOCKET_MEXC_FUTURES_CHANNEL_DEPTH) { + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["ts"].GetString())); + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + const auto& itAsks = data.FindMember("asks"); + if (itAsks != data.MemberEnd()) { + const rj::Value& asks = itAsks->value; + for (auto& x : asks.GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + } + const auto& itBids = data.FindMember("bids"); + if (itBids != data.MemberEnd()) { + const rj::Value& bids = itBids->value; + for (auto& x : bids.GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + } + int64_t versionId = std::stoll(data["version"].GetString()); + const auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]; + this->processOrderBookWithVersionId(versionId, wsConnection, channelId, symbolId, exchangeSubscriptionId, optionMap, marketDataMessageList, + marketDataMessage); + } else if (channelId == CCAPI_WEBSOCKET_MEXC_FUTURES_CHANNEL_TRANSACTION) { + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["t"].GetString())); + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(data["p"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(data["v"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(data["T"].GetString()) == "2" ? "0" : "1"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } else { + std::vector messageList; + if (channel == "rs.error") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + Message message; + message.setTimeReceived(timeReceived); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } else if (channel.rfind("rs.sub.", 0) == 0) { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + Message message; + message.setTimeReceived(timeReceived); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } + event.setMessageList(messageList); + } + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + switch (request.getOperation()) { + case Request::Operation::GENERIC_PUBLIC_REQUEST: { + MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::GET_RECENT_TRADES: { + req.method(http::verb::get); + auto target = this->getRecentTradesTarget; + std::string toReplace = "{symbol}"; + target.replace(target.find(toReplace), toReplace.length(), symbolId); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_LIMIT, "limit"}, + }); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENT: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + std::string queryString; + this->appendSymbolId(queryString, symbolId, "symbol"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENTS: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + req.target(target); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractInstrumentInfo(Element& element, const rj::Value& x) { + element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString()); + element.insert(CCAPI_MARGIN_ASSET, x["settleCoin"].GetString()); + element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceUnit"].GetString()); + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["volUnit"].GetString()); + element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minVol"].GetString()); + element.insert(CCAPI_CONTRACT_SIZE, x["contractSize"].GetString()); + } + void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + switch (request.getOperation()) { + case Request::Operation::GET_RECENT_TRADES: { + for (const auto& x : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["t"].GetString())); + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["T"].GetString()) == "2" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_INSTRUMENT: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + std::vector elementList; + Element element; + this->extractInstrumentInfo(element, document["data"]); + elementList.push_back(element); + message.setElementList(elementList); + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + case Request::Operation::GET_INSTRUMENTS: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + std::vector elementList; + for (const auto& x : document["data"].GetArray()) { + Element element; + this->extractInstrumentInfo(element, x); + elementList.push_back(element); + } + message.setElementList(elementList); + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_FUTURES_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_okex.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h similarity index 50% rename from linux/include/ccapi_cpp/service/ccapi_market_data_service_okex.h rename to linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h index 91e156757..5f501d21d 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_okex.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h @@ -1,54 +1,64 @@ -#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_ -#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKX_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKX_H_ #ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA -#ifdef CCAPI_ENABLE_EXCHANGE_OKEX +#ifdef CCAPI_ENABLE_EXCHANGE_OKX #include "ccapi_cpp/service/ccapi_market_data_service.h" namespace ccapi { -class MarketDataServiceOkex : public MarketDataService { +class MarketDataServiceOkx : public MarketDataService { public: - MarketDataServiceOkex(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr serviceContextPtr) + MarketDataServiceOkx(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { - this->exchangeName = CCAPI_EXCHANGE_NAME_OKEX; - this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKEX_PUBLIC_WS_PATH; - this->needDecompressWebsocketMessage = true; - ErrorCode ec = this->inflater.init(false); - if (ec) { - CCAPI_LOGGER_FATAL(ec.message()); - } + this->exchangeName = CCAPI_EXCHANGE_NAME_OKX; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKX_PUBLIC_WS_PATH; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); try { this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); } catch (const std::exception& e) { CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->apiKeyName = CCAPI_OKX_API_KEY; + this->apiSecretName = CCAPI_OKX_API_SECRET; + this->apiPassphraseName = CCAPI_OKX_API_PASSPHRASE; + this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName}); this->getRecentTradesTarget = "/api/v5/market/trades"; this->getInstrumentTarget = "/api/v5/public/instruments"; this->getInstrumentsTarget = "/api/v5/public/instruments"; } - virtual ~MarketDataServiceOkex() {} + virtual ~MarketDataServiceOkx() {} #ifndef CCAPI_EXPOSE_INTERNAL private: #endif - bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); } + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, - const std::map optionMap) override { + const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { if (conflateIntervalMilliSeconds < 100) { - if (marketDepthRequested <= 50) { - channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH50_L2_TBT; + if (marketDepthRequested == 1) { + channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT; + } else if (marketDepthRequested <= 50) { + channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH50_L2_TBT; } else { - channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400_L2_TBT; + channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400_L2_TBT; } } else { if (marketDepthRequested <= 5) { - channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5; + channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5; } else { - channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400; + channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400; } } } @@ -65,7 +75,7 @@ class MarketDataServiceOkex : public MarketDataService { auto channelId = subscriptionListByChannelIdSymbolId.first; for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) { std::string symbolId = subscriptionListBySymbolId.first; - if (channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5) { + if (channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5) { this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true; } std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId; @@ -112,106 +122,114 @@ class MarketDataServiceOkex : public MarketDataService { if (textMessage != "pong") { rj::Document document; document.Parse(textMessage.c_str()); - if (document.IsObject() && document.HasMember("arg")) { - const rj::Value& arg = document["arg"]; - std::string channelId = arg["channel"].GetString(); - std::string symbolId = arg["instId"].GetString(); - std::string exchangeSubscriptionId = channelId + ":" + symbolId; - if (document.HasMember("event")) { - std::string eventStr = document["event"].GetString(); - if (eventStr == "subscribe") { - event.setType(Event::Type::SUBSCRIPTION_STATUS); - std::vector messageList; - Message message; - message.setTimeReceived(timeReceived); - std::vector correlationIdList; - if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != - this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { - const rj::Value& arg = document["arg"]; - std::string channelId = arg["channel"].GetString(); - std::string symbolId = arg["instId"].GetString(); - if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != - this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) { - if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) != - this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) { - std::vector correlationIdList_2 = - this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); - correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end()); + auto it = document.FindMember("event"); + std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; + if (eventStr == "login") { + this->startSubscribe(wsConnection); + } else { + if (document.IsObject() && document.HasMember("arg")) { + const rj::Value& arg = document["arg"]; + std::string channelId = arg["channel"].GetString(); + std::string symbolId = arg["instId"].GetString(); + std::string exchangeSubscriptionId = channelId + ":" + symbolId; + if (!eventStr.empty()) { + if (eventStr == "subscribe") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + std::vector correlationIdList; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { + const rj::Value& arg = document["arg"]; + std::string channelId = arg["channel"].GetString(); + std::string symbolId = arg["instId"].GetString(); + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) { + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) { + std::vector correlationIdList_2 = + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end()); + } } } + message.setCorrelationIdList(correlationIdList); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + Element element; + element.insert(CCAPI_INFO_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); + } else if (eventStr == "error") { + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + message.setType(Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); } - message.setCorrelationIdList(correlationIdList); - message.setType(Message::Type::SUBSCRIPTION_STARTED); - Element element; - element.insert(CCAPI_INFO_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); - event.setMessageList(messageList); - } else if (eventStr == "error") { - event.setType(Event::Type::SUBSCRIPTION_STATUS); - std::vector messageList; - Message message; - message.setTimeReceived(timeReceived); - message.setType(Message::Type::SUBSCRIPTION_FAILURE); - Element element; - element.insert(CCAPI_ERROR_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); - event.setMessageList(messageList); - } - } else { - if (channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5 || channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400 || - channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH50_L2_TBT || channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400_L2_TBT) { - std::string action = channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5 ? "" : document["action"].GetString(); - for (const auto& datum : document["data"].GetArray()) { - if (this->sessionOptions.enableCheckOrderBookChecksum) { - auto it = datum.FindMember("checksum"); - if (it != datum.MemberEnd()) { - this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] = - intToHex(static_cast(static_cast(std::stoi(it->value.GetString())))); + } else { + if (channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5 || + channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400 || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH50_L2_TBT || + channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400_L2_TBT) { + std::string action = channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5 + ? "" + : document["action"].GetString(); + for (const auto& datum : document["data"].GetArray()) { + if (this->sessionOptions.enableCheckOrderBookChecksum) { + auto it = datum.FindMember("checksum"); + if (it != datum.MemberEnd()) { + this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] = + intToHex(static_cast(static_cast(std::stoi(it->value.GetString())))); + } } - } - MarketDataMessage marketDataMessage; - marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString()))); - marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; - marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; - if (channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5) { - if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) { - marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + MarketDataMessage marketDataMessage; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + if (channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5) { + if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) { + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + } else { + marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED; + } } else { - marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED; + marketDataMessage.recapType = action == "update" ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED; } - } else { - marketDataMessage.recapType = action == "update" ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED; + for (const auto& x : datum["bids"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : datum["asks"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + marketDataMessageList.emplace_back(std::move(marketDataMessage)); } - for (const auto& x : datum["bids"].GetArray()) { + } else if (channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_TRADE) { + for (const auto& datum : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; MarketDataMessage::TypeForDataPoint dataPoint; - dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); - dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); - marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["px"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["sz"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, datum["tradeId"].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "sell" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); } - for (const auto& x : datum["asks"].GetArray()) { - MarketDataMessage::TypeForDataPoint dataPoint; - dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); - dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); - marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); - } - marketDataMessageList.emplace_back(std::move(marketDataMessage)); - } - } else if (channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_TRADE) { - for (const auto& datum : document["data"].GetArray()) { - MarketDataMessage marketDataMessage; - marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; - marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; - marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString()))); - marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; - MarketDataMessage::TypeForDataPoint dataPoint; - dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["px"].GetString())}); - dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["sz"].GetString())}); - dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, datum["tradeId"].GetString()}); - dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "sell" ? "1" : "0"}); - marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); - marketDataMessageList.emplace_back(std::move(marketDataMessage)); } } } @@ -257,7 +275,6 @@ class MarketDataServiceOkex : public MarketDataService { { {CCAPI_INSTRUMENT_TYPE, "instType"}, }); - this->appendSymbolId(queryString, symbolId, "instId"); req.target(target + "?" + queryString); } break; default: @@ -273,6 +290,8 @@ class MarketDataServiceOkex : public MarketDataService { element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minSz"].GetString()); element.insert(CCAPI_MARGIN_ASSET, x["settleCcy"].GetString()); element.insert(CCAPI_UNDERLYING_SYMBOL, x["uly"].GetString()); + element.insert(CCAPI_CONTRACT_SIZE, x["ctVal"].GetString()); + element.insert(CCAPI_CONTRACT_MULTIPLIER, x["ctMult"].GetString()); } void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { @@ -326,8 +345,37 @@ class MarketDataServiceOkex : public MarketDataService { CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } } + std::vector createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector& subscriptionList, + const TimePoint& now, const std::map& credential) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("login").Move(), allocator); + rj::Value arg(rj::kObjectType); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName); + std::string ts = std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count()); + arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator); + arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator); + arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator); + std::string signData = ts + "GET" + "/users/self/verify"; + std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData)); + arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator); + rj::Value args(rj::kArrayType); + args.PushBack(arg, allocator); + document.AddMember("args", args, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + std::string apiPassphraseName; }; } /* namespace ccapi */ #endif #endif -#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_ +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKX_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h new file mode 100644 index 000000000..6dbd39d76 --- /dev/null +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h @@ -0,0 +1,340 @@ +#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_WHITEBIT_H_ +#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_WHITEBIT_H_ +#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA +#ifdef CCAPI_ENABLE_EXCHANGE_WHITEBIT +#include "ccapi_cpp/service/ccapi_market_data_service.h" +namespace ccapi { +class MarketDataServiceWhitebit : public MarketDataService { + public: + MarketDataServiceWhitebit(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, + std::shared_ptr serviceContextPtr) + : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { + this->exchangeName = CCAPI_EXCHANGE_NAME_WHITEBIT; + this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; + this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); + this->setHostRestFromUrlRest(this->baseUrlRest); + this->setHostWsFromUrlWs(this->baseUrlWs); + try { + this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + try { + this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + } catch (const std::exception& e) { + CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + } +#endif + this->getRecentTradesTarget = "/api/v4/public/trades/{market}"; + this->getInstrumentsTarget = "/api/v4/public/markets"; + this->methodDepthSubscribe = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) + "_subscribe"; + this->methodTradesSubscribe = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES) + "_subscribe"; + this->methodDepthUpdate = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) + "_update"; + this->methodTradesUpdate = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES) + "_update"; + this->shouldAlignSnapshot = true; + } + virtual ~MarketDataServiceWhitebit() {} +#ifndef CCAPI_EXPOSE_INTERNAL + + private: +#endif + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->send(hdl, R"({"id":)" + std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]) + R"(,"method":"ping","params":[]})", + wspp::frame::opcode::text, ec); + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + } + void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, + const Subscription& subscription, const std::map optionMap) override { + auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); + if (field == CCAPI_MARKET_DEPTH) { + int marketDepthSubscribedToExchange = marketDepthRequested; + // channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange); + this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange; + } + } + std::vector createSendStringList(const WsConnection& wsConnection) override { + std::vector sendStringList; + for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { + auto channelId = subscriptionListByChannelIdSymbolId.first; + if (channelId == CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) { + for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) { + auto symbolId = subscriptionListByInstrument.first; + auto exchangeSubscriptionId = channelId + subscriptionListByInstrument.first; + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator); + document.AddMember("method", rj::Value("depth_subscribe").Move(), allocator); + rj::Value params(rj::kArrayType); + params.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator); + int marketDepthSubscribedToExchange = + this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + params.PushBack(rj::Value(marketDepthSubscribedToExchange).Move(), allocator); + params.PushBack(rj::Value("0").Move(), allocator); + params.PushBack(rj::Value(true).Move(), allocator); + document.AddMember("params", params, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] + [this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = { + exchangeSubscriptionId}; + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + } + } else if (channelId == CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES) { + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator); + document.AddMember("method", rj::Value("trades_subscribe").Move(), allocator); + rj::Value params(rj::kArrayType); + std::vector exchangeSubscriptionIdList; + for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) { + auto symbolId = subscriptionListByInstrument.first; + params.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator); + auto exchangeSubscriptionId = channelId + subscriptionListByInstrument.first; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; + exchangeSubscriptionIdList.push_back(exchangeSubscriptionId); + } + document.AddMember("params", params, allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] + [this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + exchangeSubscriptionIdList; + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + } + } + return sendStringList; + } + void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + auto itId = document.FindMember("id"); + if (itId == document.MemberEnd() || itId->value.IsNull()) { + std::string method = document["method"].GetString(); + const auto& params = document["params"]; + if (method == this->methodDepthUpdate) { + bool isFullReload = params[0].GetBool(); + std::string symbolId = params[2].GetString(); + const auto& exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) + symbolId; + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.recapType = isFullReload ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE; + marketDataMessage.tp = timeReceived; + auto itBids = params[1].FindMember("bids"); + if (itBids != params[1].MemberEnd()) { + const rj::Value& bids = itBids->value; + for (const auto& x : bids.GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + } + auto itAsks = params[1].FindMember("asks"); + if (itAsks != params[1].MemberEnd()) { + const rj::Value& asks = itAsks->value; + for (const auto& x : asks.GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + } + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } else if (method == this->methodTradesUpdate) { + std::string symbolId = params[0].GetString(); + const auto& exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES) + symbolId; + for (const auto& x : params[1].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + auto timePair = UtilTime::divide(std::string(x["time"].GetString())); + auto tp = TimePoint(std::chrono::duration(timePair.first)); + tp += std::chrono::nanoseconds(timePair.second); + marketDataMessage.tp = tp; + if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES][symbolId]) { + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + } else { + marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED; + this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES][symbolId] = true; + } + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["amount"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["type"].GetString()) == "sell" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } + } else { + int id = std::stoi(itId->value.GetString()); + auto itResult = document.FindMember("result"); + if (itResult != document.MemberEnd()) { + if (itResult->value.IsObject()) { + const auto& result = itResult->value; + auto itError = document.FindMember("error"); + bool success = itError == document.MemberEnd() || itError->value.IsNull(); + event.setType(Event::Type::SUBSCRIPTION_STATUS); + std::vector messageList; + Message message; + message.setTimeReceived(timeReceived); + std::vector correlationIdList; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { + if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { + for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) { + std::string channelId = + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; + std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) { + if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) != + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) { + std::vector correlationIdList_2 = + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId); + correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end()); + } + } + } + } + } + message.setCorrelationIdList(correlationIdList); + message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); + } + } + } + } + void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& credential) override { + switch (request.getOperation()) { + case Request::Operation::GENERIC_PUBLIC_REQUEST: { + MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential); + } break; + case Request::Operation::GET_RECENT_TRADES: { + req.method(http::verb::get); + auto target = this->getRecentTradesTarget; + this->substituteParam(target, { + {"{market}", symbolId}, + }); + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, {}); + req.target(queryString.empty() ? target : target + "?" + queryString); + } break; + case Request::Operation::GET_INSTRUMENT: { + req.method(http::verb::get); + auto target = this->getInstrumentsTarget; + req.target(target); + } break; + case Request::Operation::GET_INSTRUMENTS: { + req.method(http::verb::get); + req.target(this->getInstrumentsTarget); + } break; + default: + this->convertRequestForRestCustom(req, request, now, symbolId, credential); + } + } + void extractInstrumentInfo(Element& element, const rj::Value& x) { + element.insert(CCAPI_INSTRUMENT, x["name"].GetString()); + element.insert(CCAPI_BASE_ASSET, x["stock"].GetString()); + element.insert(CCAPI_QUOTE_ASSET, x["money"].GetString()); + int moneyPrec = std::stoi(x["moneyPrec"].GetString()); + if (moneyPrec > 0) { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(moneyPrec - 1, '0') + "1"); + } else { + element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1" + std::string(-moneyPrec, '0')); + } + int stockPrec = std::stoi(x["stockPrec"].GetString()); + if (stockPrec > 0) { + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(stockPrec - 1, '0') + "1"); + } else { + element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "1" + std::string(-stockPrec, '0')); + } + element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minAmount"].GetString()); + element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minTotal"].GetString()); + } + void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { + rj::Document document; + document.Parse(textMessage.c_str()); + switch (request.getOperation()) { + case Request::Operation::GET_RECENT_TRADES: { + for (const auto& x : document.GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; + auto timePair = UtilTime::divide(std::string(x["trade_timestamp"].GetString())); + auto tp = TimePoint(std::chrono::duration(timePair.first)); + tp += std::chrono::nanoseconds(timePair.second); + marketDataMessage.tp = tp; + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["base_volume"].GetString()))}); + dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["tradeID"].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["type"].GetString()) == "sell" ? "1" : "0"}); + marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_INSTRUMENT: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + for (const auto& x : document.GetArray()) { + if (std::string(x["name"].GetString()) == request.getInstrument()) { + Element element; + this->extractInstrumentInfo(element, x); + message.setElementList({element}); + break; + } + } + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + case Request::Operation::GET_INSTRUMENTS: { + Message message; + message.setTimeReceived(timeReceived); + message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation())); + std::vector elementList; + for (const auto& x : document.GetArray()) { + Element element; + this->extractInstrumentInfo(element, x); + elementList.emplace_back(std::move(element)); + } + message.setElementList(elementList); + message.setCorrelationIdList({request.getCorrelationId()}); + event.addMessages({message}); + } break; + default: + CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); + } + } + std::string methodDepthSubscribe, methodDepthUpdate, methodTradesSubscribe, methodTradesUpdate; +}; +} /* namespace ccapi */ +#endif +#endif +#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_WHITEBIT_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_service.h b/linux/include/ccapi_cpp/service/ccapi_service.h index 874424361..289ebf615 100644 --- a/linux/include/ccapi_cpp/service/ccapi_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_service.h @@ -13,6 +13,9 @@ #ifndef RAPIDJSON_PARSE_ERROR_NORETURN #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) throw std::runtime_error(#parseErrorCode) #endif +#ifndef CCAPI_WEBSOCKET_WRITE_BUFFER_SIZE +#define CCAPI_WEBSOCKET_WRITE_BUFFER_SIZE 1 << 20 +#endif #include #include "boost/asio/strand.hpp" @@ -28,19 +31,30 @@ #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" // clang-format off +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET #include "websocketpp/config/boost_config.hpp" #include "websocketpp/client.hpp" #include "websocketpp/common/connection_hdl.hpp" #include "websocketpp/config/asio_client.hpp" +#else +#include "boost/beast/websocket.hpp" +#endif // clang-format on -#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || \ - defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_OKEX)) || \ - defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && (defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) + +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && \ + (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \ + defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \ + (defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_BITMART)) #include #include #include "ccapi_cpp/websocketpp_decompress_workaround.h" #endif +#else +#include "ccapi_cpp/ccapi_inflate_stream.h" +#endif + #include "ccapi_cpp/ccapi_fix_connection.h" #include "ccapi_cpp/ccapi_http_connection.h" #include "ccapi_cpp/ccapi_http_retry.h" @@ -57,7 +71,9 @@ namespace http = beast::http; namespace net = boost::asio; namespace ssl = boost::asio::ssl; using tcp = boost::asio::ip::tcp; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET namespace wspp = websocketpp; +#endif namespace rj = rapidjson; namespace ccapi { /** @@ -66,8 +82,12 @@ namespace ccapi { */ class Service : public std::enable_shared_from_this { public: - typedef wspp::lib::shared_ptr ServiceContextPtr; + typedef std::shared_ptr ServiceContextPtr; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET typedef wspp::lib::error_code ErrorCode; +#else + typedef boost::system::error_code ErrorCode; // a.k.a. beast::error_code +#endif enum class PingPongMethod { WEBSOCKET_PROTOCOL_LEVEL, WEBSOCKET_APPLICATION_LEVEL, @@ -97,11 +117,12 @@ class Service : public std::enable_shared_from_this { sessionConfigs(sessionConfigs), serviceContextPtr(serviceContextPtr), resolver(*serviceContextPtr->ioContextPtr), + resolverWs(*serviceContextPtr->ioContextPtr), httpConnectionPool(sessionOptions.httpConnectionPoolMaxSize) { this->enableCheckPingPongWebsocketProtocolLevel = this->sessionOptions.enableCheckPingPongWebsocketProtocolLevel; this->enableCheckPingPongWebsocketApplicationLevel = this->sessionOptions.enableCheckPingPongWebsocketApplicationLevel; - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pingWebsocketProtocolLevelIntervalMilliSeconds; - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds; + // this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pingWebsocketProtocolLevelIntervalMilliSeconds; + // this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds; this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pingWebsocketApplicationLevelIntervalMilliSeconds; this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pongWebsocketApplicationLevelTimeoutMilliSeconds; this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixIntervalMilliSeconds; @@ -125,7 +146,7 @@ class Service : public std::enable_shared_from_this { this->httpConnectionPoolPurgeTimer->cancel(); } } - // void setEventHandler(const std::function& eventHandler) { this->eventHandler = eventHandler; } + void purgeHttpConnectionPool() { this->httpConnectionPool.purge(); } void stop() { for (const auto& x : this->sendRequestDelayTimerByCorrelationIdMap) { x.second->cancel(); @@ -133,13 +154,22 @@ class Service : public std::enable_shared_from_this { sendRequestDelayTimerByCorrelationIdMap.clear(); this->shouldContinue = false; for (const auto& x : this->wsConnectionByIdMap) { - auto wsConnection = x.second; ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + auto wsConnection = x.second; this->close(wsConnection, wsConnection.hdl, websocketpp::close::status::normal, "stop", ec); +#else + auto wsConnectionPtr = x.second; + this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason("stop"), ec); +#endif if (ec) { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; +#else + this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false; +#endif } } virtual void convertRequestForRestCustom(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, @@ -188,19 +218,20 @@ class Service : public std::enable_shared_from_this { std::shared_ptr> promisePtr(promisePtrRaw); HttpRetry retry(0, 0, "", promisePtr); if (delayMilliSeconds > 0) { - this->sendRequestDelayTimerByCorrelationIdMap[request.getCorrelationId()] = this->serviceContextPtr->tlsClientPtr->set_timer( - delayMilliSeconds, [that = shared_from_this(), request, req, retry, eventQueuePtr](ErrorCode const& ec) mutable { - if (ec) { - CCAPI_LOGGER_ERROR("request = " + toString(request) + ", sendRequest timer error: " + ec.message()); - that->onError(Event::Type::REQUEST_STATUS, Message::Type::GENERIC_ERROR, ec, "timer", {request.getCorrelationId()}, eventQueuePtr); - } else { - auto thatReq = req; - auto now = UtilTime::now(); - request.setTimeSent(now); - that->tryRequest(request, thatReq, retry, eventQueuePtr); - } - that->sendRequestDelayTimerByCorrelationIdMap.erase(request.getCorrelationId()); - }); + TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliSeconds))); + timerPtr->async_wait([that = shared_from_this(), request, req, retry, eventQueuePtr](ErrorCode const& ec) mutable { + if (ec) { + CCAPI_LOGGER_ERROR("request = " + toString(request) + ", sendRequest timer error: " + ec.message()); + that->onError(Event::Type::REQUEST_STATUS, Message::Type::GENERIC_ERROR, ec, "timer", {request.getCorrelationId()}, eventQueuePtr); + } else { + auto thatReq = req; + auto now = UtilTime::now(); + request.setTimeSent(now); + that->tryRequest(request, thatReq, retry, eventQueuePtr); + } + that->sendRequestDelayTimerByCorrelationIdMap.erase(request.getCorrelationId()); + }); + this->sendRequestDelayTimerByCorrelationIdMap[request.getCorrelationId()] = timerPtr; } else { request.setTimeSent(now); this->tryRequest(request, req, retry, eventQueuePtr); @@ -261,27 +292,46 @@ class Service : public std::enable_shared_from_this { protected: #endif + // static std::string printableString(const char* s, size_t n) { + // std::string output(s, n); + // std::replace(output.begin(), output.end(), '\x01', '^'); + // return output; + // } + // static std::string printableString(const std::string& s) { + // std::string output(s); + // std::replace(output.begin(), output.end(), '\x01', '^'); + // return output; + // } typedef ServiceContext::SslContextPtr SslContextPtr; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET typedef ServiceContext::TlsClient TlsClient; - typedef wspp::lib::shared_ptr TimerPtr; +#endif + typedef std::shared_ptr TimerPtr; void setHostRestFromUrlRest(std::string baseUrlRest) { auto hostPort = this->extractHostFromUrl(baseUrlRest); this->hostRest = hostPort.first; this->portRest = hostPort.second; } + void setHostWsFromUrlWs(std::string baseUrlWs) { + auto hostPort = this->extractHostFromUrl(baseUrlWs); + this->hostWs = hostPort.first; + this->portWs = hostPort.second; + } std::pair extractHostFromUrl(std::string baseUrl) { std::string host; std::string port; - auto splitted1 = UtilString::split(baseUrl, "://"); - auto splitted2 = UtilString::split(UtilString::split(splitted1[1], "/")[0], ":"); - host = splitted2[0]; - if (splitted2.size() == 2) { - port = splitted2[1]; - } else { - if (splitted1[0] == "https") { - port = CCAPI_HTTPS_PORT_DEFAULT; + if (!baseUrl.empty()) { + auto splitted1 = UtilString::split(baseUrl, "://"); + auto splitted2 = UtilString::split(UtilString::split(splitted1.at(1), "/").at(0), ":"); + host = splitted2.at(0); + if (splitted2.size() == 2) { + port = splitted2.at(1); } else { - port = CCAPI_HTTP_PORT_DEFAULT; + if (splitted1.at(0) == "https" || splitted1.at(0) == "wss") { + port = CCAPI_HTTPS_PORT_DEFAULT; + } else { + port = CCAPI_HTTP_PORT_DEFAULT; + } } } return std::make_pair(host, port); @@ -299,7 +349,8 @@ class Service : public std::enable_shared_from_this { #endif std::shared_ptr> streamPtr(nullptr); try { - streamPtr = this->createStream(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, this->hostRest); + streamPtr = this->createStream>(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, + this->hostRest); } catch (const beast::error_code& ec) { CCAPI_LOGGER_TRACE("fail"); errorHandler(ec); @@ -319,7 +370,7 @@ class Service : public std::enable_shared_from_this { #endif std::shared_ptr> streamPtr(nullptr); try { - streamPtr = this->createStream(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, host); + streamPtr = this->createStream>(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, host); } catch (const beast::error_code& ec) { CCAPI_LOGGER_TRACE("fail"); errorHandler(ec); @@ -368,21 +419,21 @@ class Service : public std::enable_shared_from_this { // #ifdef CCAPI_DISABLE_NAGLE_ALGORITHM beast::get_lowest_layer(stream).socket().set_option(tcp::no_delay(true)); // #endif - CCAPI_LOGGER_TRACE("before async_handshake"); + CCAPI_LOGGER_TRACE("before ssl async_handshake"); stream.async_handshake(ssl::stream_base::client, - beast::bind_front_handler(&Service::onHandshake, shared_from_this(), httpConnectionPtr, req, errorHandler, responseHandler)); - CCAPI_LOGGER_TRACE("after async_handshake"); + beast::bind_front_handler(&Service::onSslHandshake, shared_from_this(), httpConnectionPtr, req, errorHandler, responseHandler)); + CCAPI_LOGGER_TRACE("after ssl async_handshake"); } - void onHandshake(std::shared_ptr httpConnectionPtr, http::request req, - std::function errorHandler, std::function&)> responseHandler, - beast::error_code ec) { - CCAPI_LOGGER_TRACE("async_handshake callback start"); + void onSslHandshake(std::shared_ptr httpConnectionPtr, http::request req, + std::function errorHandler, std::function&)> responseHandler, + beast::error_code ec) { + CCAPI_LOGGER_TRACE("ssl async_handshake callback start"); if (ec) { CCAPI_LOGGER_TRACE("fail"); errorHandler(ec); return; } - CCAPI_LOGGER_TRACE("handshaked"); + CCAPI_LOGGER_TRACE("ssl handshaked"); beast::ssl_stream& stream = *httpConnectionPtr->streamPtr; std::shared_ptr> reqPtr(new http::request(std::move(req))); CCAPI_LOGGER_TRACE("before async_write"); @@ -436,9 +487,9 @@ class Service : public std::enable_shared_from_this { #endif responseHandler(*resPtr); } - std::shared_ptr> createStream(std::shared_ptr iocPtr, std::shared_ptr ctxPtr, - const std::string& host) { - std::shared_ptr> streamPtr(new beast::ssl_stream(*iocPtr, *ctxPtr)); + template + std::shared_ptr createStream(std::shared_ptr iocPtr, std::shared_ptr ctxPtr, const std::string& host) { + std::shared_ptr streamPtr(new T(*iocPtr, *ctxPtr)); // Set SNI Hostname (many hosts need this to handshake successfully) if (!SSL_set_tlsext_host_name(streamPtr->native_handle(), host.c_str())) { beast::error_code ec{static_cast(::ERR_get_error()), net::error::get_ssl_category()}; @@ -447,6 +498,35 @@ class Service : public std::enable_shared_from_this { } return streamPtr; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + template <> + std::shared_ptr>> createStream(std::shared_ptr iocPtr, + std::shared_ptr ctxPtr, + const std::string& host) { + CCAPI_LOGGER_TRACE("host = " + host) + std::shared_ptr>> streamPtr( + new beast::websocket::stream>(*iocPtr, *ctxPtr)); + // Set SNI Hostname (many hosts need this to handshake successfully) + if (!SSL_set_tlsext_host_name(streamPtr->next_layer().native_handle(), host.c_str())) { + beast::error_code ec{static_cast(::ERR_get_error()), net::error::get_ssl_category()}; + CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message()); + throw ec; + } + return streamPtr; + } +#endif + // std::shared_ptr> createStream(std::shared_ptr iocPtr, std::shared_ptr ctxPtr, + // const std::string& host) { + // std::shared_ptr> streamPtr(new beast::ssl_stream(*iocPtr, *ctxPtr)); + // // Set SNI Hostname (many hosts need this to handshake successfully) + // if (!SSL_set_tlsext_host_name(streamPtr->native_handle(), host.c_str())) { + // beast::error_code ec{static_cast(::ERR_get_error()), net::error::get_ssl_category()}; + // CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message()); + // throw ec; + // } + // return streamPtr; + // } void performRequest(std::shared_ptr httpConnectionPtr, const Request& request, http::request& req, const HttpRetry& retry, Queue* eventQueuePtr) { CCAPI_LOGGER_FUNCTION_ENTER; @@ -477,20 +557,20 @@ class Service : public std::enable_shared_from_this { // #ifdef CCAPI_DISABLE_NAGLE_ALGORITHM beast::get_lowest_layer(stream).socket().set_option(tcp::no_delay(true)); // #endif - CCAPI_LOGGER_TRACE("before async_handshake"); + CCAPI_LOGGER_TRACE("before ssl async_handshake"); stream.async_handshake(ssl::stream_base::client, - beast::bind_front_handler(&Service::onHandshake_2, shared_from_this(), httpConnectionPtr, request, req, retry, eventQueuePtr)); - CCAPI_LOGGER_TRACE("after async_handshake"); + beast::bind_front_handler(&Service::onSslHandshake_2, shared_from_this(), httpConnectionPtr, request, req, retry, eventQueuePtr)); + CCAPI_LOGGER_TRACE("after ssl async_handshake"); } - void onHandshake_2(std::shared_ptr httpConnectionPtr, Request request, http::request req, HttpRetry retry, - Queue* eventQueuePtr, beast::error_code ec) { - CCAPI_LOGGER_TRACE("async_handshake callback start"); + void onSslHandshake_2(std::shared_ptr httpConnectionPtr, Request request, http::request req, HttpRetry retry, + Queue* eventQueuePtr, beast::error_code ec) { + CCAPI_LOGGER_TRACE("ssl async_handshake callback start"); if (ec) { CCAPI_LOGGER_TRACE("fail"); - this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "handshake", {request.getCorrelationId()}, eventQueuePtr); + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "ssl handshake", {request.getCorrelationId()}, eventQueuePtr); return; } - CCAPI_LOGGER_TRACE("handshaked"); + CCAPI_LOGGER_TRACE("ssl handshaked"); this->startWrite_2(httpConnectionPtr, request, req, retry, eventQueuePtr); } void startWrite_2(std::shared_ptr httpConnectionPtr, Request request, http::request req, HttpRetry retry, @@ -512,6 +592,7 @@ class Service : public std::enable_shared_from_this { if (ec) { CCAPI_LOGGER_TRACE("fail"); this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "write", {request.getCorrelationId()}, eventQueuePtr); + this->httpConnectionPool.purge(); auto now = UtilTime::now(); auto req = this->convertRequest(request, now); retry.numRetry += 1; @@ -529,7 +610,8 @@ class Service : public std::enable_shared_from_this { CCAPI_LOGGER_TRACE("after async_read"); } void setHttpConnectionPoolPurgeTimer() { - this->httpConnectionPoolPurgeTimer = this->serviceContextPtr->tlsClientPtr->set_timer(5000, [that = shared_from_this()](ErrorCode const& ec) { + TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(5000))); + timerPtr->async_wait([that = shared_from_this()](ErrorCode const& ec) { auto now = UtilTime::now(); if (ec) { that->onError(Event::Type::SESSION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); @@ -541,6 +623,7 @@ class Service : public std::enable_shared_from_this { that->setHttpConnectionPoolPurgeTimer(); } }); + this->httpConnectionPoolPurgeTimer = timerPtr; } void onRead_2(std::shared_ptr httpConnectionPtr, Request request, std::shared_ptr> reqPtr, HttpRetry retry, std::shared_ptr bufferPtr, std::shared_ptr> resPtr, Queue* eventQueuePtr, @@ -592,7 +675,13 @@ class Service : public std::enable_shared_from_this { this->processSuccessfulTextMessageRest(statusCode, request, body, now, eventQueuePtr); } else if (statusCode / 100 == 3) { if (resPtr->base().find("Location") != resPtr->base().end()) { - Url url(resPtr->base().at("Location").to_string()); + Url url(resPtr->base() + .at("Location") +#if BOOST_VERSION < 108100 + // Boost Beast 1.81 uses boost::core::string_view which doesn't contain to_string() method + .to_string() +#endif + ); std::string host(url.host); if (!url.port.empty()) { host += ":"; @@ -637,7 +726,7 @@ class Service : public std::enable_shared_from_this { retry.promisePtr->set_value(); } } - virtual bool doesHttpBodyContainError(const Request& request, const std::string& body) { return false; } + virtual bool doesHttpBodyContainError(const std::string& body) { return false; } void tryRequest(const Request& request, http::request& req, const HttpRetry& retry, Queue* eventQueuePtr) { CCAPI_LOGGER_FUNCTION_ENTER; #if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) @@ -651,14 +740,15 @@ class Service : public std::enable_shared_from_this { if (this->sessionOptions.enableOneHttpConnectionPerRequest || this->httpConnectionPool.empty()) { std::shared_ptr> streamPtr(nullptr); try { - streamPtr = this->createStream(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, this->hostRest); + streamPtr = this->createStream>(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, + this->hostRest); } catch (const beast::error_code& ec) { CCAPI_LOGGER_TRACE("fail"); this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "create stream", {request.getCorrelationId()}, eventQueuePtr); return; } std::shared_ptr httpConnectionPtr(new HttpConnection(this->hostRest, this->portRest, streamPtr)); - CCAPI_LOGGER_TRACE("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr)); + CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr)); this->performRequest(httpConnectionPtr, request, req, retry, eventQueuePtr); } else { std::shared_ptr httpConnectionPtr(nullptr); @@ -672,14 +762,15 @@ class Service : public std::enable_shared_from_this { } std::shared_ptr> streamPtr(nullptr); try { - streamPtr = this->createStream(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, this->hostRest); + streamPtr = this->createStream>(this->serviceContextPtr->ioContextPtr, + this->serviceContextPtr->sslContextPtr, this->hostRest); } catch (const beast::error_code& ec) { CCAPI_LOGGER_TRACE("fail"); this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "create stream", {request.getCorrelationId()}, eventQueuePtr); return; } httpConnectionPtr = std::make_shared(this->hostRest, this->portRest, streamPtr); - CCAPI_LOGGER_TRACE("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr)); + CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr)); this->performRequest(httpConnectionPtr, request, req, retry, eventQueuePtr); } } @@ -711,6 +802,8 @@ class Service : public std::enable_shared_from_this { req.version(11); if (this->sessionOptions.enableOneHttpConnectionPerRequest) { req.keep_alive(false); + } else { + req.keep_alive(true); } req.set(http::field::host, this->hostRest); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); @@ -718,24 +811,6 @@ class Service : public std::enable_shared_from_this { CCAPI_LOGGER_FUNCTION_EXIT; return req; } - SslContextPtr onTlsInit(wspp::connection_hdl hdl) { return this->serviceContextPtr->sslContextPtr; } - WsConnection& getWsConnectionFromConnectionPtr(TlsClient::connection_ptr connectionPtr) { - return this->wsConnectionByIdMap.at(this->connectionAddressToString(connectionPtr)); - } - std::string connectionAddressToString(const TlsClient::connection_ptr con) { - const void* address = static_cast(con.get()); - std::stringstream ss; - ss << address; - return ss.str(); - } - void close(WsConnection& wsConnection, wspp::connection_hdl hdl, wspp::close::status::value const code, std::string const& reason, ErrorCode& ec) { - if (wsConnection.status == WsConnection::Status::CLOSING) { - CCAPI_LOGGER_WARN("websocket connection is already in the state of closing"); - return; - } - wsConnection.status = WsConnection::Status::CLOSING; - this->serviceContextPtr->tlsClientPtr->close(hdl, code, reason, ec); - } void substituteParam(std::string& target, const std::map& param, const std::map standardizationMap = {}) { for (const auto& kv : param) { auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; @@ -758,6 +833,9 @@ class Service : public std::enable_shared_from_this { ++i; } } + void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId, const std::string symbolIdCalled) { + rjValue.AddMember(rj::Value(symbolIdCalled.c_str(), allocator).Move(), rj::Value(symbolId.c_str(), allocator).Move(), allocator); + } void appendSymbolId(std::string& queryString, const std::string& symbolId, const std::string symbolIdCalled) { if (!symbolId.empty()) { queryString += symbolIdCalled; @@ -766,10 +844,6 @@ class Service : public std::enable_shared_from_this { queryString += "&"; } } - // virtual std::string convertNumberToStringInJson(const std::string& jsonString) { - // auto quotedTextMessage = std::regex_replace(jsonString, this->convertNumberToStringInJsonRegex, - // this->convertNumberToStringInJsonRewrite); return quotedTextMessage; - // } void setupCredential(std::vector nameList) { for (const auto& x : nameList) { if (this->sessionConfigs.getCredential().find(x) != this->sessionConfigs.getCredential().end()) { @@ -779,6 +853,29 @@ class Service : public std::enable_shared_from_this { } } } + http::verb convertHttpMethodStringToMethod(const std::string& methodString) { + std::string methodStringUpper = UtilString::toUpper(methodString); + return http::string_to_verb(methodStringUpper); + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + SslContextPtr onTlsInit(wspp::connection_hdl hdl) { return this->serviceContextPtr->sslContextPtr; } + WsConnection& getWsConnectionFromConnectionPtr(TlsClient::connection_ptr connectionPtr) { + return this->wsConnectionByIdMap.at(this->connectionAddressToString(connectionPtr)); + } + std::string connectionAddressToString(const TlsClient::connection_ptr con) { + const void* address = static_cast(con.get()); + std::stringstream ss; + ss << address; + return ss.str(); + } + void close(WsConnection& wsConnection, wspp::connection_hdl hdl, wspp::close::status::value const code, std::string const& reason, ErrorCode& ec) { + if (wsConnection.status == WsConnection::Status::CLOSING) { + CCAPI_LOGGER_WARN("websocket connection is already in the state of closing"); + return; + } + wsConnection.status = WsConnection::Status::CLOSING; + this->serviceContextPtr->tlsClientPtr->close(hdl, code, reason, ec); + } virtual void prepareConnect(WsConnection& wsConnection) { this->connect(wsConnection); } virtual void connect(WsConnection& wsConnection) { CCAPI_LOGGER_FUNCTION_ENTER; @@ -833,6 +930,7 @@ class Service : public std::enable_shared_from_this { message.setCorrelationIdList(correlationIdList); Element element; element.insert(CCAPI_CONNECTION_ID, wsConnection.id); + element.insert(CCAPI_CONNECTION_URL, wsConnection.url); message.setElementList({element}); event.setMessageList({message}); this->eventHandler(event, nullptr); @@ -856,21 +954,22 @@ class Service : public std::enable_shared_from_this { if (this->connectRetryOnFailTimerByConnectionIdMap.find(thisWsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) { this->connectRetryOnFailTimerByConnectionIdMap.at(thisWsConnection.id)->cancel(); } - this->connectRetryOnFailTimerByConnectionIdMap[thisWsConnection.id] = - this->serviceContextPtr->tlsClientPtr->set_timer(seconds * 1000, [thisWsConnection, that = shared_from_this(), urlBase](ErrorCode const& ec) { - if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) { - if (ec) { - CCAPI_LOGGER_ERROR("wsConnection = " + toString(thisWsConnection) + ", connect retry on fail timer error: " + ec.message()); - that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); - } else { - CCAPI_LOGGER_INFO("about to retry"); - auto thatWsConnection = thisWsConnection; - thatWsConnection.assignDummyId(); - that->prepareConnect(thatWsConnection); - that->connectNumRetryOnFailByConnectionUrlMap[urlBase] += 1; - } - } - }); + TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000))); + timerPtr->async_wait([thisWsConnection, that = shared_from_this(), urlBase](ErrorCode const& ec) { + if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("wsConnection = " + toString(thisWsConnection) + ", connect retry on fail timer error: " + ec.message()); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + CCAPI_LOGGER_INFO("about to retry"); + auto thatWsConnection = thisWsConnection; + thatWsConnection.assignDummyId(); + that->prepareConnect(thatWsConnection); + that->connectNumRetryOnFailByConnectionUrlMap[urlBase] += 1; + } + } + }); + this->connectRetryOnFailTimerByConnectionIdMap[thisWsConnection.id] = timerPtr; } virtual void onFail(wspp::connection_hdl hdl) { CCAPI_LOGGER_FUNCTION_ENTER; @@ -922,6 +1021,7 @@ class Service : public std::enable_shared_from_this { message.setType(Message::Type::SESSION_CONNECTION_DOWN); Element element; element.insert(CCAPI_CONNECTION_ID, wsConnection.id); + element.insert(CCAPI_CONNECTION_URL, wsConnection.url); element.insert(CCAPI_REASON, reason); message.setElementList({element}); std::vector correlationIdList; @@ -962,9 +1062,10 @@ class Service : public std::enable_shared_from_this { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, e); } } else if (opcode == websocketpp::frame::opcode::binary) { -#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || \ - defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_OKEX)) || \ - defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && (defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) +#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && \ + (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \ + defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \ + (defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_BITMART)) if (this->needDecompressWebsocketMessage) { std::string decompressed; const std::string& payload = msg->get_payload(); @@ -1031,89 +1132,597 @@ class Service : public std::enable_shared_from_this { this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).find(method) != this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) { this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); } - this->pingTimerByMethodByConnectionIdMap[wsConnection.id][method] = this->serviceContextPtr->tlsClientPtr->set_timer( - pingIntervalMilliSeconds - pongTimeoutMilliSeconds, - [wsConnection, that = shared_from_this(), hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { - if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { + TimerPtr timerPtr( + new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds))); + timerPtr->async_wait([wsConnection, that = shared_from_this(), hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", ping timer error: " + ec.message()); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + if (that->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN) { + ErrorCode ec; + pingMethod(hdl, ec); if (ec) { - CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", ping timer error: " + ec.message()); - that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); - } else { - if (that->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN) { - ErrorCode ec; - pingMethod(hdl, ec); - if (ec) { - that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping"); - } - if (pongTimeoutMilliSeconds <= 0) { - return; - } - if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() && - that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).find(method) != - that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) { - that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); - } - that->pongTimeOutTimerByMethodByConnectionIdMap[wsConnection.id][method] = that->serviceContextPtr->tlsClientPtr->set_timer( - pongTimeoutMilliSeconds, [wsConnection, that, hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { - if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { - if (ec) { - CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", pong time out timer error: " + ec.message()); - that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); - } else { - if (that->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN) { - auto now = UtilTime::now(); - if (that->lastPongTpByMethodByConnectionIdMap.find(wsConnection.id) != that->lastPongTpByMethodByConnectionIdMap.end() && - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) != - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() && - std::chrono::duration_cast( - now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method)) - .count() >= pongTimeoutMilliSeconds) { - auto thisWsConnection = wsConnection; - ErrorCode ec; - that->close(thisWsConnection, hdl, websocketpp::close::status::normal, "pong timeout", ec); - if (ec) { - that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); - } - that->shouldProcessRemainingMessageOnClosingByConnectionIdMap[thisWsConnection.id] = true; - } else { - auto thisWsConnection = wsConnection; - that->setPingPongTimer(method, thisWsConnection, hdl, pingMethod); - } - } - } - } - }); - } + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping"); } + if (pongTimeoutMilliSeconds <= 0) { + return; + } + if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() && + that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).find(method) != + that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) { + that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); + } + TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds))); + timerPtr->async_wait([wsConnection, that, hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", pong time out timer error: " + ec.message()); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + if (that->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN) { + auto now = UtilTime::now(); + if (that->lastPongTpByMethodByConnectionIdMap.find(wsConnection.id) != that->lastPongTpByMethodByConnectionIdMap.end() && + that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) != + that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() && + std::chrono::duration_cast(now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method)) + .count() >= pongTimeoutMilliSeconds) { + auto thisWsConnection = wsConnection; + ErrorCode ec; + that->close(thisWsConnection, hdl, websocketpp::close::status::normal, "pong timeout", ec); + if (ec) { + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); + } + that->shouldProcessRemainingMessageOnClosingByConnectionIdMap[thisWsConnection.id] = true; + } else { + auto thisWsConnection = wsConnection; + that->setPingPongTimer(method, thisWsConnection, hdl, pingMethod); + } + } + } + } + }); + that->pongTimeOutTimerByMethodByConnectionIdMap[wsConnection.id][method] = timerPtr; } - }); + } + } + }); + this->pingTimerByMethodByConnectionIdMap[wsConnection.id][method] = timerPtr; } CCAPI_LOGGER_FUNCTION_EXIT; } - http::verb convertHttpMethodStringToMethod(const std::string& methodString) { - std::string methodStringUpper = UtilString::toUpper(methodString); - return http::string_to_verb(methodStringUpper); - } virtual void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) {} + +#else + + void close(std::shared_ptr wsConnectionPtr, beast::websocket::close_code const code, beast::websocket::close_reason reason, ErrorCode& ec) { + WsConnection& wsConnection = *wsConnectionPtr; + if (wsConnection.status == WsConnection::Status::CLOSING) { + CCAPI_LOGGER_WARN("websocket connection is already in the state of closing"); + return; + } + wsConnection.status = WsConnection::Status::CLOSING; + wsConnection.remoteCloseCode = code; + wsConnection.remoteCloseReason = reason; + wsConnectionPtr->streamPtr->async_close(code, beast::bind_front_handler(&Service::onClose, shared_from_this(), wsConnectionPtr)); + } + virtual void prepareConnect(std::shared_ptr wsConnectionPtr) { this->connect(wsConnectionPtr); } + virtual void connect(std::shared_ptr wsConnectionPtr) { + CCAPI_LOGGER_FUNCTION_ENTER; + WsConnection& wsConnection = *wsConnectionPtr; + wsConnection.status = WsConnection::Status::CONNECTING; + CCAPI_LOGGER_DEBUG("connection initialization on id " + wsConnection.id); + std::string url = wsConnection.url; + CCAPI_LOGGER_DEBUG("url = " + url); + this->startConnectWs(wsConnectionPtr, this->sessionOptions.websocketConnectTimeoutMilliSeconds, this->tcpResolverResultsWs); + CCAPI_LOGGER_FUNCTION_EXIT; + } + void startConnectWs(std::shared_ptr wsConnectionPtr, long timeoutMilliSeconds, tcp::resolver::results_type tcpResolverResults) { + beast::websocket::stream>& stream = *wsConnectionPtr->streamPtr; + if (timeoutMilliSeconds > 0) { + beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliSeconds)); + } + CCAPI_LOGGER_TRACE("before async_connect"); + beast::get_lowest_layer(stream).async_connect(tcpResolverResults, beast::bind_front_handler(&Service::onConnectWs, shared_from_this(), wsConnectionPtr)); + CCAPI_LOGGER_TRACE("after async_connect"); + } + void onConnectWs(std::shared_ptr wsConnectionPtr, beast::error_code ec, tcp::resolver::results_type::endpoint_type ep) { + CCAPI_LOGGER_TRACE("async_connect callback start"); + if (ec) { + CCAPI_LOGGER_TRACE("fail"); + this->onFail(wsConnectionPtr); + return; + } + CCAPI_LOGGER_TRACE("connected"); + CCAPI_LOGGER_TRACE("ep.port() = " + std::to_string(ep.port())); + wsConnectionPtr->hostHttpHeaderValue = this->hostWs + ':' + std::to_string(ep.port()); + beast::websocket::stream>& stream = *wsConnectionPtr->streamPtr; + beast::get_lowest_layer(stream).socket().set_option(tcp::no_delay(true)); + CCAPI_LOGGER_TRACE("before ssl async_handshake"); + stream.next_layer().async_handshake(ssl::stream_base::client, beast::bind_front_handler(&Service::onSslHandshakeWs, shared_from_this(), wsConnectionPtr)); + CCAPI_LOGGER_TRACE("after ssl async_handshake"); + } + void onSslHandshakeWs(std::shared_ptr wsConnectionPtr, beast::error_code ec) { + CCAPI_LOGGER_TRACE("ssl async_handshake callback start"); + if (ec) { + CCAPI_LOGGER_TRACE("fail"); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "ssl handshake", wsConnectionPtr->correlationIdList); + return; + } + CCAPI_LOGGER_TRACE("ssl handshaked"); + beast::websocket::stream>& stream = *wsConnectionPtr->streamPtr; + beast::get_lowest_layer(stream).expires_never(); + beast::websocket::stream_base::timeout opt{std::chrono::milliseconds(this->sessionOptions.websocketConnectTimeoutMilliSeconds), + std::chrono::milliseconds(this->sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds), true}; + + stream.set_option(opt); + stream.set_option(beast::websocket::stream_base::decorator([wsConnectionPtr](beast::websocket::request_type& req) { + req.set(http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING)); + for (const auto& kv : wsConnectionPtr->headers) { + req.set(kv.first, kv.second); + } + })); + CCAPI_LOGGER_TRACE("before ws async_handshake"); + stream.async_handshake(wsConnectionPtr->hostHttpHeaderValue, wsConnectionPtr->path, + beast::bind_front_handler(&Service::onWsHandshakeWs, shared_from_this(), wsConnectionPtr)); + CCAPI_LOGGER_TRACE("after ws async_handshake"); + } + void onWsHandshakeWs(std::shared_ptr wsConnectionPtr, beast::error_code ec) { + CCAPI_LOGGER_TRACE("ws async_handshake callback start"); + if (ec) { + CCAPI_LOGGER_TRACE("fail"); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "ws handshake", wsConnectionPtr->correlationIdList); + return; + } + CCAPI_LOGGER_TRACE("ws handshaked"); + this->onOpen(wsConnectionPtr); + this->wsConnectionByIdMap.insert(std::make_pair(wsConnectionPtr->id, wsConnectionPtr)); + CCAPI_LOGGER_TRACE("about to start read"); + this->startReadWs(wsConnectionPtr); + auto& stream = *wsConnectionPtr->streamPtr; + stream.control_callback(beast::bind_front_handler(&Service::onControlCallback, shared_from_this(), wsConnectionPtr)); + } + void startReadWs(std::shared_ptr wsConnectionPtr) { + auto& stream = *wsConnectionPtr->streamPtr; + CCAPI_LOGGER_TRACE("before async_read"); + auto& connectionId = wsConnectionPtr->id; + auto& readMessageBuffer = this->readMessageBufferByConnectionIdMap[connectionId]; + stream.async_read(readMessageBuffer, beast::bind_front_handler(&Service::onReadWs, shared_from_this(), wsConnectionPtr)); + CCAPI_LOGGER_TRACE("after async_read"); + } + void onReadWs(std::shared_ptr wsConnectionPtr, const boost::system::error_code& ec, std::size_t n) { + CCAPI_LOGGER_FUNCTION_ENTER; + CCAPI_LOGGER_TRACE("n = " + toString(n)); + auto now = UtilTime::now(); + if (ec) { + if (ec == beast::error::timeout) { + CCAPI_LOGGER_TRACE("timeout, connection closed"); + } else { + CCAPI_LOGGER_TRACE("fail"); + Event event; + event.setType(Event::Type::SESSION_STATUS); + Message message; + message.setTimeReceived(now); + message.setType(Message::Type::SESSION_CONNECTION_DOWN); + message.setCorrelationIdList(wsConnectionPtr->correlationIdList); + Element element(true); + auto& connectionId = wsConnectionPtr->id; + element.insert(CCAPI_CONNECTION_ID, connectionId); + message.setElementList({element}); + event.setMessageList({message}); + this->eventHandler(event, nullptr); + this->onFail(wsConnectionPtr); + } + return; + } + if (wsConnectionPtr->status != WsConnection::Status::OPEN) { + CCAPI_LOGGER_WARN("should not process remaining message on closing"); + return; + } + auto& connectionId = wsConnectionPtr->id; + auto& readMessageBuffer = this->readMessageBufferByConnectionIdMap[connectionId]; + this->onMessage(wsConnectionPtr, (const char*)readMessageBuffer.data().data(), readMessageBuffer.size()); + readMessageBuffer.consume(readMessageBuffer.size()); + this->startReadWs(wsConnectionPtr); + this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now); + CCAPI_LOGGER_FUNCTION_EXIT; + } + virtual void onOpen(std::shared_ptr wsConnectionPtr) { + CCAPI_LOGGER_FUNCTION_ENTER; + auto now = UtilTime::now(); + WsConnection& wsConnection = *wsConnectionPtr; + wsConnection.status = WsConnection::Status::OPEN; + CCAPI_LOGGER_INFO("connection " + toString(wsConnection) + " established"); + auto urlBase = UtilString::split(wsConnection.url, "?").at(0); + this->connectNumRetryOnFailByConnectionUrlMap[urlBase] = 0; + Event event; + event.setType(Event::Type::SESSION_STATUS); + Message message; + message.setTimeReceived(now); + message.setType(Message::Type::SESSION_CONNECTION_UP); + std::vector correlationIdList = wsConnection.correlationIdList; + CCAPI_LOGGER_DEBUG("correlationIdList = " + toString(correlationIdList)); + message.setCorrelationIdList(correlationIdList); + Element element; + element.insert(CCAPI_CONNECTION_ID, wsConnection.id); + element.insert(CCAPI_CONNECTION_URL, wsConnection.url); + message.setElementList({element}); + event.setMessageList({message}); + this->eventHandler(event, nullptr); + if (this->enableCheckPingPongWebsocketProtocolLevel) { + this->setPingPongTimer(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, + [wsConnectionPtr, that = shared_from_this()](ErrorCode& ec) { that->ping(wsConnectionPtr, "", ec); }); + } + if (this->enableCheckPingPongWebsocketApplicationLevel) { + this->setPingPongTimer(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, + [wsConnectionPtr, that = shared_from_this()](ErrorCode& ec) { that->pingOnApplicationLevel(wsConnectionPtr, ec); }); + } + } + void writeMessage(std::shared_ptr wsConnectionPtr, const char* data, size_t dataSize) { + if (wsConnectionPtr->status != WsConnection::Status::OPEN) { + CCAPI_LOGGER_WARN("should write no more messages"); + return; + } + auto& connectionId = wsConnectionPtr->id; + auto& writeMessageBuffer = this->writeMessageBufferByConnectionIdMap[connectionId]; + auto& writeMessageBufferWrittenLength = this->writeMessageBufferWrittenLengthByConnectionIdMap[connectionId]; + auto& writeMessageBufferBoundary = this->writeMessageBufferBoundaryByConnectionIdMap[connectionId]; + size_t n = writeMessageBufferWrittenLength; + memcpy(writeMessageBuffer.data() + n, data, dataSize); + writeMessageBufferBoundary.push_back(dataSize); + n += dataSize; + CCAPI_LOGGER_DEBUG("about to send " + std::string(data, dataSize)); + CCAPI_LOGGER_TRACE("writeMessageBufferWrittenLength = " + toString(writeMessageBufferWrittenLength)); + if (writeMessageBufferWrittenLength == 0) { + CCAPI_LOGGER_TRACE("about to start write"); + this->startWriteWs(wsConnectionPtr, writeMessageBuffer.data(), writeMessageBufferBoundary.front()); + } + writeMessageBufferWrittenLength = n; + CCAPI_LOGGER_TRACE("writeMessageBufferWrittenLength = " + toString(writeMessageBufferWrittenLength)); + CCAPI_LOGGER_TRACE("writeMessageBufferBoundary = " + toString(writeMessageBufferBoundary)); + } + void startWriteWs(std::shared_ptr wsConnectionPtr, const char* data, size_t numBytesToWrite) { + auto& stream = *wsConnectionPtr->streamPtr; + CCAPI_LOGGER_TRACE("before async_write"); + CCAPI_LOGGER_TRACE("numBytesToWrite = " + toString(numBytesToWrite)); + stream.binary(false); + stream.async_write(boost::asio::buffer(data, numBytesToWrite), beast::bind_front_handler(&Service::onWriteWs, shared_from_this(), wsConnectionPtr)); + CCAPI_LOGGER_TRACE("after async_write"); + } + void onWriteWs(std::shared_ptr wsConnectionPtr, const boost::system::error_code& ec, std::size_t n) { + CCAPI_LOGGER_FUNCTION_ENTER; + auto& connectionId = wsConnectionPtr->id; + auto& writeMessageBuffer = this->writeMessageBufferByConnectionIdMap[connectionId]; + auto& writeMessageBufferWrittenLength = this->writeMessageBufferWrittenLengthByConnectionIdMap[connectionId]; + auto& writeMessageBufferBoundary = this->writeMessageBufferBoundaryByConnectionIdMap[connectionId]; + writeMessageBufferWrittenLength -= writeMessageBufferBoundary.front(); + writeMessageBufferBoundary.erase(writeMessageBufferBoundary.begin()); + CCAPI_LOGGER_TRACE("writeMessageBufferWrittenLength = " + toString(writeMessageBufferWrittenLength)); + CCAPI_LOGGER_TRACE("writeMessageBufferBoundary = " + toString(writeMessageBufferBoundary)); + if (writeMessageBufferWrittenLength > 0) { + std::memmove(writeMessageBuffer.data(), writeMessageBuffer.data() + n, writeMessageBufferWrittenLength); + CCAPI_LOGGER_TRACE("about to start write"); + this->startWriteWs(wsConnectionPtr, writeMessageBuffer.data(), writeMessageBufferBoundary.front()); + } + CCAPI_LOGGER_FUNCTION_EXIT; + } + virtual void onFail_(std::shared_ptr wsConnectionPtr) { + WsConnection& wsConnection = *wsConnectionPtr; + wsConnection.status = WsConnection::Status::FAILED; + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "connection " + toString(wsConnection) + " has failed before opening"); + WsConnection thisWsConnection = wsConnection; + this->wsConnectionByIdMap.erase(thisWsConnection.id); + auto urlBase = UtilString::split(thisWsConnection.url, "?").at(0); + long seconds = std::round(UtilAlgorithm::exponentialBackoff(1, 1, 2, std::min(this->connectNumRetryOnFailByConnectionUrlMap[urlBase], 6))); + CCAPI_LOGGER_INFO("about to set timer for " + toString(seconds) + " seconds"); + if (this->connectRetryOnFailTimerByConnectionIdMap.find(thisWsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) { + this->connectRetryOnFailTimerByConnectionIdMap.at(thisWsConnection.id)->cancel(); + } + TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000))); + timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), urlBase](ErrorCode const& ec) { + WsConnection& thisWsConnection = *wsConnectionPtr; + if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("wsConnection = " + toString(thisWsConnection) + ", connect retry on fail timer error: " + ec.message()); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + CCAPI_LOGGER_INFO("about to retry"); + try { + auto thatWsConnectionPtr = that->createWsConnectionPtr(wsConnectionPtr); + that->prepareConnect(thatWsConnectionPtr); + that->connectNumRetryOnFailByConnectionUrlMap[urlBase] += 1; + } catch (const beast::error_code& ec) { + CCAPI_LOGGER_TRACE("fail"); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", wsConnectionPtr->correlationIdList); + return; + } + } + } + }); + this->connectRetryOnFailTimerByConnectionIdMap[thisWsConnection.id] = timerPtr; + } + std::shared_ptr createWsConnectionPtr(std::shared_ptr wsConnectionPtr) { + std::shared_ptr thatWsConnectionPtr = wsConnectionPtr; + std::shared_ptr>> streamPtr(nullptr); + try { + streamPtr = this->createStream>>(this->serviceContextPtr->ioContextPtr, + this->serviceContextPtr->sslContextPtr, this->hostWs); + } catch (const beast::error_code& ec) { + throw ec; + } + thatWsConnectionPtr->streamPtr = streamPtr; + return thatWsConnectionPtr; + } + virtual void onFail(std::shared_ptr wsConnectionPtr) { + CCAPI_LOGGER_FUNCTION_ENTER; + this->clearStates(wsConnectionPtr); + this->onFail_(wsConnectionPtr); + CCAPI_LOGGER_FUNCTION_EXIT; + } + virtual void clearStates(std::shared_ptr wsConnectionPtr) { + WsConnection& wsConnection = *wsConnectionPtr; + CCAPI_LOGGER_INFO("clear states for wsConnection " + toString(wsConnection)); + this->shouldProcessRemainingMessageOnClosingByConnectionIdMap.erase(wsConnection.id); + this->lastPongTpByMethodByConnectionIdMap.erase(wsConnection.id); + this->extraPropertyByConnectionIdMap.erase(wsConnection.id); + if (this->pingTimerByMethodByConnectionIdMap.find(wsConnection.id) != this->pingTimerByMethodByConnectionIdMap.end()) { + for (const auto& x : this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id)) { + x.second->cancel(); + } + this->pingTimerByMethodByConnectionIdMap.erase(wsConnection.id); + } + if (this->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != this->pongTimeOutTimerByMethodByConnectionIdMap.end()) { + for (const auto& x : this->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id)) { + x.second->cancel(); + } + this->pongTimeOutTimerByMethodByConnectionIdMap.erase(wsConnection.id); + } + // auto urlBase = UtilString::split(wsConnection.url, "?").at(0); + // this->connectNumRetryOnFailByConnectionUrlMap.erase(urlBase); + if (this->connectRetryOnFailTimerByConnectionIdMap.find(wsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) { + this->connectRetryOnFailTimerByConnectionIdMap.at(wsConnection.id)->cancel(); + this->connectRetryOnFailTimerByConnectionIdMap.erase(wsConnection.id); + } + this->readMessageBufferByConnectionIdMap.erase(wsConnection.id); + this->writeMessageBufferByConnectionIdMap.erase(wsConnection.id); + this->writeMessageBufferWrittenLengthByConnectionIdMap.erase(wsConnection.id); + } + virtual void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) { + CCAPI_LOGGER_FUNCTION_ENTER; + auto now = UtilTime::now(); + WsConnection& wsConnection = *wsConnectionPtr; + wsConnection.status = WsConnection::Status::CLOSED; + CCAPI_LOGGER_INFO("connection " + toString(wsConnection) + " is closed"); + std::stringstream s; + s << "close code: " << wsConnectionPtr->remoteCloseCode << " (" << std::to_string(wsConnectionPtr->remoteCloseCode) + << "), close reason: " << wsConnectionPtr->remoteCloseReason.reason; + std::string reason = s.str(); + CCAPI_LOGGER_INFO("reason is " + reason); + Event event; + event.setType(Event::Type::SESSION_STATUS); + Message message; + message.setTimeReceived(now); + message.setType(Message::Type::SESSION_CONNECTION_DOWN); + Element element; + element.insert(CCAPI_CONNECTION_ID, wsConnection.id); + element.insert(CCAPI_CONNECTION_URL, wsConnection.url); + element.insert(CCAPI_REASON, reason); + message.setElementList({element}); + std::vector correlationIdList; + for (const auto& subscription : wsConnection.subscriptionList) { + correlationIdList.push_back(subscription.getCorrelationId()); + } + CCAPI_LOGGER_DEBUG("correlationIdList = " + toString(correlationIdList)); + message.setCorrelationIdList(correlationIdList); + event.setMessageList({message}); + this->eventHandler(event, nullptr); + CCAPI_LOGGER_INFO("connection " + toString(wsConnection) + " is closed"); + this->clearStates(wsConnectionPtr); + auto thisWsConnectionPtr = this->createWsConnectionPtr(wsConnectionPtr); + this->wsConnectionByIdMap.erase(wsConnectionPtr->id); + if (this->shouldContinue.load()) { + this->prepareConnect(thisWsConnectionPtr); + } + CCAPI_LOGGER_FUNCTION_EXIT; + } + void onMessage(std::shared_ptr wsConnectionPtr, const char* data, size_t dataSize) { + auto now = UtilTime::now(); + WsConnection& wsConnection = *wsConnectionPtr; + CCAPI_LOGGER_DEBUG("received a message from connection " + toString(wsConnection)); + if (wsConnection.status != WsConnection::Status::OPEN && !this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id]) { + CCAPI_LOGGER_WARN("should not process remaining message on closing"); + return; + } + auto& stream = *wsConnectionPtr->streamPtr; + if (stream.got_text()) { + boost::beast::string_view textMessage(data, dataSize); + CCAPI_LOGGER_DEBUG(std::string("received a text message: ") + std::string(textMessage)); + try { + this->onTextMessage(wsConnectionPtr, textMessage, now); + } catch (const std::exception& e) { + CCAPI_LOGGER_ERROR(std::string("textMessage = ") + std::string(textMessage)); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, e); + } + } else if (stream.got_binary()) { + CCAPI_LOGGER_DEBUG(std::string("received a binary message: ") + UtilAlgorithm::stringToHex(std::string(data, dataSize))); +#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && \ + (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \ + defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \ + (defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_BITMART)) + if (this->needDecompressWebsocketMessage) { + std::string decompressed; + boost::beast::string_view payload(data, dataSize); + try { + ErrorCode ec = this->inflater.decompress(reinterpret_cast(&payload[0]), payload.size(), decompressed); + if (ec) { + CCAPI_LOGGER_FATAL(ec.message()); + } + CCAPI_LOGGER_DEBUG("decompressed = " + decompressed); + this->onTextMessage(wsConnectionPtr, decompressed, now); + } catch (const std::exception& e) { + std::stringstream ss; + ss << std::hex << std::setfill('0'); + for (int i = 0; i < payload.size(); ++i) { + ss << std::setw(2) << static_cast(reinterpret_cast(&payload[0])[i]); + } + CCAPI_LOGGER_ERROR("binaryMessage = " + ss.str()); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, e); + } + ErrorCode ec = this->inflater.inflate_reset(); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "decompress"); + } + } +#endif + } + } + void onControlCallback(std::shared_ptr wsConnectionPtr, boost::beast::websocket::frame_type kind, boost::beast::string_view payload) { + if (kind == boost::beast::websocket::frame_type::ping) { + this->onPing(wsConnectionPtr, payload); + } else if (kind == boost::beast::websocket::frame_type::pong) { + this->onPong(wsConnectionPtr, payload); + } else if (kind == boost::beast::websocket::frame_type::close) { + this->onClose(wsConnectionPtr, ErrorCode()); + } + } + void onPong(std::shared_ptr wsConnectionPtr, boost::beast::string_view payload) { + auto now = UtilTime::now(); + this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now); + } + void onPongByMethod(PingPongMethod method, std::shared_ptr wsConnectionPtr, const TimePoint& timeReceived) { + CCAPI_LOGGER_FUNCTION_ENTER; + CCAPI_LOGGER_TRACE(pingPongMethodToString(method) + ": received a pong from " + toString(*wsConnectionPtr)); + this->lastPongTpByMethodByConnectionIdMap[wsConnectionPtr->id][method] = timeReceived; + CCAPI_LOGGER_FUNCTION_EXIT; + } + void onPing(std::shared_ptr wsConnectionPtr, boost::beast::string_view payload) { + CCAPI_LOGGER_FUNCTION_ENTER; + CCAPI_LOGGER_TRACE("received a ping from " + toString(*wsConnectionPtr)); + CCAPI_LOGGER_FUNCTION_EXIT; + } + void send(std::shared_ptr wsConnectionPtr, boost::beast::string_view payload, ErrorCode& ec) { + this->writeMessage(wsConnectionPtr, payload.data(), payload.length()); + } + void ping(std::shared_ptr wsConnectionPtr, boost::beast::string_view payload, ErrorCode& ec) { + if (!this->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id]) { + auto& stream = *wsConnectionPtr->streamPtr; + stream.async_ping("", [that = this, wsConnectionPtr](ErrorCode const& ec) { that->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id] = false; }); + this->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id] = true; + } + } + virtual void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) {} + void setPingPongTimer(PingPongMethod method, std::shared_ptr wsConnectionPtr, std::function pingMethod) { + CCAPI_LOGGER_FUNCTION_ENTER; + CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method)); + auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method]; + auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method]; + CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds)); + CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds)); + if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) { + return; + } + WsConnection& wsConnection = *wsConnectionPtr; + if (wsConnection.status == WsConnection::Status::OPEN) { + if (this->pingTimerByMethodByConnectionIdMap.find(wsConnection.id) != this->pingTimerByMethodByConnectionIdMap.end() && + this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).find(method) != this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) { + this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); + } + TimerPtr timerPtr( + new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds))); + timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + WsConnection& wsConnection = *wsConnectionPtr; + if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", ping timer error: " + ec.message()); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + if (that->wsConnectionByIdMap.at(wsConnection.id)->status == WsConnection::Status::OPEN) { + ErrorCode ec; + pingMethod(ec); + if (ec) { + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping"); + } + if (pongTimeoutMilliSeconds <= 0) { + return; + } + if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() && + that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).find(method) != + that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) { + that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); + } + TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds))); + timerPtr->async_wait([wsConnectionPtr, that, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + WsConnection& wsConnection = *wsConnectionPtr; + if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", pong time out timer error: " + ec.message()); + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + if (that->wsConnectionByIdMap.at(wsConnection.id)->status == WsConnection::Status::OPEN) { + auto now = UtilTime::now(); + if (that->lastPongTpByMethodByConnectionIdMap.find(wsConnection.id) != that->lastPongTpByMethodByConnectionIdMap.end() && + that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) != + that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() && + std::chrono::duration_cast(now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method)) + .count() >= pongTimeoutMilliSeconds) { + auto thisWsConnectionPtr = wsConnectionPtr; + ErrorCode ec; + that->close(thisWsConnectionPtr, beast::websocket::close_code::normal, + beast::websocket::close_reason(beast::websocket::close_code::normal, "pong timeout"), ec); + if (ec) { + that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); + } + that->shouldProcessRemainingMessageOnClosingByConnectionIdMap[thisWsConnectionPtr->id] = true; + } else { + auto thisWsConnectionPtr = wsConnectionPtr; + that->setPingPongTimer(method, thisWsConnectionPtr, pingMethod); + } + } + } + } + }); + that->pongTimeOutTimerByMethodByConnectionIdMap[wsConnection.id][method] = timerPtr; + } + } + } + }); + this->pingTimerByMethodByConnectionIdMap[wsConnection.id][method] = timerPtr; + } + CCAPI_LOGGER_FUNCTION_EXIT; + } + virtual void onTextMessage(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived) {} +#endif std::string apiKeyName; std::string apiSecretName; std::string exchangeName; - std::string baseUrl; + std::string baseUrlWs; std::string baseUrlRest; std::function* eventQueue)> eventHandler; SessionOptions sessionOptions; SessionConfigs sessionConfigs; ServiceContextPtr serviceContextPtr; - tcp::resolver resolver; + tcp::resolver resolver, resolverWs; std::string hostRest; std::string portRest; - tcp::resolver::results_type tcpResolverResultsRest; + std::string hostWs; + std::string portWs; + tcp::resolver::results_type tcpResolverResultsRest, tcpResolverResultsWs; Queue> httpConnectionPool; TimePoint lastHttpConnectionPoolPushBackTp{std::chrono::seconds{0}}; TimerPtr httpConnectionPoolPurgeTimer; std::map credentialDefault; std::map sendRequestDelayTimerByCorrelationIdMap; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET std::map wsConnectionByIdMap; +#else + std::map> wsConnectionByIdMap; // TODO(cryptochassis): for consistency, to be renamed to wsConnectionPtrByIdMap + std::map readMessageBufferByConnectionIdMap; + std::map> writeMessageBufferByConnectionIdMap; + std::map writeMessageBufferWrittenLengthByConnectionIdMap; + std::map> writeMessageBufferBoundaryByConnectionIdMap; +#endif + std::map wsConnectionPendingPingingByIdMap; std::map shouldProcessRemainingMessageOnClosingByConnectionIdMap; std::map connectNumRetryOnFailByConnectionUrlMap; std::map connectRetryOnFailTimerByConnectionIdMap; @@ -1130,11 +1739,16 @@ class Service : public std::enable_shared_from_this { // std::regex convertNumberToStringInJsonRegex{"(\\[|,|\":)\\s?(-?\\d+\\.?\\d*)"}; // std::string convertNumberToStringInJsonRewrite{"$1\"$2\""}; bool needDecompressWebsocketMessage{}; -#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || \ - defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_OKEX)) || \ - defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && (defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) +#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && \ + (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \ + defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \ + (defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_BITMART)) +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET struct monostate {}; websocketpp::extensions_workaround::permessage_deflate::enabled inflater; +#else + InflateStream inflater; +#endif #endif }; } /* namespace ccapi */ diff --git a/linux/include/ccapi_cpp/service/ccapi_service_context.h b/linux/include/ccapi_cpp/service/ccapi_service_context.h index 37ccd6f5a..60618c6f2 100644 --- a/linux/include/ccapi_cpp/service/ccapi_service_context.h +++ b/linux/include/ccapi_cpp/service/ccapi_service_context.h @@ -1,5 +1,6 @@ #ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_ #define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_ +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET #include "ccapi_cpp/ccapi_logger.h" #include "websocketpp/client.hpp" #include "websocketpp/common/connection_hdl.hpp" @@ -23,7 +24,7 @@ class ServiceContext CCAPI_FINAL { }; #endif #ifdef CCAPI_WEBSOCKET_READ_BUFFER_SIZE -static const size_t connection_read_buffer_size = CCAPI_WEBSOCKET_READ_BUFFER_SIZE; + static const size_t connection_read_buffer_size = CCAPI_WEBSOCKET_READ_BUFFER_SIZE; #endif static const wspp::log::level alog_level = wspp::log::alevel::none; static const wspp::log::level elog_level = wspp::log::elevel::none; @@ -63,9 +64,52 @@ static const size_t connection_read_buffer_size = CCAPI_WEBSOCKET_READ_BUFFER_SI } IoContextPtr ioContextPtr{new IoContext()}; TlsClientPtr tlsClientPtr{new TlsClient()}; - SslContextPtr sslContextPtr{new SslContext(SslContext::sslv23)}; + SslContextPtr sslContextPtr{new SslContext(SslContext::tls_client)}; +}; + +} /* namespace ccapi */ +#else +#include "ccapi_cpp/ccapi_logger.h" +namespace ccapi { +/** + * Defines the service that the service depends on. + */ +class ServiceContext CCAPI_FINAL { + public: + typedef boost::asio::io_context IoContext; + typedef std::shared_ptr IoContextPtr; + typedef boost::asio::executor_work_guard ExecutorWorkGuard; + typedef std::shared_ptr ExecutorWorkGuardPtr; + typedef boost::asio::ssl::context SslContext; + typedef std::shared_ptr SslContextPtr; + ServiceContext() { + // this->sslContextPtr->set_options(SslContext::default_workarounds | SslContext::no_sslv2 | SslContext::no_sslv3 | SslContext::single_dh_use); + this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none); + // TODO(cryptochassis): verify ssl certificate to strengthen security + // https://github.com/boostorg/asio/blob/develop/example/cpp03/ssl/client.cpp + } + ServiceContext(const ServiceContext&) = delete; + ServiceContext& operator=(const ServiceContext&) = delete; + virtual ~ServiceContext() { + // delete this->ExecutorWorkGuardPtr; + // delete this->ioContextPtr; + // delete this->sslContextPtr; + } + void start() { + CCAPI_LOGGER_INFO("about to start client asio io_context run loop"); + this->ioContextPtr->run(); + CCAPI_LOGGER_INFO("just exited client asio io_context run loop"); + } + void stop() { + this->executorWorkGuardPtr->reset(); + this->ioContextPtr->stop(); + } + IoContextPtr ioContextPtr{new IoContext()}; + ExecutorWorkGuardPtr executorWorkGuardPtr{new ExecutorWorkGuard(ioContextPtr->get_executor())}; + SslContextPtr sslContextPtr{new SslContext(SslContext::tls_client)}; }; } /* namespace ccapi */ +#endif #endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_