diff --git a/linux/include/ccapi_cpp/ccapi_message.h b/linux/include/ccapi_cpp/ccapi_message.h index da6270d5c..4fb3c26dc 100644 --- a/linux/include/ccapi_cpp/ccapi_message.h +++ b/linux/include/ccapi_cpp/ccapi_message.h @@ -16,8 +16,10 @@ class Message CCAPI_FINAL { public: enum class RecapType { UNKNOWN, - 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. + SOLICITED, // A recap. For market depth, it represents the initial order book snapshot. For public trade, it represents the most recent historical trades. + // This is the first batch of data points. + NONE, // Normal data tick, not a recap. For market depth, it represents the updated order book state. For public trade, it represents the new trades. These + // are the batches of data points after the first batch. }; static std::string recapTypeToString(RecapType recapType) { std::string output; diff --git a/linux/include/ccapi_cpp/ccapi_ws_connection.h b/linux/include/ccapi_cpp/ccapi_ws_connection.h index cde6d64f1..dddc6c8af 100644 --- a/linux/include/ccapi_cpp/ccapi_ws_connection.h +++ b/linux/include/ccapi_cpp/ccapi_ws_connection.h @@ -94,16 +94,27 @@ class WsConnection CCAPI_FINAL { 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('?'); + auto foundSlash = splitted1.at(1).find_first_of('/'); + auto foundQuestionMark = splitted1.at(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); + this->path = "/" + splitted1.at(1).substr(foundQuestionMark); } else if (foundSlash != std::string::npos && foundQuestionMark == std::string::npos) { - this->path = splitted1[1].substr(foundSlash); + this->path = splitted1.at(1).substr(foundSlash); } else { - this->path = splitted1[1].substr(foundSlash); + this->path = splitted1.at(1).substr(foundSlash); + } + auto splitted2 = UtilString::split(UtilString::split(splitted1.at(1), "/").at(0), ":"); + this->host = splitted2.at(0); + if (splitted2.size() == 2) { + this->port = splitted2.at(1); + } else { + if (splitted1.at(0) == "https" || splitted1.at(0) == "wss") { + this->port = CCAPI_HTTPS_PORT_DEFAULT; + } else { + this->port = CCAPI_HTTP_PORT_DEFAULT; + } } } WsConnection() {} @@ -166,6 +177,8 @@ class WsConnection CCAPI_FINAL { beast::websocket::close_reason remoteCloseReason; std::string hostHttpHeaderValue; std::string path; + std::string host; + std::string port; }; } /* namespace ccapi */ #endif 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 0e5544d98..0b1a9a908 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h @@ -194,7 +194,11 @@ class ExecutionManagementService : public Service { for (const auto& sendString : sendStringList) { CCAPI_LOGGER_INFO("sendString = " + sendString); 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"); } @@ -271,7 +275,7 @@ class ExecutionManagementService : public Service { this->wsRequestIdByConnectionIdMap.erase(wsConnection.id); Service::onClose(wsConnectionPtr, ec); } - virtual void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessage, + virtual void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, const TimePoint& timeReceived) {} #endif void convertRequestForRestGenericPrivateRequest(http::request& req, const Request& request, const TimePoint& now, 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 661ac8a74..f72728474 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 @@ -43,12 +43,17 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService { private: #endif + bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } 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 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); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } + void onOpen(std::shared_ptr wsConnectionPtr) override { wsConnectionPtr->status = WsConnection::Status::OPEN; } +#endif 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,18 +355,31 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService { void subscribe(std::vector& subscriptionList) override { 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); - auto credential = subscription.getCredential(); - if (credential.empty()) { - credential = that->credentialDefault; + 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; + } + const auto& accountGroup = mapGetWithDefault(credential, that->apiAccountGroupName); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + WsConnection wsConnection(that->baseUrlWs + "/" + accountGroup + "/api/pro/v1/stream", "", {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; } - const auto& accountGroup = mapGetWithDefault(credential, that->apiAccountGroupName); - WsConnection wsConnection(that->baseUrlWs + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription}, credential); - that->prepareConnect(wsConnection); - }); + std::shared_ptr wsConnectionPtr(new WsConnection(that->baseUrlWs + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription}, credential, streamPtr)); + CCAPI_LOGGER_WARN("about to subscribe with new wsConnectionPtr " + toString(*wsConnectionPtr)); + that->prepareConnect(wsConnectionPtr); +#endif + }); } } } @@ -387,6 +405,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET 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); @@ -397,8 +416,26 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService { this->eventHandler(event, nullptr); } } +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; Message message; @@ -485,14 +522,26 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService { document.Accept(writerSubscribe); std::string sendString = stringBufferSubscribe.GetString(); ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, sendString, ec); +#endif +#else + this->send(wsConnectionPtr, sendString, ec); +#endif if (ec) { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); } } else if (m == "connected") { std::string type = document["type"].GetString(); if (type == "unauth") { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET ExecutionManagementService::onOpen(hdl); +#else + ExecutionManagementService::onOpen(wsConnectionPtr); +#endif } } } 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 7e88c4686..18849d208 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 @@ -17,6 +17,265 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService #ifndef CCAPI_EXPOSE_INTERNAL protected: +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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; + 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; + } + 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->baseUrlWs + "/" + 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); + message.setCorrelationIdList({wsConnection.subscriptionList.at(0).getCorrelationId()}); + event.setMessageList({message}); + this->eventHandler(event, nullptr); + 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; + } + 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 (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { + 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); + } +#else + void prepareConnect(std::shared_ptr wsConnectionPtr) 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; + const auto& marginType = wsConnectionPtr->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 = wsConnectionPtr->subscriptionList.at(0).getInstrument(); + target += "?" + symbol; + } + req.target(target); + auto credential = wsConnectionPtr->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, + [wsConnectionPtr, that = shared_from_base()](const beast::error_code& ec) { that->onFail_(wsConnectionPtr); }, + [wsConnectionPtr, that = shared_from_base()](const http::response& res) { + 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; + wsConnectionPtr->url = url; + that->connect(wsConnectionPtr); + that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({ + {"listenKey", listenKey}, + }); + return; + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); + } + } + that->onFail_(wsConnectionPtr); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); + } + void onOpen(std::shared_ptr wsConnectionPtr) override { + ExecutionManagementService::onOpen(wsConnectionPtr); + auto now = UtilTime::now(); + Event event; + event.setType(Event::Type::SUBSCRIPTION_STATUS); + Message message; + message.setTimeReceived(now); + message.setType(Message::Type::SUBSCRIPTION_STARTED); + message.setCorrelationIdList({wsConnectionPtr->subscriptionList.at(0).getCorrelationId()}); + event.setMessageList({message}); + this->eventHandler(event, nullptr); + this->setPingListenKeyTimer(wsConnectionPtr); + } + void setPingListenKeyTimer(const std::shared_ptr wsConnectionPtr) { + TimerPtr timerPtr( + new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(this->pingListenKeyIntervalSeconds * 1000))); + timerPtr->async_wait([wsConnectionPtr, that = shared_from_base()](ErrorCode const& ec) { + if (ec) { + return; + } + that->setPingListenKeyTimer(wsConnectionPtr); + 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 = wsConnectionPtr->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(wsConnectionPtr->id).at("listenKey"); + params.insert({"listenKey", listenKey}); + if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { + auto symbol = wsConnectionPtr->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 = wsConnectionPtr->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, + [wsConnectionPtr, 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"); + }, + [wsConnectionPtr, that_2 = that->shared_from_base()](const http::response& res) { + CCAPI_LOGGER_DEBUG("ping listen key success"); + }, + that->sessionOptions.httpRequestTimeoutMilliSeconds); + }); + this->pingListenKeyTimerMapByConnectionIdMap[wsConnectionPtr->id] = timerPtr; + } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + if (this->pingListenKeyTimerMapByConnectionIdMap.find(wsConnectionPtr->id) != this->pingListenKeyTimerMapByConnectionIdMap.end()) { + this->pingListenKeyTimerMapByConnectionIdMap.at(wsConnectionPtr->id)->cancel(); + this->pingListenKeyTimerMapByConnectionIdMap.erase(wsConnectionPtr->id); + } + ExecutionManagementService::onClose(wsConnectionPtr, ec); + } #endif 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, @@ -267,146 +526,37 @@ class ExecutionManagementServiceBinanceBase : 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; - 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; - } - 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->baseUrlWs + "/" + 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(); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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)); - Event event; - event.setType(Event::Type::SUBSCRIPTION_STATUS); - 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); - 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; - } - 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 (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) { - 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 TimePoint& timeReceived) override { + auto subscription = wsConnection.subscriptionList.at(0); rj::Document document; document.Parse(textMessage.c_str()); - Event event = this->createEvent(subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, 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) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; const auto& fieldSet = subscription.getFieldSet(); 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 f2299fe25..9ce4b452a 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 @@ -42,10 +42,17 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService { private: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { auto now = UtilTime::now(); this->send(hdl, "{\"cid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + auto now = UtilTime::now(); + this->send(wsConnectionPtr, "{\"cid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", ec); + } +#endif 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 { @@ -353,121 +360,142 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, - const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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(subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, 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; - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - const auto& fieldSet = subscription.getFieldSet(); - const auto& instrumentSet = subscription.getInstrumentSet(); - if (document.IsArray() && document.Size() >= 3 && std::string(document[0].GetString()) == "0") { - std::string type = document[1].GetString(); - if ((type == CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE) && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { - event.setType(Event::Type::SUBSCRIPTION_DATA); - const rj::Value& data = document[2]; - std::string instrument = data[1].GetString(); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(data[2].GetString()))); - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); - std::vector elementList; - Element element; - if (type == "tu") { - element.insert(CCAPI_TRADE_ID, data[2].GetString()); - } - std::string amount = data[4].GetString(); - if (amount.at(0) == '-') { - amount.erase(0, 1); - element.insert(CCAPI_EM_ORDER_SIDE, CCAPI_EM_ORDER_SIDE_SELL); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, amount); - } else { - element.insert(CCAPI_EM_ORDER_SIDE, CCAPI_EM_ORDER_SIDE_BUY); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, amount); - } - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data[5].GetString()); - element.insert(CCAPI_IS_MAKER, std::string(data[8].GetString()).at(0) != '-' ? "1" : "0"); - element.insert(CCAPI_EM_ORDER_INSTRUMENT, data[1].GetString()); - element.insert(CCAPI_EM_ORDER_ID, data[3].GetString()); - element.insert(CCAPI_EM_CLIENT_ORDER_ID, data[11].GetString()); - if (type == "tu") { - std::string fee = data[9].GetString(); - if (fee.at(0) == '-') { - fee.erase(0, 1); - } else { - fee.insert(0, 1, '-'); - } - element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, fee); - element.insert(CCAPI_EM_ORDER_FEE_ASSET, data[10].GetString()); - } - elementList.emplace_back(std::move(element)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived){ +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif + 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.IsArray() && document.Size() >= 3 && std::string(document[0].GetString()) == "0") { + std::string type = document[1].GetString(); + if ((type == CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE) && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + event.setType(Event::Type::SUBSCRIPTION_DATA); + const rj::Value& data = document[2]; + std::string instrument = data[1].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(data[2].GetString()))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); + std::vector elementList; + Element element; + if (type == "tu") { + element.insert(CCAPI_TRADE_ID, data[2].GetString()); } - } else if ((type == "on" || type == "ou" || type == "oc") && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { - event.setType(Event::Type::SUBSCRIPTION_DATA); - const rj::Value& data = document[2]; - std::string instrument = data[3].GetString(); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(data[5].GetString()))); - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); - Element info; - this->extractOrderInfo(info, data); - std::vector elementList; - elementList.emplace_back(std::move(info)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } - } else if (type == "n") { - event.setType(Event::Type::RESPONSE); - const rj::Value& data = document[2]; - std::string status = data[6].GetString(); - if (status != "SUCCESS") { - message.setType(Message::Type::RESPONSE_ERROR); - Element element; - element.insert(CCAPI_ERROR_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); + std::string amount = data[4].GetString(); + if (amount.at(0) == '-') { + amount.erase(0, 1); + element.insert(CCAPI_EM_ORDER_SIDE, CCAPI_EM_ORDER_SIDE_SELL); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, amount); } else { - std::vector elementList; - std::string notificationType = data[1].GetString(); - if (notificationType == "on-req") { - message.setType(Message::Type::CREATE_ORDER); - } else if (notificationType == "oc-req") { - message.setType(Message::Type::CANCEL_ORDER); + element.insert(CCAPI_EM_ORDER_SIDE, CCAPI_EM_ORDER_SIDE_BUY); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, amount); + } + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data[5].GetString()); + element.insert(CCAPI_IS_MAKER, std::string(data[8].GetString()).at(0) != '-' ? "1" : "0"); + element.insert(CCAPI_EM_ORDER_INSTRUMENT, data[1].GetString()); + element.insert(CCAPI_EM_ORDER_ID, data[3].GetString()); + element.insert(CCAPI_EM_CLIENT_ORDER_ID, data[11].GetString()); + if (type == "tu") { + std::string fee = data[9].GetString(); + if (fee.at(0) == '-') { + fee.erase(0, 1); + } else { + fee.insert(0, 1, '-'); } - this->extractOrderInfoFromRequestForWebsocket(elementList, data[4]); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); + element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, fee); + element.insert(CCAPI_EM_ORDER_FEE_ASSET, data[10].GetString()); } + elementList.emplace_back(std::move(element)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); } - } else if (document.IsObject()) { - auto it = document.FindMember("event"); - if (it != document.MemberEnd()) { - std::string eventStr = it->value.GetString(); - if (eventStr == "auth") { - std::string status = document["status"].GetString(); - event.setType(Event::Type::SUBSCRIPTION_STATUS); - message.setType(status == "OK" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); - Element element; - element.insert(status == "OK" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); - message.setElementList({element}); - messageList.emplace_back(std::move(message)); + } else if ((type == "on" || type == "ou" || type == "oc") && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { + event.setType(Event::Type::SUBSCRIPTION_DATA); + const rj::Value& data = document[2]; + std::string instrument = data[3].GetString(); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(data[5].GetString()))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); + Element info; + this->extractOrderInfo(info, data); + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } else if (type == "n") { + event.setType(Event::Type::RESPONSE); + const rj::Value& data = document[2]; + std::string status = data[6].GetString(); + if (status != "SUCCESS") { + message.setType(Message::Type::RESPONSE_ERROR); + Element element; + element.insert(CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); + } else { + std::vector elementList; + std::string notificationType = data[1].GetString(); + if (notificationType == "on-req") { + message.setType(Message::Type::CREATE_ORDER); + } else if (notificationType == "oc-req") { + message.setType(Message::Type::CANCEL_ORDER); } + this->extractOrderInfoFromRequestForWebsocket(elementList, data[4]); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); + } + } + } else if (document.IsObject()) { + auto it = document.FindMember("event"); + if (it != document.MemberEnd()) { + std::string eventStr = it->value.GetString(); + if (eventStr == "auth") { + std::string status = document["status"].GetString(); + event.setType(Event::Type::SUBSCRIPTION_STATUS); + message.setType(status == "OK" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE); + Element element; + element.insert(status == "OK" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage); + message.setElementList({element}); + messageList.emplace_back(std::move(message)); } } - event.setMessageList(messageList); - return event; } -}; + event.setMessageList(messageList); + return event; +} +}; // namespace ccapi } /* namespace ccapi */ #endif #endif 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 index 279d2c5bc..bd759f369 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h @@ -254,145 +254,157 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget sendStringList.push_back(sendString); return sendStringList; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + const TimePoint& timeReceived) override{ +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, 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") { + WsConnection& wsConnection = *wsConnectionPtr; + 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) { - 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}); + 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(); - 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()) { + 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; +#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); + } + } +} +} // namespace ccapi +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["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); + message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); std::vector elementList; - elementList.emplace_back(std::move(info)); + 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; + } 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 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 index 5f4838f1f..5afaa00e8 100644 --- 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 @@ -14,7 +14,11 @@ class ExecutionManagementServiceBitgetBase : public ExecutionManagementService { protected: #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); } +#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*\"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, 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 index 324648947..cb525c728 100644 --- 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 @@ -309,8 +309,14 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic sendStringList.push_back(sendString); return sendStringList; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); +#endif if (textMessage != "pong") { rj::Document document; document.Parse(textMessage.c_str()); @@ -343,20 +349,34 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic 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); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event event = this->createEvent(wsConnection, wsConnection.hdl, subscription, textMessage, document, eventStr, timeReceived); +#else + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, eventStr, timeReceived); +#endif 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) { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const std::string& eventStr, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const std::string& eventStr, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; Message message; 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 index a3b887bf6..495115e9e 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h @@ -52,7 +52,11 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService { 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); } +#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*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, @@ -297,8 +301,15 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + WsConnection& wsConnection = *wsConnectionPtr; + std::string textMessage(textMessageView); +#endif if (textMessage != "pong") { rj::Document document; document.Parse(textMessage.c_str()); @@ -327,7 +338,11 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService { 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"); } 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 a6614cca1..0b2081bed 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 @@ -311,144 +311,165 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService { 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()); - Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived); - if (!event.getMessageList().empty()) { - this->eventHandler(event, nullptr); - } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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(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()}); - const auto& fieldSet = subscription.getFieldSet(); - const auto& instrumentSet = subscription.getInstrumentSet(); - if (document.FindMember("error") != document.MemberEnd()) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived){ +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif + 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.FindMember("error") != document.MemberEnd()) { + auto it = document.FindMember("request"); + if (it != document.MemberEnd()) { + if (std::string(it->value["op"].GetString()) == "authKeyExpires") { + 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 (document.FindMember("success") != document.MemberEnd()) { auto it = document.FindMember("request"); if (it != document.MemberEnd()) { if (std::string(it->value["op"].GetString()) == "authKeyExpires") { event.setType(Event::Type::SUBSCRIPTION_STATUS); - message.setType(Message::Type::SUBSCRIPTION_FAILURE); + message.setType(Message::Type::SUBSCRIPTION_STARTED); Element element; - element.insert(CCAPI_ERROR_MESSAGE, textMessage); + element.insert(CCAPI_INFO_MESSAGE, textMessage); message.setElementList({element}); messageList.emplace_back(std::move(message)); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("subscribe").Move(), allocator); + rj::Value args(rj::kArrayType); + if (instrumentSet.empty()) { + for (const auto& field : fieldSet) { + if (field == CCAPI_EM_ORDER_UPDATE) { + args.PushBack(rj::Value("order").Move(), allocator); + } else if (field == CCAPI_EM_PRIVATE_TRADE) { + args.PushBack(rj::Value("execution").Move(), allocator); + } + } + } else { + for (const auto& instrument : instrumentSet) { + for (const auto& field : fieldSet) { + std::string arg; + if (field == CCAPI_EM_ORDER_UPDATE) { + arg = std::string("order:") + instrument; + } else if (field == CCAPI_EM_PRIVATE_TRADE) { + arg = std::string("execution:") + instrument; + } + args.PushBack(rj::Value(arg.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; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + this->send(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 { - if (document.FindMember("success") != document.MemberEnd()) { - auto it = document.FindMember("request"); - if (it != document.MemberEnd()) { - if (std::string(it->value["op"].GetString()) == "authKeyExpires") { - 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)); - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); - document.AddMember("op", rj::Value("subscribe").Move(), allocator); - rj::Value args(rj::kArrayType); - if (instrumentSet.empty()) { - for (const auto& field : fieldSet) { - if (field == CCAPI_EM_ORDER_UPDATE) { - args.PushBack(rj::Value("order").Move(), allocator); - } else if (field == CCAPI_EM_PRIVATE_TRADE) { - args.PushBack(rj::Value("execution").Move(), allocator); - } - } - } else { - for (const auto& instrument : instrumentSet) { - for (const auto& field : fieldSet) { - std::string arg; - if (field == CCAPI_EM_ORDER_UPDATE) { - arg = std::string("order:") + instrument; - } else if (field == CCAPI_EM_PRIVATE_TRADE) { - arg = std::string("execution:") + instrument; - } - args.PushBack(rj::Value(arg.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 { - auto it = document.FindMember("table"); - if (it != document.MemberEnd()) { - std::string table = it->value.GetString(); - event.setType(Event::Type::SUBSCRIPTION_DATA); - auto it_2 = document.FindMember("action"); - if (it_2 != document.MemberEnd()) { - std::string action = it_2->value.GetString(); - if (action == "insert") { - for (const auto& x : document["data"].GetArray()) { - std::string instrument = std::string(x["symbol"].GetString()); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - message.setTime(UtilTime::parse(std::string(x["timestamp"].GetString()))); - if (table == "execution" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { - std::string execType = x["execType"].GetString(); - if (execType == "Trade") { - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); - std::vector elementList; - Element element; - element.insert(CCAPI_TRADE_ID, std::string(x["trdMatchID"].GetString())); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["lastPx"].GetString())); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["lastQty"].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()) == "RemovedLiquidity" ? "0" : "1"); - element.insert(CCAPI_EM_ORDER_ID, std::string(x["orderID"].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["commission"].GetString())); - elementList.emplace_back(std::move(element)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } - } else if (table == "order" && 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("orderID", 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("price", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("leavesQty", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumQty", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_STATUS, std::make_pair("ordStatus", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, - }; - Element info; - this->extractOrderInfo(info, x, extractionFieldNameMap); - auto it = x.FindMember("avgPx"); - if (it != x.MemberEnd() && !it->value.IsNull()) { - info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, - std::to_string(std::stod(it->value.GetString()) * std::stod(x["cumQty"].GetString()))); - } + auto it = document.FindMember("table"); + if (it != document.MemberEnd()) { + std::string table = it->value.GetString(); + event.setType(Event::Type::SUBSCRIPTION_DATA); + auto it_2 = document.FindMember("action"); + if (it_2 != document.MemberEnd()) { + std::string action = it_2->value.GetString(); + if (action == "insert") { + for (const auto& x : document["data"].GetArray()) { + std::string instrument = std::string(x["symbol"].GetString()); + if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { + message.setTime(UtilTime::parse(std::string(x["timestamp"].GetString()))); + if (table == "execution" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { + std::string execType = x["execType"].GetString(); + if (execType == "Trade") { + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); std::vector elementList; - elementList.emplace_back(std::move(info)); + Element element; + element.insert(CCAPI_TRADE_ID, std::string(x["trdMatchID"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["lastPx"].GetString())); + element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["lastQty"].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()) == "RemovedLiquidity" ? "0" : "1"); + element.insert(CCAPI_EM_ORDER_ID, std::string(x["orderID"].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["commission"].GetString())); + elementList.emplace_back(std::move(element)); message.setElementList(elementList); messageList.emplace_back(std::move(message)); } + } else if (table == "order" && 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("orderID", 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("price", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("leavesQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumQty", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_STATUS, std::make_pair("ordStatus", JsonDataType::STRING)}, + {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, + }; + Element info; + this->extractOrderInfo(info, x, extractionFieldNameMap); + auto it = x.FindMember("avgPx"); + if (it != x.MemberEnd() && !it->value.IsNull()) { + info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, + std::to_string(std::stod(it->value.GetString()) * std::stod(x["cumQty"].GetString()))); + } + std::vector elementList; + elementList.emplace_back(std::move(info)); + message.setElementList(elementList); + messageList.emplace_back(std::move(message)); } } } @@ -456,10 +477,11 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService { } } } - event.setMessageList(messageList); - return event; } -}; + event.setMessageList(messageList); + return event; +} +}; // namespace ccapi } /* namespace ccapi */ #endif #endif 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 14fd36058..7f1628568 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 @@ -44,9 +44,15 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService { protected: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + this->send(wsConnectionPtr, R"({"event": "bts:heartbeat"})", ec); + } +#endif 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; @@ -268,6 +274,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService { CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void prepareConnect(WsConnection& wsConnection) override { auto now = UtilTime::now(); auto hostPort = this->extractHostFromUrl(this->baseUrlRest); @@ -324,6 +331,59 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService { }, this->sessionOptions.httpRequestTimeoutMilliSeconds); } +#else + void prepareConnect(std::shared_ptr wsConnectionPtr) 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); + std::string target = this->getWebSocketsTokenTarget; + req.target(target); + auto credential = wsConnectionPtr->subscriptionList.at(0).getCredential(); + if (credential.empty()) { + credential = this->credentialDefault; + } + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("X-Auth", "BITSTAMP " + apiKey); + std::string nonce = UtilString::generateUuidV4(); + req.set("X-Auth-Nonce", nonce); + req.set("X-Auth-Timestamp", std::to_string(std::chrono::duration_cast(now.time_since_epoch()).count())); + req.set("X-Auth-Version", "v2"); + std::string body; + this->signRequest(req, "", credential); + this->sendRequest( + req, [wsConnectionPtr, that = shared_from_base()](const beast::error_code& ec) { that->onFail_(wsConnectionPtr); }, + [wsConnectionPtr, that = shared_from_base()](const http::response& res) { + int statusCode = res.result_int(); + std::string body = res.body(); + if (statusCode / 100 == 2) { + try { + rj::Document document; + document.Parse(body.c_str()); + if (document.HasMember("token") && document.HasMember("user_id")) { + std::string token = document["token"].GetString(); + std::string userId = document["user_id"].GetString(); + wsConnectionPtr->url = that->baseUrlWs; + that->connect(wsConnectionPtr); + that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({ + {"token", token}, + {"userId", userId}, + }); + } + return; + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); + } + } + that->onFail_(wsConnectionPtr); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); + } +#endif std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, const std::map& credential) override { const auto& fieldSet = subscription.getFieldSet(); @@ -356,16 +416,37 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService { } return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, - const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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(subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, 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) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; Message message; 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 85d8438d0..3b72af2c9 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 @@ -204,129 +204,140 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa 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 == "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())); - } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) override{ +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); +#endif + 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 == "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_CLIENT_ORDER_ID, std::string(x["c"].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())); - } + } + { + 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)); } + 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::STRING)}, + {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)); } } } - } 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; + } 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; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + this->send(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 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; +} +}; // namespace ccapi } /* namespace ccapi */ #endif #endif 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 index b51c8a8c3..ce6b69686 100644 --- 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 @@ -15,7 +15,11 @@ class ExecutionManagementServiceBybitBase : public ExecutionManagementService { protected: #endif bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } +#endif 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 { @@ -98,19 +102,37 @@ class ExecutionManagementServiceBybitBase : public ExecutionManagementService { 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 { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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); + Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); } } + virtual Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { + return {}; + } +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } + virtual Event createEvent(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + return {}; + } +#endif }; } /* namespace ccapi */ #endif 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 index 603be4e3b..36ad753e8 100644 --- 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 @@ -238,141 +238,151 @@ class ExecutionManagementServiceBybitDerivatives : public ExecutionManagementSer 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()) { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) override{ +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); +#endif + 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["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); + message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["execTime"].GetString())))); + message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); std::vector elementList; - elementList.emplace_back(std::move(info)); + 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 (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; + } 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; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + this->send(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 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 } /* namespace ccapi */ #endif #endif 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 827e34df9..ea05d2f84 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 @@ -293,26 +293,37 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } - 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 + 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(subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, 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) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; Message message; 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 8410f7222..54caa0c33 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 @@ -331,17 +331,37 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService { sendStringList.push_back(body); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, - const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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, subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); } } - Event createEvent(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, - const TimePoint& timeReceived) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; Message message; @@ -466,7 +486,11 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService { std::string id = document["id"].GetString(); std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})"; ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, msg, ec); +#endif if (ec) { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); } @@ -527,7 +551,11 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService { document.Accept(writer); std::string sendString = stringBuffer.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"); } 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 70be1f325..682b793a4 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 @@ -45,6 +45,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { protected: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void onOpen(wspp::connection_hdl hdl) override { ExecutionManagementService::onOpen(hdl); WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); @@ -66,6 +67,39 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); } } + void onClose(wspp::connection_hdl hdl) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->subscriptionJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id); + this->authorizationJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id); + ExecutionManagementService::onClose(hdl); + } +#else + void onOpen(std::shared_ptr wsConnectionPtr) override { + ExecutionManagementService::onOpen(wsConnectionPtr); + 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/set_heartbeat", + { + {"interval", "10"}, + }); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string msg = stringBuffer.GetString(); + ErrorCode ec; + this->send(wsConnectionPtr, msg, ec); + if (ec) { + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); + } + } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + this->subscriptionJsonrpcIdSetByConnectionIdMap.erase(wsConnectionPtr->id); + this->authorizationJsonrpcIdSetByConnectionIdMap.erase(wsConnectionPtr->id); + ExecutionManagementService::onClose(wsConnectionPtr, ec); + } +#endif void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& httpMethodString, std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, const std::map& credential) override { @@ -322,17 +356,38 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, - const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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, subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); } } - Event createEvent(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, - const TimePoint& timeReceived) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); + const WsConnection& wsConnection = *wsConnectionPtr; +#endif Event event; std::vector messageList; Message message; @@ -393,7 +448,11 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { document.Accept(writer); std::string sendString = stringBuffer.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"); } @@ -495,7 +554,11 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { document.Accept(writer); std::string msg = stringBuffer.GetString(); ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, msg, ec); +#endif if (ec) { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); } @@ -506,12 +569,6 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService { 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->subscriptionJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id); - this->authorizationJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id); - ExecutionManagementService::onClose(hdl); - } std::map> subscriptionJsonrpcIdSetByConnectionIdMap; std::map> authorizationJsonrpcIdSetByConnectionIdMap; std::string restTarget; 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 361097a53..0087cf212 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 @@ -22,7 +22,11 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService { protected: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } +#endif 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 { @@ -318,8 +322,13 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService { } return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + WsConnection& wsConnection = *wsConnectionPtr; + std::string textMessage(textMessageView); +#endif rj::Document document; document.Parse(textMessage.c_str()); Event event = this->createEvent(subscription, textMessage, document, timeReceived); 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 c794f5cb3..0b5f866c8 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,12 +14,21 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService { protected: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET 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); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + auto now = UtilTime::now(); + this->send(wsConnectionPtr, + "{\"time\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"channel\":\"" + (this->isDerivatives ? "futures" : "spot") + ".ping\"}", + ec); + } +#endif 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 { @@ -343,16 +352,37 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService { } return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, - const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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(subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, 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) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; Message message; 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 09a799947..319d68cef 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 @@ -87,28 +87,42 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem 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); - const auto& instrumentSet = subscription.getInstrumentSet(); - auto it = instrumentSet.begin(); - if (it != instrumentSet.end()) { - std::string settle; - std::string symbolId = *it; - if (UtilString::endsWith(symbolId, "_USD")) { - settle = "btc"; - } else if (UtilString::endsWith(symbolId, "_USDT")) { - settle = "usdt"; - } - auto credential = subscription.getCredential(); - if (credential.empty()) { - credential = that->credentialDefault; - } - WsConnection wsConnection(that->baseUrlWs + settle, "", {subscription}, credential); - that->prepareConnect(wsConnection); + boost::asio::post(*this->serviceContextPtr->ioContextPtr, + [that = shared_from_base(), subscription]() mutable { + auto now = UtilTime::now(); + subscription.setTimeSent(now); + const auto& instrumentSet = subscription.getInstrumentSet(); + auto it = instrumentSet.begin(); + if (it != instrumentSet.end()) { + std::string settle; + std::string symbolId = *it; + if (UtilString::endsWith(symbolId, "_USD")) { + settle = "btc"; + } else if (UtilString::endsWith(symbolId, "_USDT")) { + settle = "usdt"; + } + auto credential = subscription.getCredential(); + if (credential.empty()) { + credential = that->credentialDefault; + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + WsConnection wsConnection(that->baseUrlWs + settle, "", {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 + settle, "", {subscription}, credential, streamPtr)); + CCAPI_LOGGER_WARN("about to subscribe with new wsConnectionPtr " + toString(*wsConnectionPtr)); + that->prepareConnect(wsConnectionPtr); +#endif + } + }); } } CCAPI_LOGGER_FUNCTION_EXIT; 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 6fff3bfb8..8ccc343bc 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 @@ -273,6 +273,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService { } } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void prepareConnect(WsConnection& wsConnection) override { auto now = UtilTime::now(); auto subscription = wsConnection.subscriptionList.at(0); @@ -303,16 +304,69 @@ 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 TimePoint& timeReceived) override { +#else + void prepareConnect(std::shared_ptr wsConnectionPtr) override { + auto now = UtilTime::now(); + auto subscription = wsConnectionPtr->subscriptionList.at(0); + const auto& fieldSet = subscription.getFieldSet(); + const auto& instrumentSet = subscription.getInstrumentSet(); + auto credential = wsConnectionPtr->subscriptionList.at(0).getCredential(); + if (credential.empty()) { + credential = this->credentialDefault; + } + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + wsConnectionPtr->url += "?heartbeat=true"; + if (fieldSet == std::set({CCAPI_EM_PRIVATE_TRADE})) { + wsConnectionPtr->url += "&eventTypeFilter=fill"; + } + if (!instrumentSet.empty()) { + for (const auto& instrument : instrumentSet) { + wsConnectionPtr->url += "&symbolFilter=" + instrument; + } + } + wsConnectionPtr->url += "&apiSessionFilter=" + apiKey; + wsConnectionPtr->headers.insert({"X-GEMINI-APIKEY", apiKey}); + int64_t nonce = std::chrono::duration_cast(now.time_since_epoch()).count(); + std::string payload = R"({"request":"/v1/order/events","nonce":)" + std::to_string(nonce) + "}"; + auto base64Payload = UtilAlgorithm::base64Encode(payload); + wsConnectionPtr->headers.insert({"X-GEMINI-PAYLOAD", base64Payload}); + auto apiSecret = mapGetWithDefault(credential, this->apiSecretName); + auto signature = Hmac::hmac(Hmac::ShaVersion::SHA384, apiSecret, base64Payload, true); + wsConnectionPtr->headers.insert({"X-GEMINI-SIGNATURE", signature}); + this->connect(wsConnectionPtr); + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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(subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, 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) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; if (document.IsObject()) { 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 932a5b16c..8a318ba31 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 @@ -265,8 +265,15 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa sendStringList.push_back(sendString); return sendStringList; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + WsConnection& wsConnection = *wsConnectionPtr; + std::string textMessage(textMessageView); +#endif rj::Document document; document.Parse(textMessage.c_str()); std::string actionStr = document["action"].GetString(); @@ -301,7 +308,11 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa 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"); } @@ -319,7 +330,11 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa std::string toReplace("ping"); sendString.replace(sendString.find(toReplace), toReplace.length(), "pong"); 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, "pong"); } 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 ef411a994..742dcb7db 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 @@ -13,7 +13,12 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen this->isDerivatives = true; // this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)\\s?(-?\\d+\\.?\\d*[eE]?-?\\d*)"); 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()); } @@ -239,8 +244,15 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen sendStringList.push_back(sendString); return sendStringList; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const TimePoint& timeReceived) override { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + WsConnection& wsConnection = *wsConnectionPtr; + std::string textMessage(textMessageView); +#endif rj::Document document; document.Parse(textMessage.c_str()); std::string op = document["op"].GetString(); @@ -267,7 +279,11 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen 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"); } @@ -284,7 +300,11 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen std::string toReplace("ping"); sendString.replace(sendString.find(toReplace), toReplace.length(), "pong"); 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, "pong"); } 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 f6d6cc740..4a1b80fd5 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 @@ -46,10 +46,17 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { protected: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { auto now = UtilTime::now(); this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + auto now = UtilTime::now(); + this->send(wsConnectionPtr, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", ec); + } +#endif 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, @@ -264,6 +271,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void prepareConnect(WsConnection& wsConnection) override { auto now = UtilTime::now(); auto hostPort = this->extractHostFromUrl(this->baseUrlRest); @@ -318,6 +326,57 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { }, this->sessionOptions.httpRequestTimeoutMilliSeconds); } +#else + void prepareConnect(std::shared_ptr wsConnectionPtr) 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); + std::string target = this->getWebSocketsTokenTarget; + req.target(target); + auto credential = wsConnectionPtr->subscriptionList.at(0).getCredential(); + if (credential.empty()) { + credential = this->credentialDefault; + } + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + req.set("API-Key", apiKey); + req.set(beast::http::field::content_type, "application/x-www-form-urlencoded; charset=utf-8"); + std::string body; + std::string nonce = std::to_string(this->generateNonce(now)); + this->appendParam(body, {}, nonce); + body.pop_back(); + this->signRequest(req, body, credential, nonce); + this->sendRequest( + req, [wsConnectionPtr, that = shared_from_base()](const beast::error_code& ec) { that->onFail_(wsConnectionPtr); }, + [wsConnectionPtr, that = shared_from_base()](const http::response& res) { + int statusCode = res.result_int(); + std::string body = res.body(); + if (statusCode / 100 == 2) { + try { + rj::Document document; + document.Parse(body.c_str()); + if (document.HasMember("result") && document["result"].HasMember("token")) { + std::string token = document["result"]["token"].GetString(); + wsConnectionPtr->url = that->baseUrlWs; + that->connect(wsConnectionPtr); + that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({ + {"token", token}, + }); + } + return; + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); + } + } + that->onFail_(wsConnectionPtr); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); + } +#endif std::vector createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, const std::map& credential) override { const auto& fieldSet = subscription.getFieldSet(); @@ -345,16 +404,37 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { } return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, - const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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(subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, 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) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; if (document.IsArray() && document.Size() == 3) { 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 9470cec99..efcc226ad 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 @@ -273,17 +273,37 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, - const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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); + Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived); if (!event.getMessageList().empty()) { this->eventHandler(event, nullptr); } } - Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, - const TimePoint& timeReceived) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; if (document.FindMember("event") == document.MemberEnd()) { @@ -400,7 +420,11 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic } for (const auto& sendString : sendStringList) { ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(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"); } 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 87e34935d..bde4a635d 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 @@ -17,14 +17,14 @@ class ExecutionManagementServiceKucoin : public ExecutionManagementServiceKucoin } 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 + // #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; 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 index c41173f11..094ac2ffe 100644 --- 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 @@ -14,11 +14,16 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService { protected: #endif + bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET 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 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 prepareConnect(WsConnection& wsConnection) override { auto now = UtilTime::now(); http::request req; @@ -66,10 +71,56 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService { }, this->sessionOptions.httpRequestTimeoutMilliSeconds); } - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { +#else + void onOpen(std::shared_ptr wsConnectionPtr) override { wsConnectionPtr->status = WsConnection::Status::OPEN; } + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { auto now = UtilTime::now(); - this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec); + this->send(wsConnectionPtr, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", ec); } + void prepareConnect(std::shared_ptr wsConnectionPtr) 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 = wsConnectionPtr->subscriptionList.at(0).getCredential(); + if (credential.empty()) { + credential = this->credentialDefault; + } + this->prepareReq(req, now, credential); + this->signRequest(req, "", credential); + this->sendRequest( + req, + [wsConnectionPtr, that = shared_from_base()](const beast::error_code& ec) { that->onFail_(wsConnectionPtr); }, + [wsConnectionPtr, that = shared_from_base()](const http::response& res) { + 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()); + wsConnectionPtr->url = urlWebsocketBase; + that->connect(wsConnectionPtr); + that->extraPropertyByConnectionIdMap[wsConnectionPtr->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_(wsConnectionPtr); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); + } +#endif 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 { @@ -356,6 +407,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService { sendStringList.push_back(sendString); return sendStringList; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET 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); @@ -366,8 +418,27 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService { this->eventHandler(event, nullptr); } } +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); + const WsConnection& wsConnection = *wsConnectionPtr; +#endif Event event; std::vector messageList; Message message; @@ -457,7 +528,11 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService { this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET ExecutionManagementService::onOpen(hdl); +#else + ExecutionManagementService::onOpen(wsConnectionPtr); +#endif } else if (type == "pong") { auto now = UtilTime::now(); this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now; 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 5f9bde587..571ef4296 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 @@ -17,14 +17,14 @@ 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 + // #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->apiPassphraseName = CCAPI_KUCOIN_FUTURES_API_PASSPHRASE; 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 index ca9199bef..2daad48d5 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h @@ -45,7 +45,13 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService { protected: #endif // bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"PING"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + this->send(wsConnectionPtr, R"({"method":"PING"})", ec); + } +#endif 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 { @@ -220,6 +226,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService { CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void prepareConnect(WsConnection& wsConnection) override { auto now = UtilTime::now(); auto hostPort = this->extractHostFromUrl(this->baseUrlRest); @@ -274,32 +281,6 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService { 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) { @@ -348,16 +329,162 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService { } ExecutionManagementService::onClose(hdl); } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, - const TimePoint& timeReceived) override { +#else + void prepareConnect(std::shared_ptr wsConnectionPtr) 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 = wsConnectionPtr->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, [wsConnectionPtr, that = shared_from_base()](const beast::error_code& ec) { that->onFail_(wsConnectionPtr); }, + [wsConnectionPtr, that = shared_from_base()](const http::response& res) { + 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; + wsConnectionPtr->url = url; + that->connect(wsConnectionPtr); + that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({ + {"listenKey", listenKey}, + }); + return; + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); + } + } + that->onFail_(wsConnectionPtr); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); + } + void onOpen(std::shared_ptr wsConnectionPtr) override { + ExecutionManagementService::onOpen(wsConnectionPtr); + this->setPingListenKeyTimer(wsConnectionPtr); + } + void setPingListenKeyTimer(std::shared_ptr wsConnectionPtr) { + TimerPtr timerPtr( + new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(this->pingListenKeyIntervalSeconds * 1000))); + timerPtr->async_wait([wsConnectionPtr, that = shared_from_base()](ErrorCode const& ec) { + if (ec) { + return; + } + auto now = UtilTime::now(); + that->setPingListenKeyTimer(wsConnectionPtr); + 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(wsConnectionPtr->id).at("listenKey"); + params.insert({"listenKey", listenKey}); + for (const auto& param : params) { + queryString += param.first + "=" + Url::urlEncode(param.second); + queryString += "&"; + } + auto credential = wsConnectionPtr->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, + [wsConnectionPtr, 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"); + }, + [wsConnectionPtr, that_2 = that->shared_from_base()](const http::response& res) { + CCAPI_LOGGER_DEBUG("ping listen key success"); + }, + that->sessionOptions.httpRequestTimeoutMilliSeconds); + }); + this->pingListenKeyTimerMapByConnectionIdMap[wsConnectionPtr->id] = timerPtr; + } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + if (this->pingListenKeyTimerMapByConnectionIdMap.find(wsConnectionPtr->id) != this->pingListenKeyTimerMapByConnectionIdMap.end()) { + this->pingListenKeyTimerMapByConnectionIdMap.at(wsConnectionPtr->id)->cancel(); + this->pingListenKeyTimerMapByConnectionIdMap.erase(wsConnectionPtr->id); + } + ExecutionManagementService::onClose(wsConnectionPtr, ec); + } +#endif + 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; + } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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(subscription, textMessage, document, timeReceived); + Event event = this->createEvent(wsConnection, hdl, 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) { +#else + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } +#endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, + const rj::Document& document, const TimePoint& timeReceived) { +#else + Event createEvent(const std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const rj::Document& document, const TimePoint& timeReceived) { + std::string textMessage(textMessageView); +#endif Event event; std::vector messageList; if (document.IsObject() && document.HasMember("code") && std::string(document["code"].GetString()) == "0") { 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 index 149b6357b..de5f17232 100644 --- 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 @@ -45,7 +45,13 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService private: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"ping"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + this->send(wsConnectionPtr, R"({"method":"ping"})", ec); + } +#endif 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) { @@ -356,8 +362,13 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService // sendStringList.push_back(sendString); return sendStringList; } - void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, const TimePoint& timeReceived) override { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#else + WsConnection& wsConnection = *wsConnectionPtr; + std::string textMessage(textMessageView); +#endif // if (textMessage != "pong") { // rj::Document document; // document.Parse(textMessage.c_str()); @@ -390,7 +401,11 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService // document.Accept(writerSubscribe); // std::string sendString = stringBufferSubscribe.GetString(); // ErrorCode ec; - // this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, 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"); // } diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h index 5c426dece..5eaef313d 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h @@ -411,8 +411,12 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService { document.Accept(writerSubscribe); std::string sendString = stringBufferSubscribe.GetString(); ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, sendString, ec); +#endif #else this->send(wsConnectionPtr, sendString, ec); #endif diff --git a/linux/include/ccapi_cpp/service/ccapi_fix_service.h b/linux/include/ccapi_cpp/service/ccapi_fix_service.h index 9eaaa5f76..3ddbde9fd 100644 --- a/linux/include/ccapi_cpp/service/ccapi_fix_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_fix_service.h @@ -45,7 +45,7 @@ class FixService : public Service { CCAPI_LOGGER_FUNCTION_ENTER; CCAPI_LOGGER_DEBUG("this->baseUrlFix = " + this->baseUrlFix); if (this->shouldContinue.load()) { - wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [that = shared_from_base(), subscription]() { + boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base(), subscription]() { auto now = UtilTime::now(); auto thatSubscription = subscription; thatSubscription.setTimeSent(now); @@ -90,19 +90,20 @@ class FixService : public Service { if (this->connectRetryOnFailTimerByConnectionIdMap.find(fixConnectionPtr->id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) { this->connectRetryOnFailTimerByConnectionIdMap.at(fixConnectionPtr->id)->cancel(); } - this->connectRetryOnFailTimerByConnectionIdMap[fixConnectionPtr->id] = this->serviceContextPtr->tlsClientPtr->set_timer( - seconds * 1000, [fixConnectionPtr, that = shared_from_base(), urlBase](ErrorCode const& ec) { - if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) == that->fixConnectionPtrByIdMap.end()) { - if (ec) { - CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", connect retry on fail timer error: " + ec.message()); - that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); - } else { - CCAPI_LOGGER_INFO("about to retry"); - that->connect(fixConnectionPtr->subscription); - that->connectNumRetryOnFailByConnectionUrlMap[urlBase] += 1; - } - } - }); + TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000))); + timerPtr->async_wait([fixConnectionPtr, that = shared_from_base(), urlBase](ErrorCode const& ec) { + if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) == that->fixConnectionPtrByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", connect retry on fail timer error: " + ec.message()); + that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + CCAPI_LOGGER_INFO("about to retry"); + that->connect(fixConnectionPtr->subscription); + that->connectNumRetryOnFailByConnectionUrlMap[urlBase] += 1; + } + } + }); + this->connectRetryOnFailTimerByConnectionIdMap[fixConnectionPtr->id] = timerPtr; } std::shared_ptr createStreamFix(std::shared_ptr iocPtr, std::shared_ptr ctxPtr, const std::string& host); void connect(Subscription& subscription) { @@ -421,7 +422,7 @@ class FixService : public Service { void sendRequestByFix(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 { + 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)); @@ -469,57 +470,59 @@ class FixService : public Service { this->pingTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).end()) { this->pingTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)->cancel(); } - this->pingTimerByMethodByConnectionIdMap[fixConnectionPtr->id][method] = this->serviceContextPtr->tlsClientPtr->set_timer( - pingIntervalMilliSeconds - pongTimeoutMilliSeconds, - [fixConnectionPtr, that = shared_from_base(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { - if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) != that->fixConnectionPtrByIdMap.end()) { + TimerPtr timerPtr( + new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds))); + timerPtr->async_wait([fixConnectionPtr, that = shared_from_base(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) != that->fixConnectionPtrByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", ping timer error: " + ec.message()); + that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + if (that->fixConnectionPtrByIdMap.at(fixConnectionPtr->id)->status == FixConnection::Status::OPEN) { + ErrorCode ec; + pingMethod(fixConnectionPtr); if (ec) { - CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", ping timer error: " + ec.message()); - that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); - } else { - if (that->fixConnectionPtrByIdMap.at(fixConnectionPtr->id)->status == FixConnection::Status::OPEN) { - ErrorCode ec; - pingMethod(fixConnectionPtr); - if (ec) { - that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "ping"); - } - if (pongTimeoutMilliSeconds <= 0) { - return; - } - if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(fixConnectionPtr->id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() && - that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).find(method) != - that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).end()) { - that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)->cancel(); - } - that->pongTimeOutTimerByMethodByConnectionIdMap[fixConnectionPtr->id][method] = that->serviceContextPtr->tlsClientPtr->set_timer( - pongTimeoutMilliSeconds, [fixConnectionPtr, that, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { - if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) != that->fixConnectionPtrByIdMap.end()) { - if (ec) { - CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", pong timeout timer error: " + ec.message()); - that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); - } else { - if (that->fixConnectionPtrByIdMap.at(fixConnectionPtr->id)->status == FixConnection::Status::OPEN) { - auto now = UtilTime::now(); - if (that->lastPongTpByMethodByConnectionIdMap.find(fixConnectionPtr->id) != that->lastPongTpByMethodByConnectionIdMap.end() && - that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).find(method) != - that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).end() && - std::chrono::duration_cast( - now - that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)) - .count() >= pongTimeoutMilliSeconds) { - auto thisFixConnectionPtr = fixConnectionPtr; - that->onFail(fixConnectionPtr, "pong timeout"); - } else { - auto thisFixConnectionPtr = fixConnectionPtr; - that->setPingPongTimer(method, thisFixConnectionPtr, pingMethod); - } - } - } - } - }); - } + that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "ping"); } + if (pongTimeoutMilliSeconds <= 0) { + return; + } + if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(fixConnectionPtr->id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() && + that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).find(method) != + that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).end()) { + that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)->cancel(); + } + TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds))); + timerPtr->async_wait([fixConnectionPtr, that, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) != that->fixConnectionPtrByIdMap.end()) { + if (ec) { + CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", pong timeout timer error: " + ec.message()); + that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); + } else { + if (that->fixConnectionPtrByIdMap.at(fixConnectionPtr->id)->status == FixConnection::Status::OPEN) { + auto now = UtilTime::now(); + if (that->lastPongTpByMethodByConnectionIdMap.find(fixConnectionPtr->id) != that->lastPongTpByMethodByConnectionIdMap.end() && + that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).find(method) != + that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).end() && + std::chrono::duration_cast(now - + that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)) + .count() >= pongTimeoutMilliSeconds) { + auto thisFixConnectionPtr = fixConnectionPtr; + that->onFail(fixConnectionPtr, "pong timeout"); + } else { + auto thisFixConnectionPtr = fixConnectionPtr; + that->setPingPongTimer(method, thisFixConnectionPtr, pingMethod); + } + } + } + } + }); + that->pongTimeOutTimerByMethodByConnectionIdMap[fixConnectionPtr->id][method] = timerPtr; } - }); + } + } + }); + this->pingTimerByMethodByConnectionIdMap[fixConnectionPtr->id][method] = timerPtr; } CCAPI_LOGGER_FUNCTION_EXIT; } 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 761600108..2ac851eaa 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service.h @@ -409,7 +409,11 @@ class MarketDataService : public Service { for (const auto& sendString : sendStringList) { CCAPI_LOGGER_INFO("sendString = " + sendString); 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"); } @@ -437,7 +441,11 @@ class MarketDataService : public Service { for (const auto& sendString : sendStringList) { CCAPI_LOGGER_INFO("sendString = " + sendString); 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"); } @@ -558,10 +566,10 @@ class MarketDataService : public Service { 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, + virtual void onIncorrectStatesFound(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView, 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) + + std::string errorMessage = "incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + std::string(textMessageView) + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId + ", reason = " + reason; CCAPI_LOGGER_ERROR(errorMessage); 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 d6f6e3bc2..a314dc01b 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 @@ -46,7 +46,11 @@ class MarketDataServiceAscendex : public MarketDataService { } } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } +#endif std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { @@ -73,8 +77,19 @@ class MarketDataServiceAscendex : public MarketDataService { } 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()); std::string m = document["m"].GetString(); @@ -147,7 +162,11 @@ class MarketDataServiceAscendex : public MarketDataService { } } else if (m == "ping") { ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(hdl, R"({ "op": "pong" })", wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, R"({ "op": "pong" })", ec); +#endif if (ec) { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "pong"); } @@ -196,7 +215,11 @@ class MarketDataServiceAscendex : public MarketDataService { std::string sendString = stringBuffer.GetString(); ErrorCode ec; CCAPI_LOGGER_TRACE(sendString); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(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"); } 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 3998c8483..0c23bc435 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 @@ -36,22 +36,8 @@ class MarketDataServiceBitfinex : public MarketDataService { private: #endif - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { - auto now = UtilTime::now(); - 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 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) { - int marketDepthSubscribedToExchange = 1; - marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector({1, 25, 100, 250})); - 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 { return std::vector(); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } void onOpen(wspp::connection_hdl hdl) override { MarketDataService::onOpen(hdl); rj::Document document; @@ -75,8 +61,139 @@ class MarketDataServiceBitfinex : public MarketDataService { this->sequenceByConnectionIdMap.erase(wsConnection.id); MarketDataService::onClose(hdl); } - void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, - std::vector& marketDataMessageList) override { + bool checkSequence(const WsConnection& wsConnection, int sequence) { + if (this->sequenceByConnectionIdMap.find(wsConnection.id) == this->sequenceByConnectionIdMap.end()) { + if (sequence != this->sessionConfigs.getInitialSequenceByExchangeMap().at(this->exchangeName)) { + CCAPI_LOGGER_WARN("incorrect initial sequence, wsConnection = " + toString(wsConnection)); + return false; + } + this->sequenceByConnectionIdMap.insert(std::pair(wsConnection.id, sequence)); + return true; + } else { + if (sequence - this->sequenceByConnectionIdMap[wsConnection.id] == 1) { + this->sequenceByConnectionIdMap[wsConnection.id] = sequence; + return true; + } else { + return false; + } + } + } + void onOutOfSequence(WsConnection& wsConnection, int sequence, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, + const std::string& exchangeSubscriptionId) { + int previous = 0; + if (this->sequenceByConnectionIdMap.find(wsConnection.id) != this->sequenceByConnectionIdMap.end()) { + previous = this->sequenceByConnectionIdMap[wsConnection.id]; + } + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, + "out of sequence: previous = " + toString(previous) + ", current = " + toString(sequence) + ", connection = " + toString(wsConnection) + + ", textMessage = " + textMessage + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived)); + this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId].clear(); + ErrorCode ec; + this->close(wsConnection, hdl, websocketpp::close::status::normal, "out of sequence", ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); + } + this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; + } + void onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, + const std::string& exchangeSubscriptionId, std::string const& reason) override { + CCAPI_LOGGER_ERROR("incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + textMessage + + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", reason = " + reason); + this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId].clear(); + MarketDataService::onIncorrectStatesFound(wsConnection, hdl, textMessage, timeReceived, exchangeSubscriptionId, reason); + } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } + void onOpen(std::shared_ptr wsConnectionPtr) override { + MarketDataService::onOpen(wsConnectionPtr); + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("event", rj::Value("conf").Move(), allocator); + document.AddMember("flags", rj::Value(229376).Move(), allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + ErrorCode ec; + this->send(wsConnectionPtr, sendString, ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe"); + } + } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap.erase(wsConnectionPtr->id); + this->sequenceByConnectionIdMap.erase(wsConnectionPtr->id); + MarketDataService::onClose(wsConnectionPtr, ec); + } + bool checkSequence(std::shared_ptr wsConnectionPtr, int sequence) { + if (this->sequenceByConnectionIdMap.find(wsConnectionPtr->id) == this->sequenceByConnectionIdMap.end()) { + if (sequence != this->sessionConfigs.getInitialSequenceByExchangeMap().at(this->exchangeName)) { + CCAPI_LOGGER_WARN("incorrect initial sequence, wsConnection = " + toString(*wsConnectionPtr)); + return false; + } + this->sequenceByConnectionIdMap.insert(std::pair(wsConnectionPtr->id, sequence)); + return true; + } else { + if (sequence - this->sequenceByConnectionIdMap[wsConnectionPtr->id] == 1) { + this->sequenceByConnectionIdMap[wsConnectionPtr->id] = sequence; + return true; + } else { + return false; + } + } + } + void onOutOfSequence(std::shared_ptr wsConnectionPtr, int sequence, boost::beast::string_view textMessageView, const TimePoint& timeReceived, + const std::string& exchangeSubscriptionId) { + int previous = 0; + if (this->sequenceByConnectionIdMap.find(wsConnectionPtr->id) != this->sequenceByConnectionIdMap.end()) { + previous = this->sequenceByConnectionIdMap[wsConnectionPtr->id]; + } + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, + "out of sequence: previous = " + toString(previous) + ", current = " + toString(sequence) + ", connection = " + toString(*wsConnectionPtr) + + ", textMessage = " + std::string(textMessageView) + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived)); + this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnectionPtr->id][exchangeSubscriptionId].clear(); + ErrorCode ec; + this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason(beast::websocket::close_code::normal, "out of sequence"), + ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); + } + this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false; + } + void onIncorrectStatesFound(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived, + const std::string& exchangeSubscriptionId, std::string const& reason) override { + CCAPI_LOGGER_ERROR("incorrect states found: connection = " + toString(*wsConnectionPtr) + ", textMessage = " + std::string(textMessageView) + + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", reason = " + reason); + this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnectionPtr->id][exchangeSubscriptionId].clear(); + MarketDataService::onIncorrectStatesFound(wsConnectionPtr, textMessageView, timeReceived, exchangeSubscriptionId, reason); + } +#endif + 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) { + int marketDepthSubscribedToExchange = 1; + marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector({1, 25, 100, 250})); + 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 { return std::vector(); } + 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.IsArray() && document.Size() >= 1) { @@ -84,10 +201,17 @@ class MarketDataServiceBitfinex : public MarketDataService { if (document.Size() >= 2 && document[1].IsString() && std::string(document[1].GetString()) == "hb") { if (this->sessionOptions.enableCheckSequence) { int sequence = std::stoi(document[2].GetString()); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET if (!this->checkSequence(wsConnection, sequence)) { this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId); return; } +#else + if (!this->checkSequence(wsConnectionPtr, sequence)) { + this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, exchangeSubscriptionId); + return; + } +#endif } } else { auto channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID); @@ -99,10 +223,17 @@ class MarketDataServiceBitfinex : public MarketDataService { if (document[1].IsArray()) { if (this->sessionOptions.enableCheckSequence) { int sequence = std::stoi(document[2].GetString()); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET if (!this->checkSequence(wsConnection, sequence)) { this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId); return; } +#else + if (!this->checkSequence(wsConnectionPtr, sequence)) { + this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, exchangeSubscriptionId); + return; + } +#endif } const rj::Value& content = document[1].GetArray(); if (content[0].IsArray()) { @@ -195,10 +326,17 @@ class MarketDataServiceBitfinex : public MarketDataService { if (str == "tu" || str == "te") { if (this->sessionOptions.enableCheckSequence) { int sequence = std::stoi(document[3].GetString()); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET if (!this->checkSequence(wsConnection, sequence)) { this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId); return; } +#else + if (!this->checkSequence(wsConnectionPtr, sequence)) { + this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, exchangeSubscriptionId); + return; + } +#endif } if (str == CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE) { const rj::Value& x = document[2].GetArray(); @@ -223,10 +361,17 @@ class MarketDataServiceBitfinex : public MarketDataService { } else if (str == "cs") { if (this->sessionOptions.enableCheckSequence) { int sequence = std::stoi(document[3].GetString()); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET if (!this->checkSequence(wsConnection, sequence)) { this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId); return; } +#else + if (!this->checkSequence(wsConnectionPtr, sequence)) { + this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, exchangeSubscriptionId); + return; + } +#endif } if (this->sessionOptions.enableCheckOrderBookChecksum) { this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] = @@ -285,7 +430,11 @@ class MarketDataServiceBitfinex : public MarketDataService { } for (const auto& sendString : sendStringList) { ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(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"); } @@ -328,40 +477,6 @@ class MarketDataServiceBitfinex : public MarketDataService { } } } - bool checkSequence(const WsConnection& wsConnection, int sequence) { - if (this->sequenceByConnectionIdMap.find(wsConnection.id) == this->sequenceByConnectionIdMap.end()) { - if (sequence != this->sessionConfigs.getInitialSequenceByExchangeMap().at(this->exchangeName)) { - CCAPI_LOGGER_WARN("incorrect initial sequence, wsConnection = " + toString(wsConnection)); - return false; - } - this->sequenceByConnectionIdMap.insert(std::pair(wsConnection.id, sequence)); - return true; - } else { - if (sequence - this->sequenceByConnectionIdMap[wsConnection.id] == 1) { - this->sequenceByConnectionIdMap[wsConnection.id] = sequence; - return true; - } else { - return false; - } - } - } - void onOutOfSequence(WsConnection& wsConnection, int sequence, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, - const std::string& exchangeSubscriptionId) { - int previous = 0; - if (this->sequenceByConnectionIdMap.find(wsConnection.id) != this->sequenceByConnectionIdMap.end()) { - previous = this->sequenceByConnectionIdMap[wsConnection.id]; - } - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, - "out of sequence: previous = " + toString(previous) + ", current = " + toString(sequence) + ", connection = " + toString(wsConnection) + - ", textMessage = " + textMessage + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived)); - this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId].clear(); - ErrorCode ec; - this->close(wsConnection, hdl, websocketpp::close::status::normal, "out of sequence", ec); - if (ec) { - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); - } - this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; - } std::string calculateOrderBookChecksum(const std::map& snapshotBid, const std::map& snapshotAsk) override { auto i = 0; auto i1 = snapshotBid.rbegin(); @@ -384,13 +499,6 @@ class MarketDataServiceBitfinex : public MarketDataService { uint_fast32_t csCalc = UtilAlgorithm::crc(csStr.begin(), csStr.end()); return intToHex(csCalc); } - void onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, - const std::string& exchangeSubscriptionId, std::string const& reason) override { - CCAPI_LOGGER_ERROR("incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + textMessage + - ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", reason = " + reason); - this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId].clear(); - MarketDataService::onIncorrectStatesFound(wsConnection, hdl, textMessage, timeReceived, exchangeSubscriptionId, reason); - } void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& credential) override { switch (request.getOperation()) { 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 index f958f72b9..770b20383 100644 --- 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 @@ -45,7 +45,11 @@ class MarketDataServiceBitgetBase : public MarketDataService { } } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); } +#endif std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; rj::Document document; @@ -102,8 +106,19 @@ class MarketDataServiceBitgetBase : public MarketDataService { 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 { + 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 if (textMessage != "pong") { rj::Document document; document.Parse(textMessage.c_str()); 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 index 3974c3713..1cbb27242 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h @@ -39,11 +39,6 @@ class MarketDataServiceBitmart : public MarketDataService { 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)); @@ -57,7 +52,20 @@ class MarketDataServiceBitmart : public MarketDataService { } } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } + 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); + } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap.erase(wsConnectionPtr->id); + MarketDataService::onClose(wsConnectionPtr, ec); + } +#endif 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; @@ -88,8 +96,19 @@ class MarketDataServiceBitmart : 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 if (textMessage != "pong") { rj::Document document; document.Parse(textMessage.c_str()); 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 5e2534d43..16231ac82 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 @@ -54,7 +54,20 @@ class MarketDataServiceBitmex : public MarketDataService { } } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } + void onClose(wspp::connection_hdl hdl) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->priceByConnectionIdChannelIdSymbolIdPriceIdMap.erase(wsConnection.id); + MarketDataService::onClose(hdl); + } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + this->priceByConnectionIdChannelIdSymbolIdPriceIdMap.erase(wsConnectionPtr->id); + MarketDataService::onClose(wsConnectionPtr, ec); + } +#endif std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; rj::Document document; @@ -83,13 +96,19 @@ class MarketDataServiceBitmex : public MarketDataService { sendStringList.push_back(sendString); return sendStringList; } - void onClose(wspp::connection_hdl hdl) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - this->priceByConnectionIdChannelIdSymbolIdPriceIdMap.erase(wsConnection.id); - MarketDataService::onClose(hdl); - } - 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 if (textMessage != "pong") { rj::Document document; document.Parse(textMessage.c_str()); @@ -168,10 +187,17 @@ class MarketDataServiceBitmex : public MarketDataService { } else { price = this->priceByConnectionIdChannelIdSymbolIdPriceIdMap[wsConnection.id][channelId][symbolId][priceId]; if (price.empty()) { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->onIncorrectStatesFound(wsConnection, hdl, textMessage, timeReceived, exchangeSubscriptionId, "bitmex update for missing item came through on wsConnection = " + toString(wsConnection) + ", channelId = " + channelId + ", symbolId = " + symbolId + ", priceId = " + priceId + ". Data: " + toString(this->priceByConnectionIdChannelIdSymbolIdPriceIdMap[wsConnection.id][channelId][symbolId])); +#else + this->onIncorrectStatesFound(wsConnectionPtr, textMessageView, timeReceived, exchangeSubscriptionId, + "bitmex update for missing item came through on wsConnection = " + toString(wsConnection) + + ", channelId = " + channelId + ", symbolId = " + symbolId + ", priceId = " + priceId + ". Data: " + + toString(this->priceByConnectionIdChannelIdSymbolIdPriceIdMap[wsConnection.id][channelId][symbolId])); +#endif } if (action == "update") { size = UtilString::normalizeDecimalString(x["size"].GetString()); 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 3791479ef..8c583779e 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 @@ -37,9 +37,15 @@ class MarketDataServiceBitstamp : public MarketDataService { private: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + this->send(wsConnectionPtr, R"({"event": "bts:heartbeat"})", ec); + } +#endif bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("status": "error")") != std::string::npos || body.find(R"("status":"error")") != std::string::npos; } @@ -71,8 +77,19 @@ class MarketDataServiceBitstamp : public MarketDataService { } 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()); const rj::Value& data = document["data"]; 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 9e537d6fc..658f29273 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 @@ -82,8 +82,19 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase { 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("op")) { 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 index f1abd7ddc..4982dc109 100644 --- 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 @@ -15,7 +15,11 @@ class MarketDataServiceBybitBase : public MarketDataService { protected: #endif bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } +#endif }; } /* namespace ccapi */ #endif 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 index 9b7461ac9..0f7792f94 100644 --- 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 @@ -110,8 +110,19 @@ class MarketDataServiceBybitDerivatives : public MarketDataServiceBybitBase { 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("op")) { 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 93ed67140..e21c18e75 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 @@ -100,8 +100,19 @@ class MarketDataServiceCryptocom : 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 it = document.FindMember("id"); @@ -208,7 +219,11 @@ class MarketDataServiceCryptocom : public MarketDataService { } else if (method == "public/heartbeat") { std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})"; ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, msg, ec); +#endif 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 1f52592b8..e660f276f 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 @@ -37,6 +37,7 @@ class MarketDataServiceDeribit : public MarketDataService { private: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void onOpen(wspp::connection_hdl hdl) override { MarketDataService::onOpen(hdl); WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); @@ -63,10 +64,6 @@ class MarketDataServiceDeribit : public MarketDataService { // END - BTS Custom Code ////////////////////////////////////////////////// - this->appendParam(document, allocator, std::chrono::duration_cast(now.time_since_epoch()).count(), "public/set_heartbeat", - { - {"interval", "10"}, - }); rj::StringBuffer stringBuffer; rj::Writer writer(stringBuffer); document.Accept(writer); @@ -77,6 +74,37 @@ class MarketDataServiceDeribit : public MarketDataService { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); } } + void onClose(wspp::connection_hdl hdl) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + this->subscriptionJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id); + MarketDataService::onClose(hdl); + } +#else + void onOpen(std::shared_ptr wsConnectionPtr) override { + MarketDataService::onOpen(wsConnectionPtr); + 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/set_heartbeat", + { + {"interval", "10"}, + }); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string msg = stringBuffer.GetString(); + ErrorCode ec; + this->send(wsConnectionPtr, msg, ec); + if (ec) { + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); + } + } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + this->subscriptionJsonrpcIdSetByConnectionIdMap.erase(wsConnectionPtr->id); + MarketDataService::onClose(wsConnectionPtr, ec); + } +#endif 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)); @@ -290,8 +318,19 @@ class MarketDataServiceDeribit : public MarketDataService { // END - BTS Custom Code ////////////////////////////////////////////////// - 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 it = document.FindMember("result"); @@ -410,7 +449,11 @@ class MarketDataServiceDeribit : public MarketDataService { document.Accept(writer); std::string msg = stringBuffer.GetString(); ErrorCode ec; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->send(hdl, msg, wspp::frame::opcode::text, ec); +#else + this->send(wsConnectionPtr, msg, ec); +#endif if (ec) { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request"); } @@ -616,12 +659,6 @@ class MarketDataServiceDeribit : public MarketDataService { CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE); } } - void onClose(wspp::connection_hdl hdl) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - this->subscriptionJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id); - MarketDataService::onClose(hdl); - } - std::map> subscriptionJsonrpcIdSetByConnectionIdMap; std::string restTarget; }; 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 7759f6c58..2ecdd95d4 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 @@ -68,8 +68,19 @@ class MarketDataServiceErisx : public MarketDataService { } 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()); std::string type = document["type"].GetString(); 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 40bd73de2..3681545b2 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 @@ -85,8 +85,19 @@ class MarketDataServiceFtxBase : public MarketDataService { 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 { + 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_gateio_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h index 47a9d9d3d..27e6ec352 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 @@ -14,12 +14,21 @@ class MarketDataServiceGateioBase : public MarketDataService { protected: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET 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); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + auto now = UtilTime::now(); + this->send(wsConnectionPtr, + "{\"time\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"channel\":\"" + (this->isDerivatives ? "futures" : "spot") + ".ping\"}", + ec); + } +#endif 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)); @@ -131,8 +140,19 @@ class MarketDataServiceGateioBase : public MarketDataService { } 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.HasMember("event") && std::string(document["event"].GetString()) == "subscribe") { 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 5de73f6b4..035f76127 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 @@ -49,6 +49,7 @@ class MarketDataServiceGemini : public MarketDataService { } } std::vector createSendStringList(const WsConnection& wsConnection) override { return std::vector(); } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void onOpen(wspp::connection_hdl hdl) override { MarketDataService::onOpen(hdl); WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); @@ -85,21 +86,147 @@ class MarketDataServiceGemini : public MarketDataService { this->sequenceByConnectionIdMap.erase(wsConnection.id); MarketDataService::onClose(hdl); } - void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event, - std::vector& marketDataMessageList) override { + bool checkSequence(const WsConnection& wsConnection, int sequence) { + if (this->sequenceByConnectionIdMap.find(wsConnection.id) == this->sequenceByConnectionIdMap.end()) { + if (sequence != this->sessionConfigs.getInitialSequenceByExchangeMap().at(this->exchangeName)) { + CCAPI_LOGGER_WARN("incorrect initial sequence, wsConnection = " + toString(wsConnection)); + return false; + } + this->sequenceByConnectionIdMap.insert(std::pair(wsConnection.id, sequence)); + return true; + } else { + if (sequence - this->sequenceByConnectionIdMap[wsConnection.id] == 1) { + this->sequenceByConnectionIdMap[wsConnection.id] = sequence; + return true; + } else { + return false; + } + } + } + void onOutOfSequence(WsConnection& wsConnection, int sequence, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, + const std::string& exchangeSubscriptionId) { + int previous = 0; + if (this->sequenceByConnectionIdMap.find(wsConnection.id) != this->sequenceByConnectionIdMap.end()) { + previous = this->sequenceByConnectionIdMap[wsConnection.id]; + } + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, + "out of sequence: previous = " + toString(previous) + ", current = " + toString(sequence) + ", connection = " + toString(wsConnection) + + ", textMessage = " + textMessage + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived)); + ErrorCode ec; + this->close(wsConnection, hdl, websocketpp::close::status::normal, "out of sequence", ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); + } + this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; + } +#else + void onOpen(std::shared_ptr wsConnectionPtr) override { + MarketDataService::onOpen(wsConnectionPtr); + std::vector correlationIdList; + for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnectionPtr->id)) { + auto channelId = subscriptionListByChannelIdSymbolId.first; + for (auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) { + auto symbolId = subscriptionListByInstrument.first; + int marketDepthSubscribedToExchange = this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnectionPtr->id][channelId][symbolId]; + if (marketDepthSubscribedToExchange == 1) { + this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnectionPtr->id][channelId][symbolId] = true; + } + auto exchangeSubscriptionId = wsConnectionPtr->url; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnectionPtr->id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; + this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnectionPtr->id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; + std::vector correlationIdList_2 = + this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnectionPtr->id).at(channelId).at(symbolId); + correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end()); + } + } + auto timeReceived = UtilTime::now(); + 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); + messageList.emplace_back(std::move(message)); + event.setMessageList(messageList); + this->eventHandler(event, nullptr); + } + void onClose(std::shared_ptr wsConnectionPtr, ErrorCode ec) override { + this->sequenceByConnectionIdMap.erase(wsConnectionPtr->id); + MarketDataService::onClose(wsConnectionPtr, ec); + } + bool checkSequence(std::shared_ptr wsConnectionPtr, int sequence) { + if (this->sequenceByConnectionIdMap.find(wsConnectionPtr->id) == this->sequenceByConnectionIdMap.end()) { + if (sequence != this->sessionConfigs.getInitialSequenceByExchangeMap().at(this->exchangeName)) { + CCAPI_LOGGER_WARN("incorrect initial sequence, wsConnection = " + toString(*wsConnectionPtr)); + return false; + } + this->sequenceByConnectionIdMap.insert(std::pair(wsConnectionPtr->id, sequence)); + return true; + } else { + if (sequence - this->sequenceByConnectionIdMap[wsConnectionPtr->id] == 1) { + this->sequenceByConnectionIdMap[wsConnectionPtr->id] = sequence; + return true; + } else { + return false; + } + } + } + void onOutOfSequence(std::shared_ptr wsConnectionPtr, int sequence, boost::beast::string_view textMessageView, const TimePoint& timeReceived, + const std::string& exchangeSubscriptionId) { + int previous = 0; + if (this->sequenceByConnectionIdMap.find(wsConnectionPtr->id) != this->sequenceByConnectionIdMap.end()) { + previous = this->sequenceByConnectionIdMap[wsConnectionPtr->id]; + } + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, + "out of sequence: previous = " + toString(previous) + ", current = " + toString(sequence) + ", connection = " + toString(*wsConnectionPtr) + + ", textMessage = " + std::string(textMessageView) + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived)); + ErrorCode ec; + this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason(beast::websocket::close_code::normal, "out of sequence"), + ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); + } + this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false; + } +#endif + 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()); if (this->sessionOptions.enableCheckSequence) { int sequence = std::stoi(document["socket_sequence"].GetString()); +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET if (!this->checkSequence(wsConnection, sequence)) { this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, ""); return; } +#else + if (!this->checkSequence(wsConnectionPtr, sequence)) { + this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, ""); + return; + } +#endif } if (type == "update" && !document["events"].GetArray().Empty()) { MarketDataMessage marketDataMessage; +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET marketDataMessage.exchangeSubscriptionId = wsConnection.url; +#else + marketDataMessage.exchangeSubscriptionId = wsConnectionPtr->url; +#endif TimePoint time = timeReceived; auto it = document.FindMember("timestampms"); if (it != document.MemberEnd()) { @@ -184,39 +311,6 @@ class MarketDataServiceGemini : public MarketDataService { } return url; } - bool checkSequence(const WsConnection& wsConnection, int sequence) { - if (this->sequenceByConnectionIdMap.find(wsConnection.id) == this->sequenceByConnectionIdMap.end()) { - if (sequence != this->sessionConfigs.getInitialSequenceByExchangeMap().at(this->exchangeName)) { - CCAPI_LOGGER_WARN("incorrect initial sequence, wsConnection = " + toString(wsConnection)); - return false; - } - this->sequenceByConnectionIdMap.insert(std::pair(wsConnection.id, sequence)); - return true; - } else { - if (sequence - this->sequenceByConnectionIdMap[wsConnection.id] == 1) { - this->sequenceByConnectionIdMap[wsConnection.id] = sequence; - return true; - } else { - return false; - } - } - } - void onOutOfSequence(WsConnection& wsConnection, int sequence, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, - const std::string& exchangeSubscriptionId) { - int previous = 0; - if (this->sequenceByConnectionIdMap.find(wsConnection.id) != this->sequenceByConnectionIdMap.end()) { - previous = this->sequenceByConnectionIdMap[wsConnection.id]; - } - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, - "out of sequence: previous = " + toString(previous) + ", current = " + toString(sequence) + ", connection = " + toString(wsConnection) + - ", textMessage = " + textMessage + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived)); - ErrorCode ec; - this->close(wsConnection, hdl, websocketpp::close::status::normal, "out of sequence", ec); - if (ec) { - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); - } - this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; - } void convertRequestForRest(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& credential) override { switch (request.getOperation()) { 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 e85048731..52467e21a 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 @@ -37,10 +37,17 @@ class MarketDataServiceKraken : public MarketDataService { private: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { auto now = UtilTime::now(); this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + auto now = UtilTime::now(); + this->send(wsConnectionPtr, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", ec); + } +#endif 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 Subscription& subscription, const std::map optionMap) override { @@ -117,8 +124,19 @@ class MarketDataServiceKraken : public MarketDataService { } 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; rj::Document::AllocatorType& allocator = document.GetAllocator(); document.Parse(textMessage.c_str()); 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 4a1525fae..e0c1e0970 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 @@ -79,8 +79,19 @@ class MarketDataServiceKrakenFutures : public MarketDataService { } 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; rj::Document::AllocatorType& allocator = document.GetAllocator(); document.Parse(textMessage.c_str()); 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 731118c1b..2bd38612d 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 @@ -19,14 +19,14 @@ class MarketDataServiceKucoin : public MarketDataServiceKucoinBase { } 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 + // #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; 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 b82c94579..cc1826042 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 @@ -43,6 +43,15 @@ class MarketDataServiceKucoinBase : public MarketDataService { } } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + 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 onOpen(wspp::connection_hdl hdl) override { + WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); + wsConnection.status = WsConnection::Status::OPEN; + } void prepareConnect(WsConnection& wsConnection) override { http::request req; req.set(http::field::host, this->hostRest); @@ -88,14 +97,53 @@ class MarketDataServiceKucoinBase : public MarketDataService { }, this->sessionOptions.httpRequestTimeoutMilliSeconds); } - void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { auto now = UtilTime::now(); - this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec); + this->send(wsConnectionPtr, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", ec); } - void onOpen(wspp::connection_hdl hdl) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - wsConnection.status = WsConnection::Status::OPEN; + void onOpen(std::shared_ptr wsConnectionPtr) override { wsConnectionPtr->status = WsConnection::Status::OPEN; } + void prepareConnect(std::shared_ptr wsConnectionPtr) override { + http::request req; + req.set(http::field::host, this->hostRest); + req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); + req.set(beast::http::field::content_type, "application/json"); + req.method(http::verb::post); + req.target("/api/v1/bullet-public"); + this->sendRequest( + req, [wsConnectionPtr, that = shared_from_base()](const beast::error_code& ec) { that->onFail_(wsConnectionPtr); }, + [wsConnectionPtr, that = shared_from_base()](const http::response& res) { + 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()); + wsConnectionPtr->url = urlWebsocketBase; + that->connect(wsConnectionPtr); + for (const auto& subscription : wsConnectionPtr->subscriptionList) { + auto instrument = subscription.getInstrument(); + that->subscriptionStatusByInstrumentGroupInstrumentMap[wsConnectionPtr->group][instrument] = Subscription::Status::SUBSCRIBING; + } + that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({ + {"pingInterval", std::string(instanceServer["pingInterval"].GetString())}, + {"pingTimeout", std::string(instanceServer["pingInterval"].GetString())}, + }); + return; + } catch (const std::runtime_error& e) { + CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); + } + } + that->onFail_(wsConnectionPtr); + }, + this->sessionOptions.httpRequestTimeoutMilliSeconds); } +#endif std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; std::map> symbolListByTopicMap; @@ -189,8 +237,19 @@ class MarketDataServiceKucoinBase : public MarketDataService { 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 { + 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()) { @@ -321,9 +380,14 @@ class MarketDataServiceKucoinBase : public MarketDataService { this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET Service::onOpen(hdl); WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); this->startSubscribe(wsConnection); +#else + Service::onOpen(wsConnectionPtr); + this->startSubscribe(wsConnectionPtr); +#endif } else if (type == "pong") { auto now = UtilTime::now(); this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now; 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 95b4f8c16..ba743fd03 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 @@ -19,14 +19,14 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase { } 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 + // #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"; 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 index 3bbb1d694..b45c24439 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h @@ -37,12 +37,19 @@ class MarketDataServiceMexc : public MarketDataService { protected: #endif // bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET 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; } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + this->send(wsConnectionPtr, R"({"id":)" + std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnectionPtr->id]) + R"(,"method":"PING"})", ec); + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnectionPtr->id] += 1; + } +#endif std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; rj::Document document; @@ -97,8 +104,19 @@ class MarketDataServiceMexc : public MarketDataService { 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 { + 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("code") && std::string(document["code"].GetString()) == "0") { 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 index eba85b604..09ed8fafd 100644 --- 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 @@ -36,7 +36,13 @@ class MarketDataServiceMexcFutures : public MarketDataService { protected: #endif bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"ping"})", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + this->send(wsConnectionPtr, R"({"method":"ping"})", ec); + } +#endif std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) { @@ -85,8 +91,19 @@ class MarketDataServiceMexcFutures : public MarketDataService { 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 { + 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("channel")) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h index 5f501d21d..5d3be02af 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h @@ -63,7 +63,11 @@ class MarketDataServiceOkx : public MarketDataService { } } } +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); } +#endif std::vector createSendStringList(const WsConnection& wsConnection) override { std::vector sendStringList; rj::Document document; @@ -117,15 +121,30 @@ class MarketDataServiceOkx : public MarketDataService { 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 { + 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 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") { +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET this->startSubscribe(wsConnection); +#else + this->startSubscribe(wsConnectionPtr); +#endif } else { if (document.IsObject() && document.HasMember("arg")) { const rj::Value& arg = document["arg"]; 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 index 6dbd39d76..3a1362d25 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h @@ -40,12 +40,20 @@ class MarketDataServiceWhitebit : public MarketDataService { private: #endif +#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET 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; } +#else + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { + this->send(wsConnectionPtr, + R"({"id":)" + std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnectionPtr->id]) + R"(,"method":"ping","params":[]})", ec); + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnectionPtr->id] += 1; + } +#endif 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)); @@ -118,8 +126,19 @@ class MarketDataServiceWhitebit : public MarketDataService { } 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 itId = document.FindMember("id"); diff --git a/linux/include/ccapi_cpp/service/ccapi_service.h b/linux/include/ccapi_cpp/service/ccapi_service.h index 289ebf615..7ce93e312 100644 --- a/linux/include/ccapi_cpp/service/ccapi_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_service.h @@ -378,31 +378,31 @@ class Service : public std::enable_shared_from_this { } std::shared_ptr httpConnectionPtr(new HttpConnection(host, port, streamPtr)); CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr)); - tcp::resolver newResolver(*this->serviceContextPtr->ioContextPtr); - newResolver.async_resolve( - host, port, - beast::bind_front_handler(&Service::onResolve, shared_from_this(), httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliSeconds)); + std::shared_ptr newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr)); + newResolverPtr->async_resolve(host, port, + beast::bind_front_handler(&Service::onResolve, shared_from_this(), httpConnectionPtr, newResolverPtr, req, errorHandler, + responseHandler, timeoutMilliSeconds)); } - void onResolve(std::shared_ptr httpConnectionPtr, http::request req, + void onResolve(std::shared_ptr httpConnectionPtr, std::shared_ptr newResolverPtr, http::request req, std::function errorHandler, std::function&)> responseHandler, - long timeoutMilliSeconds, beast::error_code ec, tcp::resolver::results_type tcpResolverResults) { + long timeoutMilliSeconds, beast::error_code ec, tcp::resolver::results_type tcpNewResolverResults) { if (ec) { CCAPI_LOGGER_TRACE("fail"); errorHandler(ec); return; } - this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliSeconds, tcpResolverResultsRest); + this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliSeconds, tcpNewResolverResults); } void startConnect(std::shared_ptr httpConnectionPtr, http::request req, std::function errorHandler, std::function&)> responseHandler, - long timeoutMilliSeconds, tcp::resolver::results_type tcpResolverResults) { + long timeoutMilliSeconds, tcp::resolver::results_type tcpNewResolverResults) { beast::ssl_stream& stream = *httpConnectionPtr->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::onConnect, shared_from_this(), httpConnectionPtr, req, errorHandler, responseHandler)); + tcpNewResolverResults, beast::bind_front_handler(&Service::onConnect, shared_from_this(), httpConnectionPtr, req, errorHandler, responseHandler)); CCAPI_LOGGER_TRACE("after async_connect"); } void onConnect(std::shared_ptr httpConnectionPtr, http::request req, @@ -1215,9 +1215,23 @@ class Service : public std::enable_shared_from_this { 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); + this->startResolveWs(wsConnectionPtr); CCAPI_LOGGER_FUNCTION_EXIT; } + void startResolveWs(std::shared_ptr wsConnectionPtr) { + std::shared_ptr newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr)); + newResolverPtr->async_resolve(wsConnectionPtr->host, wsConnectionPtr->port, + beast::bind_front_handler(&Service::onResolveWs, shared_from_this(), wsConnectionPtr, newResolverPtr)); + } + void onResolveWs(std::shared_ptr wsConnectionPtr, std::shared_ptr newResolverPtr, beast::error_code ec, + tcp::resolver::results_type tcpNewResolverResultsWs) { + if (ec) { + CCAPI_LOGGER_TRACE("fail"); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "dns resolve", wsConnectionPtr->correlationIdList); + return; + } + this->startConnectWs(wsConnectionPtr, this->sessionOptions.websocketConnectTimeoutMilliSeconds, tcpNewResolverResultsWs); + } void startConnectWs(std::shared_ptr wsConnectionPtr, long timeoutMilliSeconds, tcp::resolver::results_type tcpResolverResults) { beast::websocket::stream>& stream = *wsConnectionPtr->streamPtr; if (timeoutMilliSeconds > 0) { diff --git a/src/ccapi/install_ccapi.sh b/src/ccapi/install_ccapi.sh index 180466be8..9dbe0ae2c 100755 --- a/src/ccapi/install_ccapi.sh +++ b/src/ccapi/install_ccapi.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -ccapi_version="5.45.1" +ccapi_version="5.45.2" if [[ "$#" -gt 0 ]]; then ccapi_version="$1" fi