Upgrade ccapi to v6.12.0

This commit is contained in:
John Colvin committed 2025-02-23 15:33:55 +00:00
1 parent 8069cc893f
commit 90492733fd
109 files changed
+4172 -8930

No files matched your search

@@ -55,13 +55,13 @@ class ExecutionManagementService : public Service {
if (credential.empty()) {
credential = that->credentialDefault;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection wsConnection(that->baseUrlWs, "", {subscription}, credential);
that->prepareConnect(wsConnection);
#else
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = that->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs);
streamPtr = that->createWsStream(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr);
} 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()});
@@ -115,10 +115,11 @@ class ExecutionManagementService : public Service {
Request::Operation operation = request.getOperation();
message.setType(this->requestOperationToMessageTypeMap.at(operation));
auto castedOperation = static_cast<int>(operation);
if (castedOperation >= Request::operationTypeExecutionManagementOrder && castedOperation < Request::operationTypeExecutionManagementAccount) {
if (castedOperation >= CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ORDER &&
castedOperation < CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ACCOUNT) {
this->extractOrderInfoFromRequest(elementList, request, operation, document);
message.setElementList(elementList);
} else if (castedOperation >= Request::operationTypeExecutionManagementAccount) {
} else if (castedOperation >= CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ACCOUNT) {
this->extractAccountInfoFromRequest(elementList, request, operation, document);
message.setElementList(elementList);
}
@@ -163,8 +164,8 @@ class ExecutionManagementService : public Service {
this->eventHandler(event, eventQueuePtr);
}
}
virtual void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) {
virtual void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) {
for (const auto& y : extractionFieldNameMap) {
auto it = x.FindMember(y.second.first.c_str());
if (it != x.MemberEnd() && !it->value.IsNull()) {
@@ -175,6 +176,10 @@ class ExecutionManagementService : public Service {
if (y.first == CCAPI_EM_ORDER_SIDE) {
value = UtilString::toLower(value).rfind("buy", 0) == 0 ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL;
}
auto it2 = conversionMap.find(y.first);
if (it2 != conversionMap.end()) {
value = it2->second(value);
}
element.insert(y.first, value);
}
}
@@ -185,7 +190,7 @@ class ExecutionManagementService : public Service {
auto errorMessage = "Websocket unimplemented operation " + Request::operationToString(request.getOperation()) + " for exchange " + request.getExchange();
throw std::runtime_error(errorMessage);
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
virtual void logonToExchange(const WsConnection& wsConnection, const TimePoint& now, const std::map<std::string, std::string>& credential) {
CCAPI_LOGGER_INFO("about to logon to exchange");
CCAPI_LOGGER_INFO("exchange is " + this->exchangeName);
@@ -194,7 +199,7 @@ class ExecutionManagementService : public Service {
for (const auto& sendString : sendStringList) {
CCAPI_LOGGER_INFO("sendString = " + sendString);
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -208,7 +213,7 @@ class ExecutionManagementService : public Service {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
this->onTextMessage(wsConnection, subscription, textMessage, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived, false);
}
void onOpen(wspp::connection_hdl hdl) override {
CCAPI_LOGGER_FUNCTION_ENTER;
@@ -252,7 +257,7 @@ class ExecutionManagementService : public Service {
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived) override {
auto subscription = wsConnectionPtr->subscriptionList.at(0);
this->onTextMessage(wsConnectionPtr, subscription, textMessageView, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived, false);
}
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
CCAPI_LOGGER_FUNCTION_ENTER;
@@ -329,7 +334,7 @@ class ExecutionManagementService : public Service {
that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "Websocket connection was not found", {correlationId});
return;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
auto& wsConnection = it->second;
#else
auto wsConnectionPtr = it->second;
@@ -353,7 +358,7 @@ class ExecutionManagementService : public Service {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
CCAPI_LOGGER_TRACE("sendString = " + sendString);
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
that->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
that->send(wsConnectionPtr, sendString, ec);
@@ -389,10 +394,10 @@ class ExecutionManagementService : public Service {
std::string getAccountBalancesTarget;
std::string getAccountPositionsTarget;
std::map<std::string, std::string> correlationIdByConnectionIdMap;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
std::map<std::string, WsConnection> wsConnectionByCorrelationIdMap;
#else
std::map<std::string, std::shared_ptr<WsConnection> >
std::map<std::string, std::shared_ptr<WsConnection>>
wsConnectionByCorrelationIdMap; // TODO(cryptochassis): for consistency, to be renamed to wsConnectionPtrByCorrelationIdMap
#endif
std::map<std::string, int> wsRequestIdByConnectionIdMap;
@@ -14,19 +14,19 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_ASCENDEX_API_KEY;
this->apiSecretName = CCAPI_ASCENDEX_API_SECRET;
this->apiAccountGroupName = CCAPI_ASCENDEX_API_ACCOUNT_GROUP;
@@ -44,7 +44,7 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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));
@@ -288,7 +288,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
this->extractOrderInfoFromRequest(elementList, document);
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const rj::Value& value) {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -337,8 +337,8 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("cumFilledQty");
@@ -347,7 +347,8 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
auto it1Str = std::string(it1->value.GetString());
auto it2Str = std::string(it2->value.GetString());
if (!it1Str.empty() && !it2Str.empty()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))).toString());
}
}
}
@@ -363,13 +364,13 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
credential = that->credentialDefault;
}
const auto& accountGroup = mapGetWithDefault(credential, that->apiAccountGroupName);
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection wsConnection(that->baseUrlWs + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription}, credential);
that->prepareConnect(wsConnection);
#else
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = that->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs);
streamPtr = that->createWsStream(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr);
} 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()});
@@ -405,7 +406,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -428,7 +429,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -477,7 +478,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString()))));
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::INTEGER)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("sd", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)},
@@ -491,7 +492,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
auto it = data.FindMember("ap");
if (it != data.MemberEnd() && !it->value.IsNull()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["cfq"].GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["cfq"].GetString()))).toString());
}
info.insert(CCAPI_EM_BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING, data["bab"].GetString());
info.insert(CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL, data["btb"].GetString());
@@ -522,8 +523,8 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -537,7 +538,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
} else if (m == "connected") {
std::string type = document["type"].GetString();
if (type == "unauth") {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ExecutionManagementService::onOpen(hdl);
#else
ExecutionManagementService::onOpen(wsConnectionPtr);
@@ -17,19 +17,19 @@ class ExecutionManagementServiceBinance : public ExecutionManagementServiceBinan
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_API_KEY;
this->apiSecretName = CCAPI_BINANCE_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -18,7 +18,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
std::string host = hostPort.first;
@@ -74,7 +74,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
void onOpen(wspp::connection_hdl hdl) override {
ExecutionManagementService::onOpen(hdl);
@@ -138,7 +138,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
[wsConnection, that_2 = that->shared_from_base<ExecutionManagementServiceBinanceBase>()](const http::response<http::string_body>& res) {
CCAPI_LOGGER_DEBUG("ping listen key success");
},
that->sessionOptions.httpRequestTimeoutMilliSeconds);
that->sessionOptions.httpRequestTimeoutMilliseconds);
});
}
void onClose(wspp::connection_hdl hdl) override {
@@ -189,7 +189,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
std::string listenKey = document["listenKey"].GetString();
std::string url = that->baseUrlWs + "/" + listenKey;
wsConnectionPtr->url = url;
wsConnectionPtr->setUrl(url);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"listenKey", listenKey},
@@ -201,7 +201,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
ExecutionManagementService::onOpen(wsConnectionPtr);
@@ -265,7 +265,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
[wsConnectionPtr, that_2 = that->shared_from_base<ExecutionManagementServiceBinanceBase>()](const http::response<http::string_body>& res) {
CCAPI_LOGGER_DEBUG("ping listen key success");
},
that->sessionOptions.httpRequestTimeoutMilliSeconds);
that->sessionOptions.httpRequestTimeoutMilliseconds);
});
this->pingListenKeyTimerMapByConnectionIdMap[wsConnectionPtr->id] = timerPtr;
}
@@ -350,6 +350,11 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
queryString += "timeInForce=GTC&";
}
}
if (param.find("newClientOrderId") == param.end() && param.find(CCAPI_EM_CLIENT_ORDER_ID) == param.end()) {
std::string nonce = std::to_string(this->generateNonce(now, request.getIndex()));
queryString += std::string("newClientOrderId=x-") + (this->isDerivatives ? CCAPI_BINANCE_USDS_FUTURES_API_LINK_ID : CCAPI_BINANCE_API_LINK_ID) + "-" +
nonce + "&";
}
this->signRequest(queryString, param, now, credential);
req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN
? this->createOrderMarginTarget
@@ -446,6 +451,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair(this->isDerivatives ? "cumQuote" : "cummulativeQuoteQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
{CCAPI_LAST_UPDATED_TIME_SECONDS, std::make_pair("updateTime", JsonDataType::STRING)},
};
if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("origClientOrderId", JsonDataType::STRING)});
@@ -454,12 +460,20 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
}
if (document.IsObject()) {
Element element;
this->extractOrderInfo(element, document, extractionFieldNameMap);
this->extractOrderInfo(
element, document, extractionFieldNameMap,
{
{CCAPI_LAST_UPDATED_TIME_SECONDS, [](const std::string& input) { return UtilTime::convertMillisecondsStrToSecondsStr(input); }},
});
elementList.emplace_back(std::move(element));
} else {
for (const auto& x : document.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
this->extractOrderInfo(
element, x, extractionFieldNameMap,
{
{CCAPI_LAST_UPDATED_TIME_SECONDS, [](const std::string& input) { return UtilTime::convertMillisecondsStrToSecondsStr(input); }},
});
elementList.emplace_back(std::move(element));
}
}
@@ -475,6 +489,9 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
element.insert(CCAPI_EM_ASSET, x["asset"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString());
if (this->isDerivatives) {
element.insert(CCAPI_LAST_UPDATED_TIME_SECONDS, UtilTime::convertMillisecondsStrToSecondsStr(x["updateTime"].GetString()));
}
elementList.emplace_back(std::move(element));
}
} else {
@@ -526,7 +543,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -549,7 +566,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -630,7 +647,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
auto it = data.FindMember("ap");
if (it != data.MemberEnd() && !it->value.IsNull()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["z"].GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["z"].GetString()))).toString());
}
}
std::vector<Element> elementList;
@@ -639,6 +656,44 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
messageList.emplace_back(std::move(message));
}
}
} else if (this->isDerivatives && type == "ACCOUNT_UPDATE") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["a"];
if (fieldSet.find(CCAPI_EM_BALANCE_UPDATE) != fieldSet.end() && !data["B"].Empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(document["E"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE);
std::vector<Element> elementList;
for (const auto& x : data["B"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["a"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["wb"].GetString());
elementList.emplace_back(std::move(element));
}
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
if (fieldSet.find(CCAPI_EM_POSITION_UPDATE) != fieldSet.end() && !data["P"].Empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll((this->isDerivatives ? document : data)["E"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE);
std::vector<Element> elementList;
for (const auto& x : data["P"].GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["s"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["ps"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["pa"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["ep"].GetString());
element.insert(CCAPI_EM_UNREALIZED_PNL, x["up"].GetString());
elementList.emplace_back(std::move(element));
}
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
event.setMessageList(messageList);
return event;
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBinanceCoinFutures : public ExecutionManagementS
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY;
this->apiSecretName = CCAPI_BINANCE_COIN_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -45,6 +45,12 @@ class ExecutionManagementServiceBinanceDerivativesBase : public ExecutionManagem
element.insert(CCAPI_EM_POSITION_QUANTITY, positionAmt);
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
if (x.HasMember("unrealizedProfit")) {
element.insert(CCAPI_EM_UNREALIZED_PNL, x["unrealizedProfit"].GetString());
} else {
element.insert(CCAPI_EM_UNREALIZED_PNL, x["unRealizedProfit"].GetString());
}
element.insert(CCAPI_LAST_UPDATED_TIME_SECONDS, UtilTime::convertMillisecondsStrToSecondsStr(x["updateTime"].GetString()));
elementList.emplace_back(std::move(element));
}
} break;
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBinanceUs : public ExecutionManagementServiceBin
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_US_API_KEY;
this->apiSecretName = CCAPI_BINANCE_US_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBinanceUsdsFutures : public ExecutionManagementS
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY;
this->apiSecretName = CCAPI_BINANCE_USDS_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
this->baseUrlRest = CCAPI_BITFINEX_PRIVATE_URL_REST_BASE;
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITFINEX_API_KEY;
this->apiSecretName = CCAPI_BITFINEX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -42,7 +42,7 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -360,7 +360,7 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -383,7 +383,7 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived){
#else
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITGET_API_KEY;
this->apiSecretName = CCAPI_BITGET_API_SECRET;
this->apiPassphraseName = CCAPI_BITGET_API_PASSPHRASE;
@@ -167,7 +167,7 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOrderId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -211,8 +211,8 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("accFillSz");
@@ -221,7 +221,8 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
auto it1Str = std::string(it1->value.GetString());
auto it2Str = std::string(it2->value.GetString());
if (!it1Str.empty() && !it2Str.empty()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))).toString());
}
}
}
@@ -254,7 +255,7 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override{
#else
@@ -295,7 +296,7 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -365,7 +366,7 @@ Event createEvent(const Subscription& subscription, const std::string& textMessa
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<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& 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)},
@@ -8,13 +8,15 @@ class ExecutionManagementServiceBitgetBase : public ExecutionManagementService {
public:
ExecutionManagementServiceBitgetBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->hostHttpHeaderValueIgnorePort = true;
}
virtual ~ExecutionManagementServiceBitgetBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
@@ -10,36 +10,36 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/mix/v1/stream";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/ws/private";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITGET_FUTURES_API_KEY;
this->apiSecretName = CCAPI_BITGET_FUTURES_API_SECRET;
this->apiPassphraseName = CCAPI_BITGET_FUTURES_API_PASSPHRASE;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
this->createOrderTarget = "/api/mix/v1/order/placeOrder";
this->cancelOrderTarget = "/api/mix/v1/order/cancel-order";
this->getOrderTarget = "/api/mix/v1/order/detail";
this->getOpenOrdersTarget = "/api/mix/v1/order/current";
this->getAllOpenOrdersTarget = "/api/mix/v1/order/marginCoinCurrent";
this->cancelOpenOrdersTarget = "/api/mix/v1/order/cancel-all-orders";
this->getAccountBalancesTarget = "/api/mix/v1/account/accounts";
this->getAccountPositionsTarget = "/api/mix/v1/position/singlePosition";
this->getAccountAllPositionsTarget = "/api/mix/v1/position/allPosition";
this->createOrderTarget = "/api/v2/mix/order/place-order";
this->cancelOrderTarget = "/api/v2/mix/order/cancel-order";
this->getOrderTarget = "/api/v2/mix/order/detail";
this->getOpenOrdersTarget = "/api/v2/mix/order/orders-pending";
this->getAllOpenOrdersTarget = "/api/v2/mix/order/orders-pending";
this->cancelOpenOrdersTarget = "/api/v2/mix/order/cancel-all-orders";
this->getAccountBalancesTarget = "/api/v2/mix/account/accounts";
this->getAccountPositionsTarget = "/api/v2/mix/position/single-position";
this->getAccountAllPositionsTarget = "/api/v2/mix/position/all-position";
}
virtual ~ExecutionManagementServiceBitgetFutures() {}
#ifndef CCAPI_EXPOSE_INTERNAL
@@ -49,6 +49,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_MARGIN_ASSET, "marginCoin"},
{CCAPI_MARGIN_MODE, "marginMode"},
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "size"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
@@ -65,8 +66,9 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
}
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_MARGIN_ASSET, "marginCoin"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_EM_CLIENT_ORDER_ID, "clientOrderId"},
{CCAPI_EM_CLIENT_ORDER_ID, "clientOid"},
{CCAPI_SYMBOL_ID, "symbol"},
{CCAPI_INSTRUMENT_TYPE, "productType"},
}) {
@@ -97,9 +99,6 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
if (param.find("orderType") == param.end()) {
document.AddMember("orderType", rj::Value("limit").Move(), allocator);
}
if (param.find("timeInForceValue") == param.end()) {
document.AddMember("timeInForceValue", rj::Value("normal").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId);
}
@@ -213,26 +212,40 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("baseVolume", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
const rj::Value& data = document["data"];
if (operation == Request::Operation::CREATE_ORDER || operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::GET_ORDER) {
const rj::Value& data = document["data"];
Element element;
this->extractOrderInfo(element, data, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
const rj::Value& data = document["data"]["entrustedList"];
for (const auto& x : data.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else if (operation == Request::Operation::CANCEL_OPEN_ORDERS) {
const rj::Value& successList = document["data"]["successList"];
for (const auto& x : successList.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
const rj::Value& failureList = document["data"]["failureList"];
for (const auto& x : failureList.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
}
}
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
@@ -241,12 +254,11 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : document["data"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["coinName"].GetString());
std::string available = x["available"].GetString();
element.insert(CCAPI_EM_ASSET, x["marginCoin"].GetString());
std::string available = x["crossedMaxAvailable"].GetString();
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, available);
std::string frozen = x["frozen"].GetString();
std::string lock = x["lock"].GetString();
element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(frozen)).add(Decimal(lock))).toString());
std::string locked = x["locked"].GetString();
element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(locked))).toString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -257,8 +269,9 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
element.insert(CCAPI_MARGIN_ASSET, x["marginCoin"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["holdSide"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["total"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["averageOpenPrice"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["openPriceAvg"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
element.insert(CCAPI_EM_UNREALIZED_PNL, x["unrealizedPL"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -266,17 +279,18 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("accFillSz");
auto it2 = x.FindMember("avgPx");
auto it1 = x.FindMember("accBaseVolume");
auto it2 = x.FindMember("priceAvg");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
auto it1Str = std::string(it1->value.GetString());
auto it2Str = std::string(it2->value.GetString());
if (!it1Str.empty() && !it2Str.empty()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))).toString());
}
}
}
@@ -309,7 +323,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override {
#else
@@ -330,18 +344,29 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
rj::Value args(rj::kArrayType);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
const auto& instrumentType = subscription.getInstrumentType();
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);
}
if (field == CCAPI_EM_ORDER_UPDATE || field == CCAPI_EM_PRIVATE_TRADE) {
for (const auto& instrument : instrumentSet) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("orders", allocator).Move(), allocator);
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
arg.AddMember("instType", rj::Value(instrumentType.c_str(), allocator).Move(), allocator);
args.PushBack(arg, allocator);
}
} else if (field == CCAPI_EM_POSITION_UPDATE) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("positions", allocator).Move(), allocator);
arg.AddMember("instId", rj::Value("default", allocator).Move(), allocator);
arg.AddMember("instType", rj::Value(instrumentType.c_str(), allocator).Move(), allocator);
args.PushBack(arg, allocator);
} else if (field == CCAPI_EM_BALANCE_UPDATE) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("account", allocator).Move(), allocator);
arg.AddMember("coin", rj::Value("default", allocator).Move(), allocator);
arg.AddMember("instType", rj::Value(instrumentType.c_str(), allocator).Move(), allocator);
args.PushBack(arg, allocator);
}
}
document.AddMember("args", args, allocator);
rj::StringBuffer stringBufferSubscribe;
@@ -349,7 +374,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -358,7 +383,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
}
} else {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event event = this->createEvent(wsConnection, wsConnection.hdl, subscription, textMessage, document, eventStr, timeReceived);
#else
Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, eventStr, timeReceived);
@@ -369,7 +394,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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
@@ -389,8 +414,9 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
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()) {
std::string instId = (channel == "account") ? "coin" : "instId";
std::string instrument = arg[instId.c_str()].GetString();
if (instrumentSet.empty() || instrument == "default" || instrumentSet.find(instrument) != instrumentSet.end()) {
if (channel == "orders") {
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
const rj::Value& data = document["data"];
@@ -406,15 +432,19 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
std::vector<Element> 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_LAST_EXECUTED_PRICE, std::string(x["fillPrice"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["baseVolume"].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_IS_MAKER, std::string(x["tradeScope"].GetString()) == "M" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["orderId"].GetString()));
auto itClientOId = x.FindMember("clientOId");
std::string clientOId = itClientOId != x.MemberEnd() ? itClientOId->value.GetString() : "";
if(!clientOId.empty()){
element.insert(CCAPI_EM_CLIENT_ORDER_ID, clientOId);
}
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()));
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCoin"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
@@ -429,13 +459,13 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
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<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("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_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accBaseVolume", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
};
Element info;
@@ -447,6 +477,42 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
messageList.emplace_back(std::move(message));
}
}
} else if (channel == "positions"){
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["uTime"].GetString())));
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_INSTRUMENT, x["instId"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["holdSide"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["total"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["openPriceAvg"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (channel == "account"){
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_EM_ASSET, x["marginCoin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["equity"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (eventStr == "subscribe") {
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITMART_API_KEY;
this->apiSecretName = CCAPI_BITMART_API_SECRET;
this->apiMemoName = CCAPI_BITMART_API_MEMO;
@@ -38,7 +38,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
this->cancelOpenOrdersTarget = "/spot/v1/cancel_orders";
this->getAccountBalancesTarget = "/spot/v1/wallet";
this->needDecompressWebsocketMessage = true;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ErrorCode ec = this->inflater.init(false);
#else
ErrorCode ec = this->inflater.init();
@@ -52,7 +52,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
@@ -141,6 +141,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
case Request::Operation::CREATE_ORDER: {
req.method(http::verb::post);
req.target(this->createOrderTarget);
req.set("X-BM-BROKER-ID", CCAPI_BITMART_BROKER_ID);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
@@ -301,7 +302,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override {
#else
@@ -338,7 +339,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITMEX_API_KEY;
this->apiSecretName = CCAPI_BITMEX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -224,7 +224,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& 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)},
@@ -272,15 +272,17 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("cumQty");
auto it2 = x.FindMember("avgPx");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
element.insert(
CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))))
.toString());
}
}
}
@@ -311,7 +313,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -334,7 +336,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived){
#else
@@ -404,7 +406,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -448,7 +450,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
}
} else if (table == "order" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& 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)},
@@ -464,7 +466,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
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())));
Decimal(UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(x["cumQty"].GetString()))).toString());
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITSTAMP_API_KEY;
this->apiSecretName = CCAPI_BITSTAMP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -44,7 +44,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec);
}
@@ -204,8 +204,8 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("type");
@@ -274,7 +274,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
@@ -329,7 +329,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#else
void prepareConnect(std::shared_ptr<WsConnection> wsConnectionPtr) override {
@@ -367,7 +367,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
if (document.HasMember("token") && document.HasMember("user_id")) {
std::string token = document["token"].GetString();
std::string userId = document["user_id"].GetString();
wsConnectionPtr->url = that->baseUrlWs;
wsConnectionPtr->setUrl(that->baseUrlWs);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"token", token},
@@ -381,7 +381,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#endif
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
@@ -416,7 +416,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
}
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -439,7 +439,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -2,51 +2,134 @@
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h"
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBase {
class ExecutionManagementServiceBybit : public ExecutionManagementService {
public:
ExecutionManagementServiceBybit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/private/v3";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v5/private";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->apiKeyName = CCAPI_BYBIT_API_KEY;
this->apiSecretName = CCAPI_BYBIT_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = "/spot/v3/private/order";
this->cancelOrderTarget = "/spot/v3/private/cancel-order";
this->getOrderTarget = "/spot/v3/private/order";
this->getOpenOrdersTarget = "/spot/v3/private/open-orders";
this->cancelOpenOrdersTarget = "/spot/v3/private/cancel-orders";
this->getAccountBalancesTarget = "/spot/v3/private/account";
this->createOrderTarget = "/v5/order/create";
this->cancelOrderTarget = "/v5/order/cancel";
this->getOrderTarget = "/v5/order/realtime";
this->getOpenOrdersTarget = "/v5/order/realtime";
this->cancelOpenOrdersTarget = "/v5/order/cancel-all";
this->getAccountBalancesTarget = "/v5/account/wallet-balance";
this->getAccountPositionsTarget = "/v5/position/list";
}
virtual ~ExecutionManagementServiceBybit() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; }
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& 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<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string();
preSignedText += apiKey;
preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string();
std::string aString;
if (methodString == "GET") {
aString = queryString;
} else if (methodString == "POST") {
aString = body;
}
preSignedText += aString;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-BAPI-SIGN", signature);
}
void signRequest(http::request<http::string_body>& req, const std::string aString, const TimePoint& now,
const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string();
preSignedText += apiKey;
preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string();
preSignedText += aString;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-BAPI-SIGN", signature);
}
void appendParamToQueryString(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_SETTLE_ASSET, "settleCoin"},
{CCAPI_EM_ACCOUNT_TYPE, "accountType"},
}) {
for (const auto& kv : param) {
queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
queryString += "=";
queryString += Url::urlEncode(kv.second);
queryString += "&";
}
}
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("X-BAPI-API-KEY", apiKey);
req.set("X-BAPI-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
req.set("X-BAPI-RECV-WINDOW", std::to_string(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS));
req.set("X-Referer", CCAPI_BYBIT_API_BROKER_ID);
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("auth").Move(), allocator);
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto expires = std::chrono::duration_cast<std::chrono::milliseconds>(
(now + std::chrono::milliseconds(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS)).time_since_epoch())
.count();
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = "GET";
preSignedText += "/realtime";
preSignedText += std::to_string(expires);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
rj::Value args(rj::kArrayType);
args.PushBack(rj::Value(apiKey.c_str(), allocator).Move(), allocator);
args.PushBack(rj::Value(expires).Move(), allocator);
args.PushBack(rj::Value(signature.c_str(), allocator).Move(), allocator);
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
return sendStringList;
}
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const TimePoint& timeReceived) override {
std::string textMessage(textMessageView);
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived);
if (!event.getMessageList().empty()) {
this->eventHandler(event, nullptr);
}
}
void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "orderQty"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "orderPrice"},
{CCAPI_EM_ORDER_QUANTITY, "qty"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_LIMIT, "limit"},
@@ -58,11 +141,7 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
value = value == CCAPI_EM_ORDER_SIDE_BUY ? "Buy" : "Sell";
}
if (value != "null") {
if (key == "orderCategory") {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), std::stoi(value), allocator);
} else {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
@@ -82,8 +161,11 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("category") == param.end()) {
document.AddMember("category", rj::Value("spot").Move(), allocator);
}
if (param.find("orderType") == param.end()) {
document.AddMember("orderType", rj::Value("LIMIT").Move(), allocator);
document.AddMember("orderType", rj::Value("Limit").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
@@ -105,6 +187,12 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("category") == param.end()) {
document.AddMember("category", rj::Value("spot").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
@@ -118,6 +206,9 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
if (param.find("category") == param.end()) {
queryString += "category=spot&";
}
req.target(this->getOrderTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
@@ -126,6 +217,9 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
if (param.find("category") == param.end()) {
queryString += "category=spot&";
}
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId, "symbol");
}
@@ -141,6 +235,9 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("category") == param.end()) {
document.AddMember("category", rj::Value("spot").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
}
@@ -155,8 +252,20 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::get);
std::string queryString;
this->appendParamToQueryString(queryString, {});
req.target(this->getAccountBalancesTarget);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
if (param.find("accountType") == param.end()) {
queryString += "accountType=UNIFIED&";
}
req.target(this->getAccountBalancesTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
req.method(http::verb::get);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
req.target(this->getAccountPositionsTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
default:
@@ -169,14 +278,14 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("orderPrice", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("execQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cummulativeQuoteQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
if (operation == Request::Operation::GET_OPEN_ORDERS) {
if (operation == Request::Operation::GET_OPEN_ORDERS || operation == Request::Operation::GET_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
@@ -192,11 +301,22 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
const rj::Document& document) override {
switch (request.getOperation()) {
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : document["result"]["balances"].GetArray()) {
for (const auto& x : document["result"]["list"][0]["coin"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["coin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["total"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["equity"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPrice"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -204,79 +324,41 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#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<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const rj::Document& document, const TimePoint& timeReceived) override {
const rj::Document& document, const TimePoint& timeReceived) {
std::string textMessage(textMessageView);
#endif
Event event;
std::vector<Message> 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<Element> 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()));
}
}
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
Event event;
std::vector<Message> 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.rfind("order", 0) == 0) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["updatedTime"].GetString())));
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& 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)},
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_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);
@@ -286,57 +368,127 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
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<rj::StringBuffer> 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 (topic.rfind("execution", 0) == 0) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["execTime"].GetString())));
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, x["execId"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["execPrice"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(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, x["isMaker"].GetBool() ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["orderId"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(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 == "wallet") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data[0]["coin"].GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_EM_ASSET, x["coin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["equity"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (topic.rfind("position", 0) == 0) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["updatedTime"].GetString())));
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} 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));
} 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);
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
args.PushBack(rj::Value(("order." + subscription.getInstrumentType()).c_str(), allocator).Move(), allocator);
}
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
args.PushBack(rj::Value(("execution." + subscription.getInstrumentType()).c_str(), allocator).Move(), allocator);
}
if (fieldSet.find(CCAPI_EM_POSITION_UPDATE) != fieldSet.end() && subscription.getInstrumentType() != "spot") {
args.PushBack(rj::Value(("position." + subscription.getInstrumentType()).c_str(), allocator).Move(), allocator);
}
if (fieldSet.find(CCAPI_EM_BALANCE_UPDATE) != fieldSet.end()) {
args.PushBack(rj::Value("wallet").Move(), allocator);
}
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> 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");
}
}
} 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));
}
}
event.setMessageList(messageList);
return event;
}
event.setMessageList(messageList);
return event;
}
}; // namespace ccapi
} /* namespace ccapi */
#endif
@@ -1,140 +0,0 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#if defined(CCAPI_ENABLE_EXCHANGE_BYBIT) || defined(CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES)
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBybitBase : public ExecutionManagementService {
public:
ExecutionManagementServiceBybitBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~ExecutionManagementServiceBybitBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; }
#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<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& 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<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string();
preSignedText += apiKey;
preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string();
std::string aString;
if (methodString == "GET") {
aString = queryString;
} else if (methodString == "POST") {
aString = body;
}
preSignedText += aString;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-BAPI-SIGN", signature);
}
void signRequest(http::request<http::string_body>& req, const std::string aString, const TimePoint& now,
const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string();
preSignedText += apiKey;
preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string();
preSignedText += aString;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-BAPI-SIGN", signature);
}
void appendParamToQueryString(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
queryString += "=";
queryString += Url::urlEncode(kv.second);
queryString += "&";
}
}
// void appendSymbolId(std::string& queryString, const std::string& symbolId) {
// queryString += "symbol=";
// queryString += Url::urlEncode(symbolId);
// queryString += "&";
// }
// void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
// rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
// }
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("X-BAPI-SIGN-TYPE", "2");
req.set("X-BAPI-API-KEY", apiKey);
req.set("X-BAPI-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
req.set("X-BAPI-RECV-WINDOW", std::to_string(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS));
req.set("Referer", CCAPI_BYBIT_API_BROKER_ID);
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("auth").Move(), allocator);
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto expires = std::chrono::duration_cast<std::chrono::milliseconds>(
(now + std::chrono::milliseconds(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS)).time_since_epoch())
.count();
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = "GET";
preSignedText += "/realtime";
preSignedText += std::to_string(expires);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
rj::Value args(rj::kArrayType);
args.PushBack(rj::Value(apiKey.c_str(), allocator).Move(), allocator);
args.PushBack(rj::Value(expires).Move(), allocator);
args.PushBack(rj::Value(signature.c_str(), allocator).Move(), allocator);
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> 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<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
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<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const TimePoint& timeReceived) override {
std::string textMessage(textMessageView);
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(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<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const rj::Document& document, const TimePoint& timeReceived) {
return {};
}
#endif
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
@@ -1,389 +0,0 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h"
namespace ccapi {
class ExecutionManagementServiceBybitDerivatives : public ExecutionManagementServiceBybitBase {
public:
ExecutionManagementServiceBybitDerivatives(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions,
SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/unified/private/v3";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->apiKeyName = CCAPI_BYBIT_DERIVATIVES_API_KEY;
this->apiSecretName = CCAPI_BYBIT_DERIVATIVES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = "/unified/v3/private/order/create";
this->cancelOrderTarget = "/unified/v3/private/order/cancel";
this->getOrderTarget = "/unified/v3/private/order/list";
this->getOpenOrdersTarget = "/unified/v3/private/order/unfilled-orders";
this->cancelOpenOrdersTarget = "/unified/v3/private/order/cancel-all";
this->getAccountBalancesTarget = "/unified/v3/private/account/wallet/balance";
this->getAccountPositionsTarget = "/unified/v3/private/position/list";
}
virtual ~ExecutionManagementServiceBybitDerivatives() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "qty"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "category"},
}) {
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
if (key == "side") {
value = value == CCAPI_EM_ORDER_SIDE_BUY ? "Buy" : "Sell";
}
if (value != "null") {
if (key == "reduceOnly" || key == "closeOnTrigger" || key == "mmp") {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
} else {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
this->prepareReq(req, now, credential);
switch (request.getOperation()) {
case Request::Operation::GENERIC_PRIVATE_REQUEST: {
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::CREATE_ORDER: {
req.method(http::verb::post);
req.set(beast::http::field::content_type, "application/json");
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->createOrderTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("orderType") == param.end()) {
document.AddMember("orderType", rj::Value("Limit").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
req.body() = body;
req.prepare_payload();
this->signRequest(req, body, now, credential);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
req.set(beast::http::field::content_type, "application/json");
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->cancelOrderTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
this->appendSymbolId(document, allocator, symbolId, "symbol");
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
req.body() = body;
req.prepare_payload();
this->signRequest(req, body, now, credential);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::get);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param,
{
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "category"},
});
req.target(this->getOrderTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::get);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param,
{
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "category"},
});
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId, "symbol");
}
req.target(this->getOpenOrdersTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::post);
req.set(beast::http::field::content_type, "application/json");
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->cancelOpenOrdersTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
req.body() = body;
req.prepare_payload();
this->signRequest(req, body, now, credential);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::get);
std::string queryString;
this->appendParamToQueryString(queryString, {});
req.target(queryString.empty() ? this->getAccountBalancesTarget : this->getAccountBalancesTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
req.method(http::verb::get);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
req.target(this->getAccountPositionsTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
std::map<std::string, std::pair<std::string, JsonDataType> > extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("leavesQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
if (operation == Request::Operation::GET_ORDER || operation == Request::Operation::GET_OPEN_ORDERS || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else {
Element element;
this->extractOrderInfo(element, document["result"], extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
}
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
switch (request.getOperation()) {
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : document["result"]["coin"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["currencyCoin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#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<WsConnection> 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<Message> 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<std::string, std::pair<std::string, JsonDataType> >& 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<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (topic == "user.execution.unifiedAccount") {
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"]["result"];
for (const auto& x : data.GetArray()) {
std::string execType = x["execType"].GetString();
if (execType == "TRADE") {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["execTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> 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<rj::StringBuffer> 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
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
@@ -14,19 +14,19 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_COINBASE_API_KEY;
this->apiSecretName = CCAPI_COINBASE_API_SECRET;
this->apiPassphraseName = CCAPI_COINBASE_API_PASSPHRASE;
@@ -293,7 +293,7 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -316,7 +316,7 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -358,14 +358,16 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
element.insert(CCAPI_EM_ORDER_SIDE, makerSide == "buy" ? CCAPI_EM_ORDER_SIDE_SELL : CCAPI_EM_ORDER_SIDE_BUY);
element.insert(CCAPI_IS_MAKER, "0");
element.insert(CCAPI_EM_ORDER_ID, document["taker_order_id"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY,
UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) * std::stod(document["taker_fee_rate"].GetString())));
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, Decimal(UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) *
std::stod(document["taker_fee_rate"].GetString())))
.toString());
} else if (document.FindMember("maker_user_id") != document.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_SIDE, makerSide == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, "1");
element.insert(CCAPI_EM_ORDER_ID, document["maker_order_id"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY,
UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) * std::stod(document["maker_fee_rate"].GetString())));
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, Decimal(UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) *
std::stod(document["maker_fee_rate"].GetString())))
.toString());
}
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
elementList.emplace_back(std::move(element));
@@ -14,19 +14,19 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_CRYPTOCOM_API_KEY;
this->apiSecretName = CCAPI_CRYPTOCOM_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -331,7 +331,7 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
sendStringList.push_back(body);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -354,7 +354,7 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -486,7 +486,7 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, msg, ec);
@@ -551,7 +551,7 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -14,19 +14,19 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->clientIdName = CCAPI_DERIBIT_CLIENT_ID;
this->clientSecretName = CCAPI_DERIBIT_CLIENT_SECRET;
this->setupCredential({this->clientIdName, this->clientSecretName});
@@ -45,7 +45,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
ExecutionManagementService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -315,15 +315,17 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("filled_amount");
auto it2 = x.FindMember("average_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
element.insert(
CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))))
.toString());
}
}
}
@@ -356,7 +358,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -379,7 +381,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -448,7 +450,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -533,7 +535,9 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
auto it2 = x.FindMember("average_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) *
(it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))))
.toString());
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
@@ -554,7 +558,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, msg, ec);
@@ -15,19 +15,19 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_ERISX_API_KEY;
this->apiSecretName = CCAPI_ERISX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -192,7 +192,7 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& 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)},
@@ -221,15 +221,15 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService {
}
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("cumQty");
auto it2 = x.FindMember("avgPrice");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
}
@@ -19,7 +19,7 @@ class ExecutionManagementServiceFtx : public ExecutionManagementServiceFtxBase {
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -22,7 +22,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
@@ -213,7 +213,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -259,8 +259,8 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("filledSize");
@@ -324,7 +324,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
}
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const TimePoint& timeReceived) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -376,7 +376,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
} else if (channel == "orders" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setTime(timeReceived);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -19,7 +19,7 @@ class ExecutionManagementServiceFtxUs : public ExecutionManagementServiceFtxBase
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -14,19 +14,19 @@ class ExecutionManagementServiceGateio : public ExecutionManagementServiceGateio
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GATEIO_API_KEY;
this->apiSecretName = CCAPI_GATEIO_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -14,7 +14,7 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl,
@@ -352,7 +352,7 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
}
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -375,7 +375,7 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -14,19 +14,19 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY;
this->apiSecretName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -74,7 +74,8 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
Element element;
element.insert(CCAPI_INSTRUMENT, x["contract"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["entry_price"].GetString()) * std::stod(x["size"].GetString())));
element.insert(CCAPI_EM_POSITION_COST,
Decimal(UtilString::printDoubleScientific(std::stod(x["entry_price"].GetString()) * std::stod(x["size"].GetString()))).toString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -105,13 +106,13 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
if (credential.empty()) {
credential = that->credentialDefault;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection wsConnection(that->baseUrlWs + settle, "", {subscription}, credential);
that->prepareConnect(wsConnection);
#else
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = that->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs);
streamPtr = that->createWsStream(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr);
} 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()});
@@ -14,19 +14,19 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GEMINI_API_KEY;
this->apiSecretName = CCAPI_GEMINI_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -200,7 +200,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -249,15 +249,15 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("executed_amount");
auto it2 = x.FindMember("avg_execution_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
{
@@ -273,7 +273,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto subscription = wsConnection.subscriptionList.at(0);
@@ -315,16 +315,16 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
credential = this->credentialDefault;
}
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
wsConnectionPtr->url += "?heartbeat=true";
wsConnectionPtr->appendUrlPart("?heartbeat=true");
if (fieldSet == std::set<std::string>({CCAPI_EM_PRIVATE_TRADE})) {
wsConnectionPtr->url += "&eventTypeFilter=fill";
wsConnectionPtr->appendUrlPart("&eventTypeFilter=fill");
}
if (!instrumentSet.empty()) {
for (const auto& instrument : instrumentSet) {
wsConnectionPtr->url += "&symbolFilter=" + instrument;
wsConnectionPtr->appendUrlPart("&symbolFilter=" + instrument);
}
}
wsConnectionPtr->url += "&apiSessionFilter=" + apiKey;
wsConnectionPtr->appendUrlPart("&apiSessionFilter=" + apiKey);
wsConnectionPtr->headers.insert({"X-GEMINI-APIKEY", apiKey});
int64_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
std::string payload = R"({"request":"/v1/order/events","nonce":)" + std::to_string(nonce) + "}";
@@ -336,7 +336,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
this->connect(wsConnectionPtr);
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -359,7 +359,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -419,7 +419,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -436,7 +436,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
auto it2 = x.FindMember("avg_execution_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
{
@@ -14,19 +14,19 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_HUOBI_API_KEY;
this->apiSecretName = CCAPI_HUOBI_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -235,7 +235,8 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now);
timestamp.pop_back();
std::string signature;
std::string queryString;
std::map<std::string, std::string> queryParamMap;
@@ -265,7 +266,7 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override {
#else
@@ -308,7 +309,7 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -330,7 +331,7 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
std::string toReplace("ping");
sendString.replace(sendString.find(toReplace), toReplace.length(), "pong");
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -51,7 +51,8 @@ class ExecutionManagementServiceHuobiBase : public ExecutionManagementService {
queryParamMap.insert(std::make_pair("AccessKeyId", apiKey));
queryParamMap.insert(std::make_pair("SignatureMethod", "HmacSHA256"));
queryParamMap.insert(std::make_pair("SignatureVersion", "2"));
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now);
timestamp.pop_back();
queryParamMap.insert(std::make_pair("Timestamp", Url::urlEncode(timestamp)));
std::string signature;
this->createSignature(signature, queryString, methodString, this->hostRest, path, queryParamMap, credential);
@@ -111,7 +112,8 @@ class ExecutionManagementServiceHuobiBase : public ExecutionManagementService {
queryParamMap.insert(std::make_pair("AccessKeyId", apiKey));
queryParamMap.insert(std::make_pair("SignatureMethod", "HmacSHA256"));
queryParamMap.insert(std::make_pair("SignatureVersion", "2"));
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now);
timestamp.pop_back();
queryParamMap.insert(std::make_pair("Timestamp", Url::urlEncode(timestamp)));
this->convertReqDetail(req, request, now, symbolId, credential, queryParamMap);
}
@@ -14,19 +14,19 @@ class ExecutionManagementServiceHuobiCoinSwap : public ExecutionManagementServic
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_HUOBI_COIN_SWAP_API_KEY;
this->apiSecretName = CCAPI_HUOBI_COIN_SWAP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -13,7 +13,7 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ErrorCode ec = this->inflater.init(false, 31);
#else
this->inflater.setWindowBitsOverride(31);
@@ -142,7 +142,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("direction", JsonDataType::STRING)},
@@ -202,22 +202,25 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("trade_volume");
auto it2 = x.FindMember("trade_avg_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
element.insert(
CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))))
.toString());
}
}
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now);
timestamp.pop_back();
std::string signature;
std::string queryString;
std::map<std::string, std::string> queryParamMap;
@@ -244,7 +247,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override {
#else
@@ -279,7 +282,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -300,7 +303,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
std::string toReplace("ping");
sendString.replace(sendString.find(toReplace), toReplace.length(), "pong");
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -335,7 +338,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(document["ts"].GetString())));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("direction", JsonDataType::STRING)},
@@ -352,7 +355,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
auto it2 = document.FindMember("trade_avg_price");
if (it1 != document.MemberEnd() && it2 != document.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
for (const auto& x : document["trade"].GetArray()) {
@@ -14,19 +14,19 @@ class ExecutionManagementServiceHuobiUsdtSwap : public ExecutionManagementServic
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_HUOBI_USDT_SWAP_API_KEY;
this->apiSecretName = CCAPI_HUOBI_USDT_SWAP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -15,19 +15,19 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_KRAKEN_API_KEY;
this->apiSecretName = CCAPI_KRAKEN_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -46,7 +46,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -231,7 +231,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
auto it2 = itr->value.FindMember("price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
elementList.emplace_back(std::move(element));
@@ -271,7 +271,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
@@ -324,7 +324,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#else
void prepareConnect(std::shared_ptr<WsConnection> wsConnectionPtr) override {
@@ -361,7 +361,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
if (document.HasMember("result") && document["result"].HasMember("token")) {
std::string token = document["result"]["token"].GetString();
wsConnectionPtr->url = that->baseUrlWs;
wsConnectionPtr->setUrl(that->baseUrlWs);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"token", token},
@@ -374,7 +374,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#endif
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
@@ -404,7 +404,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
}
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -427,7 +427,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -500,8 +500,9 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
auto it1 = itr->value.FindMember("vol_exec");
auto it2 = itr->value.FindMember("avg_price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
element.insert(
CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
elementList.emplace_back(std::move(element));
@@ -513,7 +514,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
auto it2 = itr->value.FindMember("avg_price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
elementList.emplace_back(std::move(element));
@@ -15,19 +15,19 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_KRAKEN_FUTURES_API_KEY;
this->apiSecretName = CCAPI_KRAKEN_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -273,7 +273,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -296,7 +296,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -420,7 +420,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
}
for (const auto& sendString : sendStringList) {
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -12,12 +12,12 @@ class ExecutionManagementServiceKucoin : public ExecutionManagementServiceKucoin
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -15,7 +15,7 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
wsConnection.status = WsConnection::Status::OPEN;
@@ -69,7 +69,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#else
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override { wsConnectionPtr->status = WsConnection::Status::OPEN; }
@@ -105,7 +105,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
urlWebsocketBase += std::string(instanceServer["endpoint"].GetString());
urlWebsocketBase += "?token=";
urlWebsocketBase += std::string(document["data"]["token"].GetString());
wsConnectionPtr->url = urlWebsocketBase;
wsConnectionPtr->setUrl(urlWebsocketBase);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"pingInterval", std::string(instanceServer["pingInterval"].GetString())},
@@ -118,7 +118,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
@@ -146,6 +146,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
preSignedText += req.base().at("KC-API-KEY").to_string();
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, CCAPI_KUCOIN_API_PARTNER_PRIVATE_KEY, preSignedText));
req.set("KC-API-PARTNER-SIGN", signature);
req.set("KC-API-PARTNER-VERIFY", "true");
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
@@ -202,7 +203,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
req.set("KC-API-KEY", apiKey);
req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
// auto apiKeyVersion = mapGetWithDefault(credential, this->apiKeyVersionName);
req.set("KC-API-KEY-VERSION", "2");
req.set("KC-API-KEY-VERSION", "3");
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
this->signApiPassphrase(req, apiPassphrase, apiSecret);
@@ -332,7 +333,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -371,8 +372,8 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
elementList.emplace_back(std::move(element));
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it = x.FindMember("isActive");
@@ -407,7 +408,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -430,7 +431,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -483,7 +484,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
std::map<std::string, std::pair<std::string, JsonDataType> > extractionFieldNameMap = {
std::map<std::string, std::pair<std::string, JsonDataType>> extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -519,16 +520,16 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else if (type == "welcome") {
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval"));
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout"));
if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
if (this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ExecutionManagementService::onOpen(hdl);
#else
ExecutionManagementService::onOpen(wsConnectionPtr);
@@ -12,12 +12,12 @@ class ExecutionManagementServiceKucoinFutures : public ExecutionManagementServic
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -15,19 +15,19 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_MEXC_API_KEY;
this->apiSecretName = CCAPI_MEXC_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -45,7 +45,7 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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<WsConnection> wsConnectionPtr, ErrorCode& ec) override {
@@ -226,7 +226,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
@@ -274,7 +274,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
void onOpen(wspp::connection_hdl hdl) override {
ExecutionManagementService::onOpen(hdl);
@@ -318,7 +318,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
[wsConnection, that_2 = that->shared_from_base<ExecutionManagementServiceMexc>()](const http::response<http::string_body>& res) {
CCAPI_LOGGER_DEBUG("ping listen key success");
},
that->sessionOptions.httpRequestTimeoutMilliSeconds);
that->sessionOptions.httpRequestTimeoutMilliseconds);
});
}
void onClose(wspp::connection_hdl hdl) override {
@@ -360,7 +360,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
std::string listenKey = document["listenKey"].GetString();
std::string url = that->baseUrlWs + "?listenKey=" + listenKey;
wsConnectionPtr->url = url;
wsConnectionPtr->setUrl(url);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"listenKey", listenKey},
@@ -372,7 +372,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
ExecutionManagementService::onOpen(wsConnectionPtr);
@@ -416,7 +416,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
[wsConnectionPtr, that_2 = that->shared_from_base<ExecutionManagementServiceMexc>()](const http::response<http::string_body>& res) {
CCAPI_LOGGER_DEBUG("ping listen key success");
},
that->sessionOptions.httpRequestTimeoutMilliSeconds);
that->sessionOptions.httpRequestTimeoutMilliseconds);
});
this->pingListenKeyTimerMapByConnectionIdMap[wsConnectionPtr->id] = timerPtr;
}
@@ -454,7 +454,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -477,7 +477,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -14,19 +14,19 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_MEXC_FUTURES_API_KEY;
this->apiSecretName = CCAPI_MEXC_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -45,7 +45,7 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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<WsConnection> wsConnectionPtr, ErrorCode& ec) override {
@@ -319,8 +319,8 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
// CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
// }
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
// ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
// {
// auto it1 = x.FindMember("accFillSz");
@@ -329,7 +329,8 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
// auto it1Str = std::string(it1->value.GetString());
// auto it2Str = std::string(it2->value.GetString());
// if (!it1Str.empty() && !it2Str.empty()) {
// element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
// element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, Decimal(UtilString::printDoubleScientific(std::stod(it1Str) *
// std::stod(it2Str))).toString());
// }
// }
// }
@@ -364,7 +365,7 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
}
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const TimePoint& timeReceived) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -401,7 +402,7 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
// document.Accept(writerSubscribe);
// std::string sendString = stringBufferSubscribe.GetString();
// ErrorCode ec;
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -3,6 +3,7 @@
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_OKX
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceOkx : public ExecutionManagementService {
public:
@@ -14,19 +15,19 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_OKX_API_KEY;
this->apiSecretName = CCAPI_OKX_API_SECRET;
this->apiPassphraseName = CCAPI_OKX_API_PASSPHRASE;
@@ -39,17 +40,19 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
this->getAccountBalancesTarget = "/api/v5/account/balance";
this->getAccountPositionsTarget = "/api/v5/account/positions";
}
virtual ~ExecutionManagementServiceOkx() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
#endif
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); }
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& 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<std::string, std::string>& credential) override {
@@ -68,6 +71,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
}
headerString += "OK-ACCESS-SIGN:" + signature;
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("OK-ACCESS-TIMESTAMP").to_string();
@@ -79,6 +83,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
req.body() = body;
req.prepare_payload();
}
void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_ORDER_SIDE, "side"},
@@ -100,6 +105,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
rjValue.AddMember("tag", CCAPI_OKX_API_BROKER_CODE, allocator);
}
}
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
@@ -109,21 +115,24 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
queryString += "&";
}
}
void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
rjValue.AddMember("instId", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
void appendSymbolId(std::string& queryString, const std::string& symbolId) {
queryString += "instId=";
queryString += Url::urlEncode(symbolId);
queryString += "&";
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
req.set(beast::http::field::content_type, "application/json");
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("OK-ACCESS-KEY", apiKey);
std::string timeStr = UtilTime::getISOTimestamp(now);
req.set("OK-ACCESS-TIMESTAMP", timeStr.substr(0, timeStr.length() - 7) + "Z");
std::string timeStr = UtilTime::getISOTimestamp<std::chrono::milliseconds>(now);
req.set("OK-ACCESS-TIMESTAMP", timeStr);
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
req.set("OK-ACCESS-PASSPHRASE", apiPassphrase);
auto apiXSimulatedTrading = mapGetWithDefault(credential, this->apiXSimulatedTradingName);
@@ -226,6 +235,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void convertRequestForWebsocket(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, const Request& request,
int wsRequestId, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
@@ -269,12 +279,14 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
this->convertRequestForWebsocketCustom(document, allocator, wsConnection, request, wsRequestId, now, symbolId, credential);
}
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
this->extractOrderInfoFromRequest(elementList, document);
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const rj::Document& document) {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& 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)},
@@ -296,6 +308,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
}
}
}
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
switch (request.getOperation()) {
@@ -305,7 +318,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
element.insert(CCAPI_EM_ASSET, x["ccy"].GetString());
std::string availEq = x["availEq"].GetString();
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, availEq.empty() ? x["availBal"].GetString() : availEq);
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["eq"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["cashBal"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -326,8 +339,9 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("accFillSz");
@@ -336,11 +350,13 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
auto it1Str = std::string(it1->value.GetString());
auto it2Str = std::string(it2->value.GetString());
if (!it1Str.empty() && !it2Str.empty()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))).toString());
}
}
}
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::vector<std::string> sendStringList;
@@ -369,15 +385,16 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
void onTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
std::string textMessage(textMessageView);
#endif
@@ -394,15 +411,40 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
rj::Value args(rj::kArrayType);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
std::string channel;
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
channel = "orders";
if (instrumentSet.empty()) {
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("orders").Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
args.PushBack(arg, allocator);
}
if (fieldSet.find(CCAPI_EM_POSITION_UPDATE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("positions").Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
args.PushBack(arg, allocator);
}
} else {
for (const auto& instrument : instrumentSet) {
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("orders").Move(), allocator);
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
args.PushBack(arg, allocator);
}
if (fieldSet.find(CCAPI_EM_POSITION_UPDATE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("positions").Move(), allocator);
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
args.PushBack(arg, allocator);
}
}
}
for (const auto& instrument : instrumentSet) {
if (fieldSet.find(CCAPI_EM_BALANCE_UPDATE) != fieldSet.end()) {
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("ANY").Move(), allocator);
arg.AddMember("channel", rj::Value("balance_and_position").Move(), allocator);
args.PushBack(arg, allocator);
}
document.AddMember("args", args, allocator);
@@ -411,8 +453,8 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -431,6 +473,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
}
}
}
Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr,
const TimePoint& timeReceived) {
Event event;
@@ -475,64 +518,98 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
const rj::Value& data = document["data"];
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()) {
for (const auto& x : data.GetArray()) {
std::string tradeId = x["tradeId"].GetString();
if (!tradeId.empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, tradeId);
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString()));
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_EM_POSITION_SIDE, std::string(x["posSide"].GetString()));
element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString()));
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
for (const auto& x : data.GetArray()) {
if (channel == "orders") {
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
for (const auto& x : data.GetArray()) {
std::string tradeId = x["tradeId"].GetString();
if (!tradeId.empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE, std::make_pair("avgPx", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> 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_EM_POSITION_SIDE, std::string(x["posSide"].GetString()));
element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, x["instId"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString()));
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
for (const auto& x : data.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE, std::make_pair("avgPx", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FEE_QUANTITY, std::make_pair("fee", JsonDataType::STRING)},
{CCAPI_EM_ORDER_FEE_ASSET, std::make_pair("feeCcy", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("instId", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
} else if (channel == "balance_and_position") {
for (const auto& x : data.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["pTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE);
std::vector<Element> elementList;
for (const auto& y : x["balData"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, y["ccy"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, y["cashBal"].GetString());
elementList.emplace_back(std::move(element));
}
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (channel == "positions") {
for (const auto& x : data.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["uTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_INSTRUMENT, x["instId"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["posSide"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["pos"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPx"].GetString());
element.insert(CCAPI_EM_UNREALIZED_PNL, x["upl"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (eventStr == "subscribe") {
@@ -553,6 +630,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
event.setMessageList(messageList);
return event;
}
std::string apiPassphraseName;
std::string apiXSimulatedTradingName;
};
@@ -11,11 +11,11 @@
#include "hffix.hpp"
namespace hff = hffix;
namespace ccapi {
template <class T>
/**
* Defines a service which provides access to exchange API and normalizes them. This is a base class that implements generic functionalities for dealing with
* exchange FIX APIs. The Session object is responsible for routing requests and subscriptions to the desired concrete service.
*/
template <class T>
class FixService : public Service {
public:
FixService(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
@@ -105,7 +105,7 @@ class FixService : public Service {
});
this->connectRetryOnFailTimerByConnectionIdMap[fixConnectionPtr->id] = timerPtr;
}
std::shared_ptr<T> createStreamFix(std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host);
std::shared_ptr<T> createStreamFix(net::io_context* iocPtr, net::ssl::context* ctxPtr, const std::string& host);
void connect(Subscription& subscription) {
std::string aHostFix = this->hostFix;
std::string aPortFix = this->portFix;
@@ -454,11 +454,11 @@ class FixService : public Service {
std::function<void(std::shared_ptr<FixConnection<T>>)> pingMethod, bool pingNow = false) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method));
auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method];
auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds));
if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) {
auto pingIntervalMilliseconds = this->pingIntervalMillisecondsByMethodMap[method];
auto pongTimeoutMilliseconds = this->pongTimeoutMillisecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliseconds = " + toString(pingIntervalMilliseconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliseconds = " + toString(pongTimeoutMilliseconds));
if (pingIntervalMilliseconds <= pongTimeoutMilliseconds) {
return;
}
if (fixConnectionPtr->status == FixConnection<T>::Status::OPEN) {
@@ -471,8 +471,8 @@ class FixService : public Service {
this->pingTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)->cancel();
}
TimerPtr timerPtr(
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds)));
timerPtr->async_wait([fixConnectionPtr, that = shared_from_base<FixService>(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliseconds - pongTimeoutMilliseconds)));
timerPtr->async_wait([fixConnectionPtr, that = shared_from_base<FixService>(), 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());
@@ -484,7 +484,7 @@ class FixService : public Service {
if (ec) {
that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "ping");
}
if (pongTimeoutMilliSeconds <= 0) {
if (pongTimeoutMilliseconds <= 0) {
return;
}
if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(fixConnectionPtr->id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() &&
@@ -492,8 +492,8 @@ class FixService : public Service {
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) {
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());
@@ -506,7 +506,7 @@ class FixService : public Service {
that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).end() &&
std::chrono::duration_cast<std::chrono::milliseconds>(now -
that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method))
.count() >= pongTimeoutMilliSeconds) {
.count() >= pongTimeoutMilliseconds) {
auto thisFixConnectionPtr = fixConnectionPtr;
that->onFail(fixConnectionPtr, "pong timeout");
} else {
@@ -558,8 +558,9 @@ class FixService : public Service {
std::string targetCompID;
};
template <>
inline std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> FixService<beast::ssl_stream<beast::tcp_stream>>::createStreamFix(
std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host) {
inline std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> FixService<beast::ssl_stream<beast::tcp_stream>>::createStreamFix(net::io_context* iocPtr,
net::ssl::context* ctxPtr,
const std::string& host) {
std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(new beast::ssl_stream<beast::tcp_stream>(*iocPtr, *ctxPtr));
// Set SNI Hostname (many hosts need this to handshake successfully)
if (!SSL_set_tlsext_host_name(streamPtr->native_handle(), host.c_str())) {
@@ -570,8 +571,8 @@ inline std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> FixService<beast::s
return streamPtr;
}
template <>
inline std::shared_ptr<beast::tcp_stream> FixService<beast::tcp_stream>::createStreamFix(std::shared_ptr<net::io_context> iocPtr,
std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host) {
inline std::shared_ptr<beast::tcp_stream> FixService<beast::tcp_stream>::createStreamFix(net::io_context* iocPtr, net::ssl::context* ctxPtr,
const std::string& host) {
std::shared_ptr<beast::tcp_stream> streamPtr(new beast::tcp_stream(*iocPtr));
return streamPtr;
}
@@ -44,7 +44,7 @@ class FixServiceCoinbase : public FixService<beast::ssl_stream<beast::tcp_stream
auto msgType = "A";
param.push_back({hff::tag::MsgType, msgType});
param.push_back({hff::tag::EncryptMethod, "0"});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliSeconds / 1000)});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliseconds / 1000)});
auto credential = this->credentialByConnectionIdMap[connectionId];
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
param.push_back({hff::tag::Password, apiPassphrase});
@@ -41,7 +41,7 @@ class FixServiceGemini : public FixService<beast::tcp_stream> {
param.push_back({hff::tag::MsgType, msgType});
param.push_back({hff::tag::ResetSeqNumFlag, "Y"});
param.push_back({hff::tag::EncryptMethod, "0"});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliSeconds / 1000)});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliseconds / 1000)});
for (const auto& x : logonOptionMap) {
param.push_back({x.first, x.second});
}
@@ -17,12 +17,17 @@ namespace ccapi {
class MarketDataService : public Service {
public:
MarketDataService(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: Service(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
CCAPI_LOGGER_FUNCTION_ENTER;
this->requestOperationToMessageTypeMap = {
{Request::Operation::GET_RECENT_TRADES, Message::Type::GET_RECENT_TRADES},
{Request::Operation::GET_HISTORICAL_TRADES, Message::Type::GET_HISTORICAL_TRADES},
{Request::Operation::GET_RECENT_AGG_TRADES, Message::Type::GET_RECENT_AGG_TRADES},
{Request::Operation::GET_HISTORICAL_AGG_TRADES, Message::Type::GET_HISTORICAL_AGG_TRADES},
{Request::Operation::GET_RECENT_CANDLESTICKS, Message::Type::GET_RECENT_CANDLESTICKS},
{Request::Operation::GET_HISTORICAL_CANDLESTICKS, Message::Type::GET_HISTORICAL_CANDLESTICKS},
{Request::Operation::GET_MARKET_DEPTH, Message::Type::GET_MARKET_DEPTH},
{Request::Operation::GET_INSTRUMENT, Message::Type::GET_INSTRUMENT},
{Request::Operation::GET_INSTRUMENTS, Message::Type::GET_INSTRUMENTS},
};
@@ -42,7 +47,7 @@ class MarketDataService : public Service {
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// subscriptions are grouped and each group creates a unique websocket connection
void subscribe(std::vector<Subscription>& subscriptionList) override {
CCAPI_LOGGER_FUNCTION_ENTER;
@@ -131,13 +136,12 @@ class MarketDataService : public Service {
}
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = that->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(
that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs);
streamPtr = that->createWsStream(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr);
} catch (const beast::error_code& ec) {
CCAPI_LOGGER_TRACE("fail");
std::vector<std::string> correlationIdList;
correlationIdList.reserve(subscriptionListGivenInstrumentGroup.size());
std::transform(subscriptionListGivenInstrumentGroup.cbegin(), subscriptionListGivenInstrumentGroup.cend(), correlationIdList.begin(),
std::transform(subscriptionListGivenInstrumentGroup.cbegin(), subscriptionListGivenInstrumentGroup.cend(), std::back_inserter(correlationIdList),
[](Subscription subscription) { return subscription.getCorrelationId(); });
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", correlationIdList);
return;
@@ -156,7 +160,7 @@ class MarketDataService : public Service {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
typedef wspp::lib::error_code ErrorCode;
typedef wspp::lib::function<void(ErrorCode const&)> TimerHandler;
#else
@@ -171,7 +175,12 @@ class MarketDataService : public Service {
return groups;
}
virtual std::string getInstrumentGroup(const Subscription& subscription) {
return this->baseUrlWs + "|" + subscription.getField() + "|" + subscription.getSerializedOptions() + "|" + subscription.getSerializedCredential();
const auto& field = subscription.getField();
if (field == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) {
return this->baseUrlWs + "|" + subscription.getField() + "|" + subscription.getCorrelationId() + "|" + subscription.getSerializedCredential();
} else {
return this->baseUrlWs + "|" + subscription.getField() + "|" + subscription.getSerializedOptions() + "|" + subscription.getSerializedCredential();
}
}
void prepareSubscription(const WsConnection& wsConnection, const Subscription& subscription) {
auto instrument = subscription.getInstrument();
@@ -196,7 +205,7 @@ class MarketDataService : public Service {
CCAPI_LOGGER_TRACE("this->correlationIdListByConnectionIdChannelSymbolIdMap = " + toString(this->correlationIdListByConnectionIdChannelIdSymbolIdMap));
CCAPI_LOGGER_FUNCTION_EXIT;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void processMarketDataMessageList(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
Event& event, std::vector<MarketDataMessage>& marketDataMessageList) {
CCAPI_LOGGER_TRACE("marketDataMessageList = " + toString(marketDataMessageList));
@@ -205,9 +214,9 @@ class MarketDataService : public Service {
if (marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE) {
if (this->sessionOptions.warnLateEventMaxMilliSeconds > 0 &&
if (this->sessionOptions.warnLateEventMaxMilliseconds > 0 &&
std::chrono::duration_cast<std::chrono::milliseconds>(timeReceived - marketDataMessage.tp).count() >
this->sessionOptions.warnLateEventMaxMilliSeconds &&
this->sessionOptions.warnLateEventMaxMilliseconds &&
marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) {
CCAPI_LOGGER_WARN("late websocket message: timeReceived = " + toString(timeReceived) + ", marketDataMessage.tp = " + toString(marketDataMessage.tp) +
", wsConnection = " + toString(wsConnection));
@@ -308,7 +317,7 @@ class MarketDataService : public Service {
event.setMessageList({message});
this->eventHandler(event, nullptr);
}
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived, false);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
@@ -391,7 +400,7 @@ class MarketDataService : public Service {
void onClose(wspp::connection_hdl hdl) override {
CCAPI_LOGGER_FUNCTION_ENTER;
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.erase(wsConnection.id);
this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id);
this->correlationIdByConnectionIdMap.erase(wsConnection.id);
@@ -409,7 +418,7 @@ class MarketDataService : public Service {
for (const auto& sendString : sendStringList) {
CCAPI_LOGGER_INFO("sendString = " + sendString);
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -441,7 +450,7 @@ class MarketDataService : public Service {
for (const auto& sendString : sendStringList) {
CCAPI_LOGGER_INFO("sendString = " + sendString);
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -460,27 +469,35 @@ class MarketDataService : public Service {
for (auto& marketDataMessage : marketDataMessageList) {
if (marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE) {
if (this->sessionOptions.warnLateEventMaxMilliSeconds > 0 &&
std::chrono::duration_cast<std::chrono::milliseconds>(timeReceived - marketDataMessage.tp).count() >
this->sessionOptions.warnLateEventMaxMilliSeconds &&
marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) {
CCAPI_LOGGER_WARN("late websocket message: timeReceived = " + toString(timeReceived) + ", marketDataMessage.tp = " + toString(marketDataMessage.tp) +
", wsConnection = " + toString(wsConnection));
}
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK) {
// if (this->sessionOptions.warnLateEventMaxMilliseconds > 0 &&
// std::chrono::duration_cast<std::chrono::milliseconds>(timeReceived - marketDataMessage.tp).count() >
// this->sessionOptions.warnLateEventMaxMilliseconds &&
// marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) {
// CCAPI_LOGGER_WARN("late websocket message: timeReceived = " + toString(timeReceived) + ", marketDataMessage.tp = " + toString(marketDataMessage.tp)
// +
// ", wsConnection = " + toString(wsConnection));
// }
std::string& exchangeSubscriptionId = marketDataMessage.exchangeSubscriptionId;
CCAPI_LOGGER_TRACE("this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap = " +
toString(this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap));
CCAPI_LOGGER_TRACE("this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id) = " +
toString(this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id)));
CCAPI_LOGGER_TRACE("exchangeSubscriptionId = " + exchangeSubscriptionId);
std::string& channelId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
CCAPI_LOGGER_TRACE("channelId = " + toString(channelId));
std::string& symbolId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
CCAPI_LOGGER_TRACE("symbolId = " + toString(symbolId));
CCAPI_LOGGER_TRACE("this->fieldByConnectionIdChannelIdSymbolIdMap = " + toString(this->fieldByConnectionIdChannelIdSymbolIdMap));
CCAPI_LOGGER_TRACE("this->fieldByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id) = " +
toString(this->fieldByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)));
auto& field = this->fieldByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
CCAPI_LOGGER_TRACE("this->optionMapByConnectionIdChannelIdSymbolIdMap = " + toString(this->optionMapByConnectionIdChannelIdSymbolIdMap));
CCAPI_LOGGER_TRACE("wsConnection = " + toString(wsConnection));
CCAPI_LOGGER_TRACE("channelId = " + toString(channelId));
CCAPI_LOGGER_TRACE("symbolId = " + toString(symbolId));
auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
CCAPI_LOGGER_TRACE("optionMap = " + toString(optionMap));
auto& correlationIdList = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
@@ -532,6 +549,11 @@ class MarketDataService : public Service {
this->processTrade(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field, optionMap,
correlationIdList, isSolicited);
}
if (marketDataMessage.data.find(MarketDataMessage::DataType::CANDLESTICK) != marketDataMessage.data.end()) {
bool isSolicited = marketDataMessage.recapType == MarketDataMessage::RecapType::SOLICITED;
this->processExchangeProvidedCandlestick(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field,
optionMap, correlationIdList, isSolicited);
}
} else {
CCAPI_LOGGER_WARN("websocket event type is unknown for " + toString(marketDataMessage));
CCAPI_LOGGER_WARN("textMessage is " + std::string(textMessage));
@@ -563,13 +585,12 @@ class MarketDataService : public Service {
event.setMessageList({message});
this->eventHandler(event, nullptr);
}
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived, false);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void onIncorrectStatesFound(std::shared_ptr<WsConnection> 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(textMessageView) +
std::string errorMessage = "incorrect states found: connection = " + toString(*wsConnectionPtr) + ", textMessage = " + std::string(textMessageView) +
", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId +
", reason = " + reason;
CCAPI_LOGGER_ERROR(errorMessage);
@@ -577,9 +598,17 @@ class MarketDataService : public Service {
this->close(wsConnectionPtr, beast::websocket::close_code::normal,
beast::websocket::close_reason(beast::websocket::close_code::normal, "incorrect states found: " + reason), ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, "shutdown");
std::string& channelId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnectionPtr->id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
std::string& symbolId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnectionPtr->id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
CCAPI_LOGGER_TRACE("channelId = " + toString(channelId));
CCAPI_LOGGER_TRACE("symbolId = " + toString(symbolId));
auto& correlationIdList = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnectionPtr->id).at(channelId).at(symbolId);
CCAPI_LOGGER_TRACE("correlationIdList = " + toString(correlationIdList));
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, "shutdown", correlationIdList);
}
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false;
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, errorMessage);
}
void connect(std::shared_ptr<WsConnection> wsConnectionPtr) override {
@@ -651,7 +680,7 @@ class MarketDataService : public Service {
virtual void onClose(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode ec) override {
CCAPI_LOGGER_FUNCTION_ENTER;
WsConnection& wsConnection = *wsConnectionPtr;
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.erase(wsConnection.id);
this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id);
this->correlationIdByConnectionIdMap.erase(wsConnection.id);
@@ -682,10 +711,10 @@ class MarketDataService : public Service {
for (const auto& subscription : wsConnection.subscriptionList) {
auto instrument = subscription.getInstrument();
this->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING;
if (subscription.getRawOptions().empty()) {
this->prepareSubscription(wsConnection, subscription);
} else {
if (subscription.getField() == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) {
this->correlationIdByConnectionIdMap.insert({wsConnection.id, subscription.getCorrelationId()});
} else {
this->prepareSubscription(wsConnection, subscription);
}
}
CCAPI_LOGGER_INFO("about to subscribe to exchange");
@@ -766,6 +795,45 @@ class MarketDataService : public Service {
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
void updateElementListWithOrderBookSnapshot(const std::string& field, int maxMarketDepth, const std::map<Decimal, std::string>& snapshotBid,
const std::map<Decimal, std::string>& snapshotAsk, std::vector<Element>& elementList) {
CCAPI_LOGGER_FUNCTION_ENTER;
if (field == CCAPI_MARKET_DEPTH) {
int bidIndex = 0;
for (auto iter = snapshotBid.rbegin(); iter != snapshotBid.rend(); iter++) {
if (bidIndex < maxMarketDepth) {
Element element;
element.insert(CCAPI_BEST_BID_N_PRICE, iter->first.toString());
element.insert(CCAPI_BEST_BID_N_SIZE, iter->second);
elementList.emplace_back(std::move(element));
}
++bidIndex;
}
if (snapshotBid.empty()) {
Element element;
element.insert(CCAPI_BEST_BID_N_PRICE, CCAPI_BEST_BID_N_PRICE_EMPTY);
element.insert(CCAPI_BEST_BID_N_SIZE, CCAPI_BEST_BID_N_SIZE_EMPTY);
elementList.emplace_back(std::move(element));
}
int askIndex = 0;
for (auto iter = snapshotAsk.begin(); iter != snapshotAsk.end(); iter++) {
if (askIndex < maxMarketDepth) {
Element element;
element.insert(CCAPI_BEST_ASK_N_PRICE, iter->first.toString());
element.insert(CCAPI_BEST_ASK_N_SIZE, iter->second);
elementList.emplace_back(std::move(element));
}
++askIndex;
}
if (snapshotAsk.empty()) {
Element element;
element.insert(CCAPI_BEST_ASK_N_PRICE, CCAPI_BEST_ASK_N_PRICE_EMPTY);
element.insert(CCAPI_BEST_ASK_N_SIZE, CCAPI_BEST_ASK_N_SIZE_EMPTY);
elementList.emplace_back(std::move(element));
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
std::map<Decimal, std::string> calculateMarketDepthUpdate(bool isBid, const std::map<Decimal, std::string>& c1, const std::map<Decimal, std::string>& c2,
int maxMarketDepth) {
if (c1.empty()) {
@@ -936,8 +1004,8 @@ class MarketDataService : public Service {
Element element;
std::string k1(CCAPI_LAST_PRICE);
std::string k2(CCAPI_LAST_SIZE);
element.emplace(k1, y.at(MarketDataMessage::DataFieldType::PRICE));
element.emplace(k2, y.at(MarketDataMessage::DataFieldType::SIZE));
element.emplace(k1, price);
element.emplace(k2, size);
{
auto it = y.find(MarketDataMessage::DataFieldType::TRADE_ID);
if (it != y.end()) {
@@ -969,20 +1037,62 @@ class MarketDataService : public Service {
}
}
}
void updateElementListWithOhlc(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, const std::string& field,
std::vector<Element>& elementList) {
void updateElementListWithExchangeProvidedCandlestick(const std::string& field, MarketDataMessage::TypeForData& input, std::vector<Element>& elementList) {
if (field == CCAPI_CANDLESTICK) {
for (auto& x : input) {
auto& type = x.first;
auto& detail = x.second;
if (type == MarketDataMessage::DataType::CANDLESTICK) {
for (auto& y : detail) {
auto& openPrice = y.at(MarketDataMessage::DataFieldType::OPEN_PRICE);
auto& highPrice = y.at(MarketDataMessage::DataFieldType::HIGH_PRICE);
auto& lowPrice = y.at(MarketDataMessage::DataFieldType::LOW_PRICE);
auto& closePrice = y.at(MarketDataMessage::DataFieldType::CLOSE_PRICE);
Element element;
std::string k1(CCAPI_OPEN_PRICE);
std::string k2(CCAPI_HIGH_PRICE);
std::string k3(CCAPI_LOW_PRICE);
std::string k4(CCAPI_CLOSE_PRICE);
element.emplace(k1, y.at(MarketDataMessage::DataFieldType::OPEN_PRICE));
element.emplace(k2, y.at(MarketDataMessage::DataFieldType::HIGH_PRICE));
element.emplace(k3, y.at(MarketDataMessage::DataFieldType::LOW_PRICE));
element.emplace(k4, y.at(MarketDataMessage::DataFieldType::CLOSE_PRICE));
{
auto it = y.find(MarketDataMessage::DataFieldType::VOLUME);
if (it != y.end()) {
std::string k(CCAPI_VOLUME);
element.emplace(k, it->second);
}
}
{
auto it = y.find(MarketDataMessage::DataFieldType::QUOTE_VOLUME);
if (it != y.end()) {
std::string k(CCAPI_QUOTE_VOLUME);
element.emplace(k, it->second);
}
}
elementList.emplace_back(std::move(element));
}
} else {
CCAPI_LOGGER_WARN("extra type " + MarketDataMessage::dataTypeToString(type));
}
}
}
}
void updateElementListWithCalculatedCandlestick(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId,
const std::string& field, std::vector<Element>& elementList) {
if (field == CCAPI_TRADE || field == CCAPI_AGG_TRADE) {
Element element;
if (this->openByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].empty()) {
element.insert(CCAPI_OPEN, CCAPI_OHLC_EMPTY);
element.insert(CCAPI_HIGH, CCAPI_OHLC_EMPTY);
element.insert(CCAPI_LOW, CCAPI_OHLC_EMPTY);
element.insert(CCAPI_CLOSE, CCAPI_OHLC_EMPTY);
element.insert(CCAPI_OPEN_PRICE, CCAPI_CANDLESTICK_EMPTY);
element.insert(CCAPI_HIGH_PRICE, CCAPI_CANDLESTICK_EMPTY);
element.insert(CCAPI_LOW_PRICE, CCAPI_CANDLESTICK_EMPTY);
element.insert(CCAPI_CLOSE_PRICE, CCAPI_CANDLESTICK_EMPTY);
} else {
element.insert(CCAPI_OPEN, this->openByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]);
element.insert(CCAPI_HIGH, this->highByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].toString());
element.insert(CCAPI_LOW, this->lowByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].toString());
element.insert(CCAPI_CLOSE, this->closeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]);
element.insert(CCAPI_OPEN_PRICE, this->openByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]);
element.insert(CCAPI_HIGH_PRICE, this->highByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].toString());
element.insert(CCAPI_LOW_PRICE, this->lowByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].toString());
element.insert(CCAPI_CLOSE_PRICE, this->closeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]);
}
elementList.emplace_back(std::move(element));
this->openByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = "";
@@ -1221,7 +1331,7 @@ class MarketDataService : public Service {
std::vector<Message> messageList;
std::vector<Element> elementList;
if (shouldConflate && intervalChanged) {
this->updateElementListWithOhlc(wsConnection, channelId, symbolId, field, elementList);
this->updateElementListWithCalculatedCandlestick(wsConnection, channelId, symbolId, field, elementList);
} else {
this->updateElementListWithTrade(field, input, elementList);
}
@@ -1243,14 +1353,53 @@ class MarketDataService : public Service {
}
if (shouldConflate) {
this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId) = conflateTp;
this->updateOhlc(wsConnection, channelId, symbolId, field, input);
this->updateCalculatedCandlestick(wsConnection, channelId, symbolId, field, input);
}
} else {
this->updateOhlc(wsConnection, channelId, symbolId, field, input);
this->updateCalculatedCandlestick(wsConnection, channelId, symbolId, field, input);
}
}
void updateOhlc(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, const std::string& field,
const MarketDataMessage::TypeForData& input) {
void processExchangeProvidedCandlestick(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, Event& event,
const TimePoint& tp, const TimePoint& timeReceived, MarketDataMessage::TypeForData& input, const std::string& field,
const std::map<std::string, std::string>& optionMap, const std::vector<std::string>& correlationIdList,
bool isSolicited) {
std::vector<Message> messageList;
std::vector<Element> elementList;
this->updateElementListWithExchangeProvidedCandlestick(field, input, elementList);
if (!elementList.empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setType(Message::Type::MARKET_DATA_EVENTS_CANDLESTICK);
message.setRecapType(isSolicited ? Message::RecapType::SOLICITED : Message::RecapType::NONE);
message.setTime(tp);
message.setElementList(elementList);
message.setCorrelationIdList(correlationIdList);
messageList.emplace_back(std::move(message));
}
if (!messageList.empty()) {
event.addMessages(messageList);
}
}
void processExchangeProvidedCandlestick(Event& event, const TimePoint& tp, const TimePoint& timeReceived, MarketDataMessage::TypeForData& input,
const std::vector<std::string>& correlationIdList, Message::Type messageType) {
std::vector<Message> messageList;
std::vector<Element> elementList;
this->updateElementListWithExchangeProvidedCandlestick(CCAPI_CANDLESTICK, input, elementList);
if (!elementList.empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setType(Message::Type::MARKET_DATA_EVENTS_CANDLESTICK);
message.setTime(tp);
message.setElementList(elementList);
message.setCorrelationIdList(correlationIdList);
messageList.emplace_back(std::move(message));
}
if (!messageList.empty()) {
event.addMessages(messageList);
}
}
void updateCalculatedCandlestick(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, const std::string& field,
const MarketDataMessage::TypeForData& input) {
if (field == CCAPI_TRADE || field == CCAPI_AGG_TRADE) {
for (const auto& x : input) {
auto type = x.first;
@@ -1327,7 +1476,7 @@ class MarketDataService : public Service {
}
return true;
}
int calculateMarketDepthSubscribedToExchange(int depthWanted, std::vector<int> availableMarketDepth) {
int calculateMarketDepthAllowedByExchange(int depthWanted, std::vector<int> availableMarketDepth) {
int i = ceilSearch(availableMarketDepth, 0, availableMarketDepth.size(), depthWanted);
if (i < 0) {
i = availableMarketDepth.size() - 1;
@@ -1374,7 +1523,7 @@ class MarketDataService : public Service {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
if (
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN
#else
this->wsConnectionByIdMap.at(wsConnection.id)->status == WsConnection::Status::OPEN
@@ -1391,7 +1540,7 @@ class MarketDataService : public Service {
this->updateElementListWithUpdateMarketDepth(field, optionMap, snapshotBid, std::map<Decimal, std::string>(), snapshotAsk,
std::map<Decimal, std::string>(), elementList, true);
} else if (field == CCAPI_TRADE || field == CCAPI_AGG_TRADE) {
this->updateElementListWithOhlc(wsConnection, channelId, symbolId, field, elementList);
this->updateElementListWithCalculatedCandlestick(wsConnection, channelId, symbolId, field, elementList);
}
CCAPI_LOGGER_TRACE("elementList = " + toString(elementList));
this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId) = conflateTp;
@@ -1474,13 +1623,24 @@ class MarketDataService : public Service {
for (auto& marketDataMessage : marketDataMessageList) {
if (marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE) {
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK) {
const std::vector<std::string>& correlationIdList = {request.getCorrelationId()};
CCAPI_LOGGER_TRACE("correlationIdList = " + toString(correlationIdList));
if (marketDataMessage.data.find(MarketDataMessage::DataType::TRADE) != marketDataMessage.data.end() ||
marketDataMessage.data.find(MarketDataMessage::DataType::AGG_TRADE) != marketDataMessage.data.end()) {
if (marketDataMessage.data.find(MarketDataMessage::DataType::BID) != marketDataMessage.data.end() ||
marketDataMessage.data.find(MarketDataMessage::DataType::ASK) != marketDataMessage.data.end()) {
auto messageType = this->requestOperationToMessageTypeMap.at(request.getOperation());
const auto& param = request.getFirstParamWithDefault();
const auto& maxMarketDepthStr = mapGetWithDefault(param, std::string(CCAPI_MARKET_DEPTH_MAX));
int maxMarketDepth = maxMarketDepthStr.empty() ? INT_MAX : std::stoi(maxMarketDepthStr);
this->processOrderBookSnapshot(event, marketDataMessage.tp, timeReceived, marketDataMessage.data, correlationIdList, messageType, maxMarketDepth);
} else if (marketDataMessage.data.find(MarketDataMessage::DataType::TRADE) != marketDataMessage.data.end() ||
marketDataMessage.data.find(MarketDataMessage::DataType::AGG_TRADE) != marketDataMessage.data.end()) {
auto messageType = this->requestOperationToMessageTypeMap.at(request.getOperation());
this->processTrade(event, marketDataMessage.tp, timeReceived, marketDataMessage.data, correlationIdList, messageType);
} else if (marketDataMessage.data.find(MarketDataMessage::DataType::CANDLESTICK) != marketDataMessage.data.end()) {
auto messageType = this->requestOperationToMessageTypeMap.at(request.getOperation());
this->processExchangeProvidedCandlestick(event, marketDataMessage.tp, timeReceived, marketDataMessage.data, correlationIdList, messageType);
}
} else {
CCAPI_LOGGER_WARN("market data event type is unknown!");
@@ -1503,6 +1663,45 @@ class MarketDataService : public Service {
messageList.emplace_back(std::move(message));
event.addMessages(messageList);
}
void processOrderBookSnapshot(Event& event, const TimePoint& tp, const TimePoint& timeReceived, MarketDataMessage::TypeForData& input,
const std::vector<std::string>& correlationIdList, Message::Type messageType, int maxMarketDepth) {
std::vector<Message> messageList;
std::vector<Element> elementList;
std::map<Decimal, std::string> snapshotBid, snapshotAsk;
for (auto& x : input) {
auto& type = x.first;
auto& detail = x.second;
if (type == MarketDataMessage::DataType::BID) {
for (auto& y : detail) {
auto& price = y.at(MarketDataMessage::DataFieldType::PRICE);
auto& size = y.at(MarketDataMessage::DataFieldType::SIZE);
Decimal decimalPrice(price, this->sessionOptions.enableCheckOrderBookChecksum);
snapshotBid.emplace(std::move(decimalPrice), std::move(size));
}
CCAPI_LOGGER_TRACE("lastNToString(snapshotBid, " + toString(maxMarketDepth) + ") = " + lastNToString(snapshotBid, maxMarketDepth));
} else if (type == MarketDataMessage::DataType::ASK) {
for (auto& y : detail) {
auto& price = y.at(MarketDataMessage::DataFieldType::PRICE);
auto& size = y.at(MarketDataMessage::DataFieldType::SIZE);
Decimal decimalPrice(price, this->sessionOptions.enableCheckOrderBookChecksum);
snapshotAsk.emplace(std::move(decimalPrice), std::move(size));
}
CCAPI_LOGGER_TRACE("firstNToString(snapshotAsk, " + toString(maxMarketDepth) + ") = " + firstNToString(snapshotAsk, maxMarketDepth));
} else {
CCAPI_LOGGER_WARN("extra type " + MarketDataMessage::dataTypeToString(type));
}
}
this->updateElementListWithOrderBookSnapshot(CCAPI_MARKET_DEPTH, maxMarketDepth, snapshotBid, snapshotAsk, elementList);
CCAPI_LOGGER_TRACE("elementList = " + toString(elementList));
Message message;
message.setTimeReceived(timeReceived);
message.setType(messageType);
message.setTime(tp);
message.setElementList(elementList);
message.setCorrelationIdList(correlationIdList);
messageList.emplace_back(std::move(message));
event.addMessages(messageList);
}
void convertRequestForRestGenericPublicRequest(http::request<http::string_body>& req, const Request& request, const TimePoint& now,
const std::string& symbolId, const std::map<std::string, std::string>& credential) {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
@@ -1535,43 +1734,43 @@ class MarketDataService : public Service {
}
} else {
if (this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId].empty()) {
int delayMilliSeconds = std::stoi(optionMap.at(CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS));
if (delayMilliSeconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliSeconds)));
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = this](ErrorCode const& ec) {
int delayMilliseconds = std::stoi(optionMap.at(CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS));
if (delayMilliseconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliseconds)));
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, delayMilliseconds, that = this](ErrorCode const& ec) {
auto now = UtilTime::now();
if (ec) {
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliseconds);
}
});
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = timerPtr;
} else {
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliseconds);
}
}
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId][versionId] =
marketDataMessage.data;
}
}
void buildOrderBookInitialOnFail(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliSeconds) {
auto thisDelayMilliSeconds = delayMilliSeconds * 2;
if (thisDelayMilliSeconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(thisDelayMilliSeconds)));
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds, that = this](ErrorCode const& ec) {
void buildOrderBookInitialOnFail(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliseconds) {
auto thisDelayMilliseconds = delayMilliseconds * 2;
if (thisDelayMilliseconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(thisDelayMilliseconds)));
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, thisDelayMilliseconds, that = this](ErrorCode const& ec) {
if (ec) {
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds);
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliseconds);
}
});
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = timerPtr;
} else {
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds);
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliseconds);
}
}
void buildOrderBookInitial(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliSeconds) {
void buildOrderBookInitial(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliseconds) {
auto now = UtilTime::now();
http::request<http::string_body> req;
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
@@ -1582,10 +1781,10 @@ class MarketDataService : public Service {
this->createFetchOrderBookInitialReq(req, symbolId, now, credential);
this->sendRequest(
req,
[wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = shared_from_base<MarketDataService>()](const beast::error_code& ec) {
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
[wsConnection, exchangeSubscriptionId, delayMilliseconds, that = shared_from_base<MarketDataService>()](const beast::error_code& ec) {
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliseconds);
},
[wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = shared_from_base<MarketDataService>()](const http::response<http::string_body>& res) {
[wsConnection, exchangeSubscriptionId, delayMilliseconds, that = shared_from_base<MarketDataService>()](const http::response<http::string_body>& res) {
auto timeReceived = UtilTime::now();
int statusCode = res.result_int();
std::string body = res.body();
@@ -1710,19 +1909,19 @@ class MarketDataService : public Service {
that->eventHandler(event, nullptr);
that->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
} else {
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
// if (delayMilliSeconds > 0) {
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliseconds);
// if (delayMilliseconds > 0) {
// that->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] =
// that->serviceContextPtr->tlsClientPtr->set_timer(
// delayMilliSeconds, [wsConnection, exchangeSubscriptionId, delayMilliSeconds, that](ErrorCode const& ec) {
// delayMilliseconds, [wsConnection, exchangeSubscriptionId, delayMilliseconds, that](ErrorCode const& ec) {
// if (ec) {
// that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
// } else {
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliseconds);
// }
// });
// } else {
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliseconds);
// }
}
return;
@@ -1730,11 +1929,27 @@ class MarketDataService : public Service {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
}
}
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliseconds);
// WsConnection thisWsConnection = wsConnection;
// that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
std::string convertCandlestickIntervalSecondsToInterval(int intervalSeconds, const std::string& secondStr, const std::string& minuteStr,
const std::string& hourStr, const std::string& dayStr, const std::string& weekStr) {
std::string interval;
if (intervalSeconds < 60) {
interval = std::to_string(intervalSeconds) + secondStr;
} else if (intervalSeconds < 3600) {
interval = std::to_string(intervalSeconds / 60) + minuteStr;
} else if (intervalSeconds < 86400) {
interval = std::to_string(intervalSeconds / 3600) + hourStr;
} else if (intervalSeconds < 604800) {
interval = std::to_string(intervalSeconds / 86400) + dayStr;
} else {
interval = std::to_string(intervalSeconds / 604800) + weekStr;
}
return interval;
}
virtual std::vector<std::string> createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector<Subscription>& subscriptionList,
const TimePoint& now, const std::map<std::string, std::string>& credential) {
@@ -1742,7 +1957,7 @@ class MarketDataService : public Service {
}
virtual void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) {}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
virtual void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
Event& event, std::vector<MarketDataMessage>& marketDataMessageList) {}
#else
@@ -1785,10 +2000,14 @@ class MarketDataService : public Service {
std::map<std::string, std::map<std::string, std::map<std::string, Decimal>>> lowByConnectionIdChannelIdSymbolIdMap;
std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> closeByConnectionIdChannelIdSymbolIdMap;
std::string getRecentTradesTarget;
std::string getHistoricalTradesTarget;
std::string getRecentCandlesticksTarget;
std::string getHistoricalCandlesticksTarget;
std::string getMarketDepthTarget;
std::string getInstrumentTarget;
std::string getInstrumentsTarget;
std::map<std::string, int> exchangeJsonPayloadIdByConnectionIdMap;
std::map<std::string, std::map<int, std::vector<std::string>>> exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap;
std::map<std::string, std::map<int, std::vector<std::string>>> exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap;
// only needed for generic public subscription
std::map<std::string, std::string> correlationIdByConnectionIdMap;
std::map<std::string, std::map<std::string, std::map<int64_t, MarketDataMessage::TypeForData>>>
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceAscendex : public MarketDataService {
public:
MarketDataServiceAscendex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_ASCENDEX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api/pro/v1/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/pro/v1/trades";
this->getInstrumentTarget = "/api/pro/v1/products";
this->getInstrumentsTarget = "/api/pro/v1/products";
@@ -44,9 +44,12 @@ class MarketDataServiceAscendex : public MarketDataService {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BBO;
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval = std::to_string(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)) / 60);
channelId += ":" + interval;
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
@@ -78,14 +81,14 @@ class MarketDataServiceAscendex : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -160,9 +163,27 @@ class MarketDataServiceAscendex : public MarketDataService {
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (m == "bar") {
std::string channelId = m;
const rj::Value& data = document["data"];
std::string symbolId = document["s"].GetString();
std::string exchangeSubscriptionId = channelId + ":" + std::string(data["i"].GetString()) + ":" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["ts"].GetString())));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, data["o"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, data["h"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, data["l"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, data["c"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, data["v"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (m == "ping") {
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, R"({ "op": "pong" })", wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, R"({ "op": "pong" })", ec);
@@ -215,7 +236,7 @@ class MarketDataServiceAscendex : public MarketDataService {
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
CCAPI_LOGGER_TRACE(sendString);
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -7,30 +7,35 @@ namespace ccapi {
class MarketDataServiceBinance : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinance(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/api/v3/trades";
this->getHistoricalTradesTarget = "/api/v3/historicalTrades";
this->getRecentAggTradesTarget = "/api/v3/aggTrades";
this->getHistoricalAggTradesTarget = "/api/v3/aggTrades";
this->getRecentCandlesticksTarget = "/api/v3/klines";
this->getHistoricalCandlesticksTarget = "/api/v3/klines";
this->getMarketDepthTarget = "/api/v3/depth";
this->getInstrumentTarget = "/api/v3/exchangeInfo";
this->getInstrumentsTarget = "/api/v3/exchangeInfo";
}
@@ -8,7 +8,7 @@ namespace ccapi {
class MarketDataServiceBinanceBase : public MarketDataService {
public:
MarketDataServiceBinanceBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->enableCheckPingPongWebsocketApplicationLevel = false;
}
@@ -17,7 +17,7 @@ class MarketDataServiceBinanceBase : public MarketDataService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
CCAPI_LOGGER_FUNCTION_ENTER;
auto now = UtilTime::now();
@@ -36,15 +36,15 @@ class MarketDataServiceBinanceBase : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER;
} else {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
std::string updateSpeed;
if (conflateIntervalMilliSeconds < 1000) {
if (conflateIntervalMilliseconds < 1000) {
updateSpeed = "100ms";
}
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
@@ -53,6 +53,10 @@ class MarketDataServiceBinanceBase : public MarketDataService {
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "s", "m", "h", "d", "w");
channelId = channelId + "_" + interval;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -94,7 +98,7 @@ class MarketDataServiceBinanceBase : public MarketDataService {
}
document.AddMember("params", params, allocator);
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
rj::StringBuffer stringBuffer;
@@ -105,14 +109,14 @@ class MarketDataServiceBinanceBase : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -127,11 +131,11 @@ class MarketDataServiceBinanceBase : public MarketDataService {
std::vector<std::string> correlationIdList;
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) {
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
@@ -240,6 +244,22 @@ class MarketDataServiceBinanceBase : public MarketDataService {
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::AGG_TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId.find(CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE) != std::string::npos) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
const rj::Value& k = data["k"];
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(k["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, k["o"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, k["h"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, k["l"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, k["c"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, k["v"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, k["q"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
@@ -268,7 +288,21 @@ class MarketDataServiceBinanceBase : public MarketDataService {
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_AGG_TRADES: {
case Request::Operation::GET_HISTORICAL_TRADES: {
req.method(http::verb::get);
auto target = this->getHistoricalTradesTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TRADE_ID, "fromId"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_AGG_TRADES:
case Request::Operation::GET_HISTORICAL_AGG_TRADES: {
req.method(http::verb::get);
auto target = this->getRecentAggTradesTarget;
std::string queryString;
@@ -276,6 +310,53 @@ class MarketDataServiceBinanceBase : public MarketDataService {
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "startTime"},
{CCAPI_END_TIME_SECONDS, "endTime"},
{CCAPI_START_AGG_TRADE_ID, "fromId"},
},
{
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBinanceBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBinanceBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
req.method(http::verb::get);
auto target = this->getRecentCandlesticksTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "interval"},
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "startTime"},
{CCAPI_END_TIME_SECONDS, "endTime"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS,
[that = shared_from_base<MarketDataServiceBinanceBase>()](const std::string& input) {
return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), "s", "m", "h", "d", "w");
}},
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBinanceBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBinanceBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_MARKET_DEPTH: {
req.method(http::verb::get);
auto target = this->getMarketDepthTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_MARKET_DEPTH_MAX, "limit"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
@@ -317,7 +398,8 @@ class MarketDataServiceBinanceBase : public MarketDataService {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
for (const auto& x : document.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
@@ -331,7 +413,8 @@ class MarketDataServiceBinanceBase : public MarketDataService {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_AGG_TRADES: {
case Request::Operation::GET_RECENT_AGG_TRADES:
case Request::Operation::GET_HISTORICAL_AGG_TRADES: {
for (const auto& x : document.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE;
@@ -345,6 +428,41 @@ class MarketDataServiceBinanceBase : public MarketDataService {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
for (const auto& x : document.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x[0].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x[7].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_MARKET_DEPTH: {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["T"].GetString()));
for (const auto& x : document["bids"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : document["asks"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
@@ -380,6 +498,7 @@ class MarketDataServiceBinanceBase : public MarketDataService {
}
bool isDerivatives{};
std::string getRecentAggTradesTarget;
std::string getHistoricalAggTradesTarget;
};
} /* namespace ccapi */
#endif
@@ -7,30 +7,35 @@ namespace ccapi {
class MarketDataServiceBinanceCoinFutures : public MarketDataServiceBinanceDerivativesBase {
public:
MarketDataServiceBinanceCoinFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/dapi/v1/trades";
this->getHistoricalTradesTarget = "/dapi/v1/historicalTrades";
this->getRecentAggTradesTarget = "/dapi/v1/aggTrades";
this->getHistoricalAggTradesTarget = "/dapi/v1/aggTrades";
this->getRecentCandlesticksTarget = "/dapi/v1/klines";
this->getHistoricalCandlesticksTarget = "/dapi/v1/klines";
this->getMarketDepthTarget = "/dapi/v1/depth";
this->getInstrumentTarget = "/dapi/v1/exchangeInfo";
this->getInstrumentsTarget = "/dapi/v1/exchangeInfo";
}
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinanceDerivativesBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->isDerivatives = true;
}
@@ -19,17 +19,17 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({1, 5, 10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({1, 5, 10, 20}));
if (marketDepthSubscribedToExchange == 1) {
channelId = CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER;
} else {
std::string updateSpeed;
if (conflateIntervalMilliSeconds < 250) {
if (conflateIntervalMilliseconds < 250) {
updateSpeed = "100ms";
} else if (conflateIntervalMilliSeconds >= 500) {
} else if (conflateIntervalMilliseconds >= 500) {
updateSpeed = "500ms";
}
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
@@ -38,9 +38,17 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "s", "m", "h", "d", "w");
channelId = channelId + "_" + interval;
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_INSTRUMENT_STATUS, x["status"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseAsset"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteAsset"].GetString());
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_MARGIN_ASSET, x["marginAsset"].GetString());
element.insert(CCAPI_UNDERLYING_SYMBOL, x["pair"].GetString());
@@ -51,11 +59,38 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB
} else if (filterType == "LOT_SIZE") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, y["stepSize"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, y["minQty"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MAX, y["maxQty"].GetString());
} else if (filterType == "MIN_NOTIONAL") {
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, y["notional"].GetString());
}
}
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
this->prepareReq(req, credential);
switch (request.getOperation()) {
case Request::Operation::GET_MARKET_DEPTH: {
req.method(http::verb::get);
auto target = this->getMarketDepthTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_MARKET_DEPTH_MAX, "limit"},
},
{
{CCAPI_MARKET_DEPTH_MAX,
[that = shared_from_base<MarketDataServiceBinanceDerivativesBase>()](const std::string& input) {
return std::to_string(that->calculateMarketDepthAllowedByExchange(std::stoi(input), {5, 10, 20, 50, 100, 500, 1000}));
}},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
default:
MarketDataServiceBinanceBase::convertRequestForRest(req, request, now, symbolId, credential);
}
}
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
switch (request.getOperation()) {
@@ -7,30 +7,35 @@ namespace ccapi {
class MarketDataServiceBinanceUs : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinanceUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_US;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_US_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/api/v3/trades";
this->getHistoricalTradesTarget = "/api/v3/historicalTrades";
this->getRecentAggTradesTarget = "/api/v3/aggTrades";
this->getHistoricalAggTradesTarget = "/api/v3/aggTrades";
this->getRecentCandlesticksTarget = "/api/v3/klines";
this->getHistoricalCandlesticksTarget = "/api/v3/klines";
this->getMarketDepthTarget = "/api/v3/depth";
this->getInstrumentTarget = "/api/v3/exchangeInfo";
this->getInstrumentsTarget = "/api/v3/exchangeInfo";
}
@@ -7,30 +7,35 @@ namespace ccapi {
class MarketDataServiceBinanceUsdsFutures : public MarketDataServiceBinanceDerivativesBase {
public:
MarketDataServiceBinanceUsdsFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/fapi/v1/trades";
this->getHistoricalTradesTarget = "/fapi/v1/historicalTrades";
this->getRecentAggTradesTarget = "/fapi/v1/aggTrades";
this->getHistoricalAggTradesTarget = "/fapi/v1/aggTrades";
this->getRecentCandlesticksTarget = "/fapi/v1/klines";
this->getHistoricalCandlesticksTarget = "/fapi/v1/klines";
this->getMarketDepthTarget = "/fapi/v1/depth";
this->getInstrumentTarget = "/fapi/v1/exchangeInfo";
this->getInstrumentsTarget = "/fapi/v1/exchangeInfo";
}
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceBitfinex : public MarketDataService {
public:
MarketDataServiceBitfinex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITFINEX;
this->baseUrlWs = std::string(CCAPI_BITFINEX_PUBLIC_URL_WS_BASE) + "/ws/2";
this->baseUrlRest = CCAPI_BITFINEX_PUBLIC_URL_REST_BASE;
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/v2/trades/{Symbol}/hist";
this->getInstrumentsTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH;
this->getInstrumentTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH;
@@ -36,8 +36,8 @@ class MarketDataServiceBitfinex : public MarketDataService {
private:
#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); }
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"event":"ping"})", wspp::frame::opcode::text, ec); }
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
rj::Document document;
@@ -103,7 +103,7 @@ class MarketDataServiceBitfinex : public MarketDataService {
MarketDataService::onIncorrectStatesFound(wsConnection, hdl, textMessage, timeReceived, exchangeSubscriptionId, reason);
}
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"event":"ping"})", ec); }
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
MarketDataService::onOpen(wsConnectionPtr);
rj::Document document;
@@ -172,28 +172,23 @@ class MarketDataServiceBitfinex : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({1, 25, 100, 250}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({1, 25, 100, 250}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "", "m", "h", "D", "W");
channelId = std::string(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES) + ":" + interval;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override { return std::vector<std::string>(); }
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
void processTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
#endif
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsArray() && document.Size() >= 1) {
@@ -201,46 +196,39 @@ 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);
auto symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
std::string channel =
channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 ? CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK : CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES ||
channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
std::string channel;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS;
} else if (channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
} else if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES;
}
rj::Value data(rj::kArrayType);
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()) {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[2].GetString());
}
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0) {
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
@@ -270,7 +258,7 @@ class MarketDataServiceBitfinex : public MarketDataService {
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else {
} else if (channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
for (const auto& x : content.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
@@ -288,36 +276,72 @@ class MarketDataServiceBitfinex : public MarketDataService {
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
for (const auto& x : content.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
std::string timestampInMilliseconds = x[0].GetString();
timestampInMilliseconds.insert(timestampInMilliseconds.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(timestampInMilliseconds));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else {
const rj::Value& x = content;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
auto count = std::string(x[1].GetString());
auto amount = UtilString::normalizeDecimalString(x[2].GetString());
if (count != "0") {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount.substr(1)});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
}
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
std::string timestampInMilliseconds = x[0].GetString();
timestampInMilliseconds.insert(timestampInMilliseconds.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(timestampInMilliseconds));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
auto count = std::string(x[1].GetString());
auto amount = UtilString::normalizeDecimalString(x[2].GetString());
if (count != "0") {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount.substr(1)});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
}
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
}
}
}
}
@@ -326,17 +350,10 @@ 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();
@@ -361,17 +378,10 @@ 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] =
@@ -397,9 +407,16 @@ class MarketDataServiceBitfinex : public MarketDataService {
std::vector<std::string> sendStringList;
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
std::string channel = channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 ? CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK
: CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES ||
channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
std::string channel;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS;
} else if (channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
} else if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES;
}
for (auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
rj::Document document;
document.SetObject();
@@ -407,8 +424,13 @@ class MarketDataServiceBitfinex : public MarketDataService {
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
document.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
auto symbolId = subscriptionListBySymbolId.first;
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK) {
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
auto splitted = UtilString::split(channelId, ':');
document.AddMember("key", rj::Value(("trade:" + splitted.at(1) + ":" + symbolId).c_str(), allocator).Move(), allocator);
} else {
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS) {
document.AddMember("prec", rj::Value("P0").Move(), allocator);
document.AddMember("freq", rj::Value("F0").Move(), allocator);
document.AddMember(
@@ -430,21 +452,28 @@ 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");
}
}
} else if (eventStr == "subscribed" || eventStr == "error") {
std::string channel = document["channel"].GetString();
auto channelId = channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK
? channel + "?" + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::string(document["len"].GetString())
: channel;
auto symbolId = std::string(document["symbol"].GetString());
std::string channelId;
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS) {
channelId = channel + "?" + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::string(document["len"].GetString());
} else if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES) {
auto splitted = UtilString::split(document["key"].GetString(), ':');
channelId = std::string(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES) + ":" + splitted.at(1);
} else {
channelId = channel;
}
std::string symbolId;
if (document.FindMember("symbol") != document.MemberEnd()) {
symbolId = std::string(document["symbol"].GetString());
} else if (document.FindMember("key") != document.MemberEnd()) {
symbolId = UtilString::split(std::string(document["key"].GetString()), ':').at(2);
}
if (eventStr == "subscribed") {
auto exchangeSubscriptionId = std::string(document["chanId"].GetString());
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
@@ -7,29 +7,32 @@ namespace ccapi {
class MarketDataServiceBitget : public MarketDataServiceBitgetBase {
public:
MarketDataServiceBitget(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/v1/stream";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/ws/public";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->getRecentTradesTarget = "/api/spot/v1/market/fills";
this->getInstrumentTarget = "/api/spot/v1/public/product";
this->getInstrumentsTarget = "/api/spot/v1/public/products";
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v2/spot/market/fills";
this->getHistoricalTradesTarget = "/api/v2/spot/market/fills-history";
this->getInstrumentTarget = "/api/v2/spot/public/symbols";
this->getInstrumentsTarget = "/api/v2/spot/public/symbols";
this->getRecentCandlesticksTarget = "/api/v2/spot/market/candles";
this->getHistoricalCandlesticksTarget = "/api/v2/spot/market/candles";
}
virtual ~MarketDataServiceBitget() {}
};
@@ -7,8 +7,10 @@ namespace ccapi {
class MarketDataServiceBitgetBase : public MarketDataService {
public:
MarketDataServiceBitgetBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->hostHttpHeaderValueIgnorePort = true;
}
virtual ~MarketDataServiceBitgetBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
@@ -18,24 +20,15 @@ class MarketDataServiceBitgetBase : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (this->isDerivatives) this->instrumentType = subscription.getInstrumentType();
if (field == CCAPI_MARKET_DEPTH) {
if (this->isDerivatives) {
if (conflateIntervalMilliSeconds < 200) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
} else {
if (marketDepthRequested <= 1) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1;
} else if (marketDepthRequested <= 5) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5;
} else if (marketDepthRequested <= 15) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15;
} else {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
}
}
if (conflateIntervalMilliseconds < 200 && this->isDerivatives) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
} else {
if (marketDepthRequested <= 5) {
if (marketDepthRequested <= 1) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1;
} else if (marketDepthRequested <= 5) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5;
} else if (marketDepthRequested <= 15) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15;
@@ -43,9 +36,13 @@ class MarketDataServiceBitgetBase : public MarketDataService {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
}
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), " ", "m", "H", "D", "W");
channelId = channelId + interval;
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
@@ -67,7 +64,7 @@ class MarketDataServiceBitgetBase : public MarketDataService {
}
std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId;
rj::Value arg(rj::kObjectType);
std::string instType = this->isDerivatives ? "mc" : "sp";
std::string instType = this->instrumentType;
arg.AddMember("instType", rj::Value(instType.c_str(), allocator).Move(), allocator);
arg.AddMember("channel", rj::Value(channelId.c_str(), allocator).Move(), allocator);
arg.AddMember("instId", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
@@ -107,14 +104,14 @@ class MarketDataServiceBitgetBase : public MarketDataService {
return intToHex(csCalc);
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -229,13 +226,31 @@ class MarketDataServiceBitgetBase : public MarketDataService {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = recapType;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["size"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "Buy" ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(datum["tradeId"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelId.find(CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_KLINE) != std::string::npos) {
for (const auto& datum : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[0].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum[1].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum[2].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum[3].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, datum[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, datum[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, datum[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, datum[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, datum[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, datum[6].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
@@ -257,26 +272,56 @@ class MarketDataServiceBitgetBase : public MarketDataService {
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
case Request::Operation::GET_HISTORICAL_TRADES: {
req.method(http::verb::get);
std::string target;
auto target = this->getHistoricalTradesTarget;
std::string queryString;
if (this->isDerivatives) {
target = this->getInstrumentsTarget;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
} else {
target = this->getInstrumentTarget;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendSymbolId(queryString, symbolId, "symbol");
}
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "productType"},
{CCAPI_START_TIME_SECONDS, "startTime"},
{CCAPI_END_TIME_SECONDS, "endTime"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
req.method(http::verb::get);
auto target = this->getRecentCandlesticksTarget;
std::string minuteSuffix = this->isDerivatives ? "m" : "min";
std::string hourSuffix = this->isDerivatives ? "H" : "h";
std::string daySuffix = this->isDerivatives ? "D" : "day";
std::string weekSuffix = this->isDerivatives ? "W" : "week";
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(
queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "granularity"},
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "startTime"},
{CCAPI_END_TIME_SECONDS, "endTime"},
{CCAPI_INSTRUMENT_TYPE, "productType"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS,
[that = shared_from_base<MarketDataServiceBitgetBase>(), minuteSuffix, hourSuffix, daySuffix, weekSuffix](const std::string& input) {
return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), " ", minuteSuffix, hourSuffix, daySuffix, weekSuffix);
}},
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBitgetBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBitgetBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENTS: {
@@ -284,25 +329,34 @@ class MarketDataServiceBitgetBase : public MarketDataService {
auto target = this->getInstrumentsTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
if (this->isDerivatives) {
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
req.target(target + "?" + queryString);
} else {
req.target(target);
}
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
std::string target;
std::string queryString;
target = this->getInstrumentsTarget;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
if (this->isDerivatives) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
int pricePlace = std::stoi(x["pricePlace"].GetString());
if (pricePlace > 0) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(pricePlace - 1, '0') + x["priceEndStep"].GetString());
@@ -312,16 +366,13 @@ class MarketDataServiceBitgetBase : public MarketDataService {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["sizeMultiplier"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeNum"].GetString());
} else {
element.insert(CCAPI_INSTRUMENT, x["symbolName"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
int priceScale = std::stoi(x["priceScale"].GetString());
int priceScale = std::stoi(x["pricePrecision"].GetString());
if (priceScale > 0) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(priceScale - 1, '0') + "1");
} else {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1");
}
int quantityScale = std::stoi(x["quantityScale"].GetString());
int quantityScale = std::stoi(x["quantityPrecision"].GetString());
if (quantityScale > 0) {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(quantityScale - 1, '0') + "1");
} else {
@@ -335,22 +386,38 @@ class MarketDataServiceBitgetBase : public MarketDataService {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
for (const auto& datum : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[this->isDerivatives ? "timestamp" : "fillTime"].GetString())));
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert(
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum[this->isDerivatives ? "price" : "fillPrice"].GetString())});
dataPoint.insert(
{MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum[this->isDerivatives ? "size" : "fillQuantity"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["size"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, datum["tradeId"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "sell" ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "Buy" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
for (const auto& datum : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(datum[0].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, datum[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, datum[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, datum[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, datum[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, datum[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, datum[6].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
@@ -385,6 +452,7 @@ class MarketDataServiceBitgetBase : public MarketDataService {
}
}
bool isDerivatives{};
std::string instrumentType{"SPOT"};
};
} /* namespace ccapi */
#endif
@@ -7,29 +7,32 @@ namespace ccapi {
class MarketDataServiceBitgetFutures : public MarketDataServiceBitgetBase {
public:
MarketDataServiceBitgetFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/mix/v1/stream";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/ws/public";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->getRecentTradesTarget = "/api/mix/v1/market/fills";
this->getInstrumentTarget = "/api/mix/v1/market/contracts";
this->getInstrumentsTarget = "/api/mix/v1/market/contracts";
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v2/mix/market/fills";
this->getHistoricalTradesTarget = "/api/v2/mix/market/fills-history";
this->getInstrumentTarget = "/api/v2/mix/market/contracts";
this->getInstrumentsTarget = "/api/v2/mix/market/contracts";
this->getRecentCandlesticksTarget = "/api/v2/mix/market/candles";
this->getHistoricalCandlesticksTarget = "/api/v2/mix/market/candles";
this->isDerivatives = true;
}
virtual ~MarketDataServiceBitgetFutures() {}
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceBitmart : public MarketDataService {
public:
MarketDataServiceBitmart(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITMART;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api?protocol=1.1";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITMART_API_KEY;
this->apiSecretName = CCAPI_BITMART_API_SECRET;
this->apiMemo = CCAPI_BITMART_API_MEMO;
@@ -52,7 +52,7 @@ class MarketDataServiceBitmart : public MarketDataService {
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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));
@@ -97,14 +97,14 @@ class MarketDataServiceBitmart : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceBitmex : public MarketDataService {
public:
MarketDataServiceBitmex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITMEX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v1/trade";
this->getInstrumentTarget = "/api/v1/instrument";
this->getInstrumentsTarget = "/api/v1/instrument";
@@ -54,7 +54,7 @@ class MarketDataServiceBitmex : public MarketDataService {
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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));
@@ -97,14 +97,14 @@ class MarketDataServiceBitmex : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -187,7 +187,7 @@ class MarketDataServiceBitmex : public MarketDataService {
} else {
price = this->priceByConnectionIdChannelIdSymbolIdPriceIdMap[wsConnection.id][channelId][symbolId][priceId];
if (price.empty()) {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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: " +
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceBitstamp : public MarketDataService {
public:
MarketDataServiceBitstamp(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITSTAMP;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
@@ -15,19 +15,19 @@ class MarketDataServiceBitstamp : public MarketDataService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v2/transactions/{currency_pair}/"; // must have trailing slash
this->getInstrumentTarget = "/api/v2/trading-pairs-info/";
this->getInstrumentsTarget = "/api/v2/trading-pairs-info/";
@@ -37,7 +37,7 @@ class MarketDataServiceBitstamp : public MarketDataService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec);
}
@@ -78,14 +78,14 @@ class MarketDataServiceBitstamp : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -2,48 +2,71 @@
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_market_data_service_bybit_base.h"
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceBybit : public MarketDataServiceBybitBase {
class MarketDataServiceBybit : public MarketDataService {
public:
MarketDataServiceBybit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/public/v3";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v5/public/{instrumentTypeSubstitute}";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->getRecentTradesTarget = "/spot/v3/public/quote/trades";
this->getInstrumentsTarget = "/spot/v3/public/symbols";
this->getRecentTradesTarget = "/v5/market/recent-trade";
this->getHistoricalTradesTarget = "/v5/market/recent-trade";
this->getRecentCandlesticksTarget = "/v5/market/kline";
this->getHistoricalCandlesticksTarget = "/v5/market/kline";
this->getMarketDepthTarget = "/v5/market/orderbook";
this->getInstrumentTarget = "/v5/market/instruments-info";
this->getInstrumentsTarget = "/v5/market/instruments-info";
}
virtual ~MarketDataServiceBybit() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
std::string getInstrumentGroup(const Subscription& subscription) override {
const auto& instrumentTypeSubstitute = subscription.getInstrumentType();
std::string url = MarketDataService::getInstrumentGroup(subscription);
std::string toReplace("{instrumentTypeSubstitute}");
url.replace(url.find(toReplace), toReplace.length(), instrumentTypeSubstitute);
return url;
}
std::string convertCandlestickIntervalSecondsToInterval(int intervalSeconds) {
std::string interval;
if (intervalSeconds < 86400) {
interval = std::to_string(intervalSeconds / 60);
} else if (intervalSeconds == 86400) {
interval = "D";
} else {
interval = "W";
}
return interval;
}
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
const auto& marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
const auto& instrumentType = subscription.getInstrumentType();
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER;
} else {
channelId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH;
std::vector<int> depths;
if (instrumentType == "spot") {
depths = {1, 50, 200};
} else if (instrumentType == "linear" || instrumentType == "inverse") {
depths = {1, 50, 200, 500};
} else if (instrumentType == "option") {
depths = {25, 100};
}
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, depths);
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else if (field == CCAPI_CANDLESTICK) {
int intervalSeconds = std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS));
std::string interval = this->convertCandlestickIntervalSecondsToInterval(intervalSeconds);
std::string toReplace = "{interval}";
channelId.replace(channelId.find(toReplace), toReplace.length(), interval);
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -58,9 +81,13 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
auto channelId = subscriptionListByChannelIdSymbolId.first;
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
auto exchangeSubscriptionId = channelId;
if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER || channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
std::string exchangeSubscriptionId = channelId;
if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_CHANNEL_ORDERBOOK, 0) == 0) {
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
exchangeSubscriptionId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_ORDERBOOK;
std::string toReplace = "{depth}";
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), std::to_string(marketDepthSubscribedToExchange));
}
std::string toReplace = "{symbol}";
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), symbolId);
@@ -72,7 +99,7 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
}
document.AddMember("args", args, allocator);
document.AddMember("req_id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
rj::StringBuffer stringBuffer;
@@ -82,19 +109,10 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
sendStringList.push_back(sendString);
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
void processTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
#endif
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsObject() && document.HasMember("op")) {
@@ -109,11 +127,11 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["req_id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) {
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
@@ -137,73 +155,63 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
event.setMessageList(messageList);
}
} else if (document.IsObject() && document.HasMember("data")) {
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId = document["topic"].GetString();
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
const rj::Value& data = document["data"];
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER) {
if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_CHANNEL_ORDERBOOK, 0) == 0) {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(document["ts"].GetString())));
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["bp"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bq"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["ap"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["aq"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
const char* bidsName = "b";
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : data[bidsName].GetArray()) {
if (bidIndex >= maxMarketDepth) {
break;
}
std::string type = document["type"].GetString();
marketDataMessage.recapType = type == "snapshot" ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE;
for (const auto& x : data["b"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
++bidIndex;
}
const char* asksName = "a";
int askIndex = 0;
for (const auto& x : data[asksName].GetArray()) {
if (askIndex >= maxMarketDepth) {
break;
}
for (const auto& x : data["a"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
++askIndex;
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(data["p"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(data["q"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(data["v"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "0" : "1"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["T"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["i"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["S"].GetString()) == "Buy" ? "0" : "1"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_CHANNEL_KLINE_2, 0) == 0) {
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["start"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x["open"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x["high"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x["low"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x["close"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x["volume"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x["turnover"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
@@ -213,7 +221,8 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
case Request::Operation::GENERIC_PUBLIC_REQUEST: {
MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
req.method(http::verb::get);
auto target = this->getRecentTradesTarget;
std::string queryString;
@@ -225,55 +234,160 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
req.method(http::verb::get);
auto target = this->getRecentCandlesticksTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "interval"},
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "start"},
{CCAPI_END_TIME_SECONDS, "end"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS,
[that = shared_from_base<MarketDataServiceBybit>()](const std::string& input) {
return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input));
}},
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBybit>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBybit>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_MARKET_DEPTH: {
req.method(http::verb::get);
auto target = this->getMarketDepthTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
req.target(target);
auto target = this->getInstrumentTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "category"},
});
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId, "symbol");
}
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
req.target(target);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "category"},
});
req.target(target + "?" + queryString);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["name"].GetString());
void extractInstrumentInfo(Element& element, const rj::Value& x, const std::string& category) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["minPricePrecision"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["basePrecision"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeQty"].GetString());
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minTradeAmt"].GetString());
auto it = x.FindMember("settleCoin");
if (it != x.MemberEnd()) {
element.insert(CCAPI_MARGIN_ASSET, it->value.GetString());
}
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceFilter"]["tickSize"].GetString());
if (category == "spot") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["basePrecision"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minOrderQty"].GetString());
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["lotSizeFilter"]["minOrderAmt"].GetString());
} else if (category == "linear" || category == "inverse") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["qtyStep"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minOrderQty"].GetString());
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["lotSizeFilter"]["minNotionalValue"].GetString());
} else if (category == "option") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["qtyStep"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minOrderQty"].GetString());
}
}
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
for (const auto& x : document["result"]["list"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["qty"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["isBuyerMaker"].GetString() ? "0" : "1"});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["size"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "sell" ? "0" : "1"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, x["execId"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
for (const auto& x : document["result"]["list"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x[0].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x[6].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_MARKET_DEPTH: {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
const rj::Value& result = document["result"];
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(result["ts"].GetString()));
for (const auto& x : result["b"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : result["a"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
std::string category = document["result"]["category"].GetString();
for (const auto& x : document["result"]["list"].GetArray()) {
if (std::string(x["name"].GetString()) == request.getInstrument()) {
if (std::string(x["symbol"].GetString()) == request.getInstrument()) {
Element element;
this->extractInstrumentInfo(element, x);
this->extractInstrumentInfo(element, x, category);
message.setElementList({element});
break;
}
@@ -285,10 +399,11 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
std::string category = document["result"]["category"].GetString();
std::vector<Element> elementList;
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
this->extractInstrumentInfo(element, x);
this->extractInstrumentInfo(element, x, category);
elementList.push_back(element);
}
message.setElementList(elementList);
@@ -1,27 +0,0 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_BYBIT) || defined(CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES)
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceBybitBase : public MarketDataService {
public:
MarketDataServiceBybitBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~MarketDataServiceBybitBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; }
#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<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
#endif
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
@@ -1,326 +0,0 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
#include "ccapi_cpp/service/ccapi_market_data_service_bybit_base.h"
namespace ccapi {
class MarketDataServiceBybitDerivatives : public MarketDataServiceBybitBase {
public:
MarketDataServiceBybitDerivatives(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/{instrumentTypeSubstitute}/public/v3";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->getRecentTradesTarget = "/derivatives/v3/public/recent-trade";
this->getInstrumentTarget = "/derivatives/v3/public/instruments-info";
this->getInstrumentsTarget = "/derivatives/v3/public/instruments-info";
}
virtual ~MarketDataServiceBybitDerivatives() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
std::string getInstrumentGroup(const Subscription& subscription) override {
const auto& instrumentType = subscription.getInstrumentType();
std::string instrumentTypeSubstitute;
if (instrumentType == "usdt-contract") {
instrumentTypeSubstitute = "contract/usdt";
} else if (instrumentType == "usdc-contract") {
instrumentTypeSubstitute = "contract/usdc";
} else if (instrumentType == "usdc-options") {
instrumentTypeSubstitute = "option/usdc";
}
std::string url = MarketDataService::getInstrumentGroup(subscription);
std::string toReplace("{instrumentTypeSubstitute}");
url.replace(url.find(toReplace), toReplace.length(), instrumentTypeSubstitute);
return url;
}
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
const auto& marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
const auto& instrumentType = subscription.getInstrumentType();
if (field == CCAPI_MARKET_DEPTH) {
std::vector<int> depths;
if (instrumentType == "usdc-options") {
depths = {25, 100};
} else {
depths = {1, 50, 200};
}
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, depths);
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
std::vector<std::string> sendStringList;
std::vector<std::string> exchangeSubscriptionIdList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
rj::Value args(rj::kArrayType);
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
std::string exchangeSubscriptionId;
if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK, 0) == 0) {
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
exchangeSubscriptionId = CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK;
std::string toReplace = "{depth}";
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), std::to_string(marketDepthSubscribedToExchange));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE) {
exchangeSubscriptionId = CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE;
}
std::string toReplace = "{symbol}";
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), symbolId);
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
args.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
}
}
document.AddMember("args", args, allocator);
document.AddMember("req_id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
#endif
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsObject() && document.HasMember("op")) {
std::string op = document["op"].GetString();
if (op == "subscribe") {
bool success = document["success"].GetBool();
event.setType(Event::Type::SUBSCRIPTION_STATUS);
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
std::vector<std::string> correlationIdList;
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["req_id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
std::vector<std::string> correlationIdList_2 =
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end());
}
}
}
}
}
message.setCorrelationIdList(correlationIdList);
message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
}
} else if (document.IsObject() && document.HasMember("data")) {
std::string exchangeSubscriptionId = document["topic"].GetString();
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
const rj::Value& data = document["data"];
if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK, 0) == 0) {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(document["ts"].GetString())));
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
std::string type = document["type"].GetString();
marketDataMessage.recapType = type == "snapshot" ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE;
for (const auto& x : data["b"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : data["a"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE) {
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["T"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["i"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["S"].GetString()) == "Buy" ? "0" : "1"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
switch (request.getOperation()) {
case Request::Operation::GENERIC_PUBLIC_REQUEST: {
MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::GET_RECENT_TRADES: {
req.method(http::verb::get);
auto target = this->getRecentTradesTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "category"},
});
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId, "symbol");
}
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "category"},
});
req.target(target + "?" + queryString);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
auto it = x.FindMember("settleCoin");
if (it != x.MemberEnd()) {
element.insert(CCAPI_MARGIN_ASSET, it->value.GetString());
}
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceFilter"]["tickSize"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["qtyStep"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minTradingQty"].GetString());
}
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
for (const auto& x : document["result"]["list"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["size"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "sell" ? "0" : "1"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, x["execId"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
for (const auto& x : document["result"]["list"].GetArray()) {
if (std::string(x["symbol"].GetString()) == request.getInstrument()) {
Element element;
this->extractInstrumentInfo(element, x);
message.setElementList({element});
break;
}
}
message.setCorrelationIdList({request.getCorrelationId()});
event.addMessages({message});
} break;
case Request::Operation::GET_INSTRUMENTS: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
std::vector<Element> elementList;
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
this->extractInstrumentInfo(element, x);
elementList.push_back(element);
}
message.setElementList(elementList);
message.setCorrelationIdList({request.getCorrelationId()});
event.addMessages({message});
} break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceCoinbase : public MarketDataService {
public:
MarketDataServiceCoinbase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_COINBASE;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/products/<product-id>/trades";
this->getInstrumentTarget = "/products/<product-id>";
this->getInstrumentsTarget = "/products";
@@ -75,14 +75,14 @@ class MarketDataServiceCoinbase : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceCryptocom : public MarketDataService {
public:
MarketDataServiceCryptocom(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_CRYPTOCOM;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/market";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/v2/public/get-trades";
this->getInstrumentTarget = "/v2/public/get-instruments";
this->getInstrumentsTarget = "/v2/public/get-instruments";
@@ -41,7 +41,7 @@ class MarketDataServiceCryptocom : public MarketDataService {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 150}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({10, 150}));
channelId = CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK;
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
@@ -101,14 +101,14 @@ class MarketDataServiceCryptocom : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -219,7 +219,7 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, msg, ec);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceDeribit : public MarketDataService {
public:
MarketDataServiceDeribit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_DERIBIT;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->restTarget = "/api/v2";
this->getRecentTradesTarget = "/public/get_last_trades_by_instrument";
this->getInstrumentTarget = "/public/get_instrument";
@@ -37,7 +37,7 @@ class MarketDataServiceDeribit : public MarketDataService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -45,25 +45,10 @@ class MarketDataServiceDeribit : public MarketDataService {
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
auto now = UtilTime::now();
//////////////////////////////////////////////////
// BEGIN - BTS Custom Code
//////////////////////////////////////////////////
const auto rpcId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
const auto hbInterval = 10;
CCAPI_LOGGER_INFO(
"MarketDataServiceDeribit::onOpen. Setting heartbeat interval."
"interval = " + toString(hbInterval) + ". "
"rpcId = " + toString(rpcId));
activeReqs.insert(rpcId);
this->appendParam(document, allocator, rpcId, "public/set_heartbeat",
this->appendParam(document, allocator, std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count(), "public/set_heartbeat",
{
{"interval", toString(hbInterval)},
{"interval", "10"},
});
//////////////////////////////////////////////////
// END - BTS Custom Code
//////////////////////////////////////////////////
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
@@ -113,7 +98,7 @@ class MarketDataServiceDeribit : public MarketDataService {
channelId = CCAPI_WEBSOCKET_DERIBIT_CHANNEL_QUOTE;
} else if (marketDepthRequested <= 20) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({10, 20}));
channelId = CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK;
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else {
@@ -188,83 +173,15 @@ class MarketDataServiceDeribit : public MarketDataService {
sendStringList.push_back(sendString);
return sendStringList;
}
//////////////////////////////////////////////////
// BEGIN - BTS Custom Code
//////////////////////////////////////////////////
std::unordered_set<std::int64_t> activeHeartbeatReqs;
std::unordered_set<std::int64_t> activeReqs;
template <class T>
static std::pair<T, bool> readJson(rapidjson::Document &doc, const std::string &key);
static bool isHeartbeatRequest(const std::string &textMessage) {
rj::Document doc;
doc.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
auto resultIt = doc.FindMember("result");
if (resultIt != doc.MemberEnd()) {
return false;
}
auto paramsIt = doc.FindMember("params");
if (paramsIt == doc.MemberEnd() || !paramsIt->value.IsObject()) {
return false;
}
const auto params = paramsIt->value.GetObject();
auto typeIt = params.FindMember("type");
if (typeIt == params.MemberEnd() || !typeIt->value.IsString()) {
return false;
}
const std::string type{typeIt->value.GetString()};
if (type != "test_request") {
return false;
}
return true;
}
void sendHeartbeat(wspp::connection_hdl hdl) {
CCAPI_LOGGER_TRACE("MarketDataServiceDeribit::sendHeartbeat");
rj::Document document;
document.SetObject();
rj::Document::AllocatorType &allocator = document.GetAllocator();
auto now = UtilTime::now();
const auto rpcId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
appendParam(document, allocator, rpcId, "/public/test", {});
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
static const std::size_t MAX_ACTIVE_HEARTBEATS = 32;
if (activeHeartbeatReqs.size() > MAX_ACTIVE_HEARTBEATS) {
CCAPI_LOGGER_WARN("MarketDataServiceDeribit::sendHeartbeat. Too many active heartbeat reqs ("
+ std::to_string(activeHeartbeatReqs.size()) + "): "
+ ccapi::toString(activeHeartbeatReqs));
activeHeartbeatReqs.clear();
}
activeHeartbeatReqs.insert(rpcId);
CCAPI_LOGGER_INFO("MarketDataServiceDeribit::sendHeartbeat. Sending heartbeat rpcId: " + std::to_string(rpcId));
this->send(hdl, msg, wspp::frame::opcode::text, ec);
if (ec) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
}
}
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override;
//////////////////////////////////////////////////
// END - BTS Custom Code
//////////////////////////////////////////////////
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -387,7 +304,7 @@ class MarketDataServiceDeribit : public MarketDataService {
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, msg, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, msg, ec);
@@ -600,79 +517,6 @@ class MarketDataServiceDeribit : public MarketDataService {
std::map<std::string, std::set<int64_t>> subscriptionJsonrpcIdSetByConnectionIdMap;
std::string restTarget;
};
//////////////////////////////////////////////////
// BEGIN - BTS Custom Code
//////////////////////////////////////////////////
template <>
inline std::pair<std::string, bool> MarketDataServiceDeribit::readJson<std::string>(rapidjson::Document &doc, const std::string &key) {
auto member = doc.FindMember(key.c_str());
if (member == doc.MemberEnd() || !member->value.IsString()) {
return {{}, false};
}
return {member->value.GetString(), true};
}
template <>
inline std::pair<std::int64_t, bool> MarketDataServiceDeribit::readJson<std::int64_t>(rapidjson::Document &doc, const std::string &key) {
auto member = doc.FindMember(key.c_str());
if (member == doc.MemberEnd()) {
return {0, false};
}
const auto &v = member->value;
if (v.IsInt64()) {
return {v.GetInt64(), true};
}
if (v.IsInt()) {
return {v.GetInt(), true};
}
if (v.IsUint64()) {
return {static_cast<std::int64_t>(v.GetUint64()), true};
}
if (v.IsUint()) {
return {static_cast<std::int64_t>(v.GetUint()), true};
}
if (v.IsString()) {
const char *cstr = v.GetString();
char* endPtr;
const std::int64_t result = std::strtol(cstr, &endPtr, 10);
if (*endPtr == '\0') {
return {result, true};
}
}
return {0, false};
}
inline void MarketDataServiceDeribit::onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) {
if (isHeartbeatRequest(textMessage)) {
sendHeartbeat(hdl);
return;
}
rj::Document doc;
doc.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
const auto [rpcId, hasRpcId] = readJson<std::int64_t>(doc, "id");
if (hasRpcId) {
if (activeHeartbeatReqs.erase(rpcId) != 0) {
return;
}
const auto [resStr, hasResStr] = readJson<std::string>(doc, "result");
if (hasResStr && resStr == "ok") {
if (activeReqs.erase(rpcId) == 0) {
CCAPI_LOGGER_ERROR("MarketDataServiceDeribit::onTextMessage. Received rpc response with unknown id:\n{}" + textMessage);
} else {
CCAPI_LOGGER_DEBUG("MarketDataServiceDeribit::onTextMessage. Received rpc response:\n{}" + textMessage);
}
return;
}
}
MarketDataService::onTextMessage(hdl, textMessage, timeReceived);
}
//////////////////////////////////////////////////
// END - BTS Custom Code
//////////////////////////////////////////////////
} /* namespace ccapi */
#endif
#endif
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceErisx : public MarketDataService {
public:
MarketDataServiceErisx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_ERISX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
@@ -69,14 +69,14 @@ class MarketDataServiceErisx : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceFtx : public MarketDataServiceFtxBase {
public:
MarketDataServiceFtx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
@@ -19,7 +19,7 @@ class MarketDataServiceFtx : public MarketDataServiceFtxBase {
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceFtxBase : public MarketDataService {
public:
MarketDataServiceFtxBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->shouldAlignSnapshot = true;
this->getRecentTradesTarget = "/api/markets/{market_name}/trades";
@@ -86,14 +86,14 @@ class MarketDataServiceFtxBase : public MarketDataService {
return intToHex(csCalc);
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceFtxUs : public MarketDataServiceFtxBase {
public:
MarketDataServiceFtxUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX_US;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
@@ -19,7 +19,7 @@ class MarketDataServiceFtxUs : public MarketDataServiceFtxBase {
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceGateio : public MarketDataServiceGateioBase {
public:
MarketDataServiceGateio(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GATEIO_API_KEY;
this->setupCredential({this->apiKeyName});
std::string prefix = "/api/v4";
@@ -36,6 +36,7 @@ class MarketDataServiceGateio : public MarketDataServiceGateioBase {
this->websocketChannelTrades = CCAPI_WEBSOCKET_GATEIO_CHANNEL_TRADES;
this->websocketChannelBookTicker = CCAPI_WEBSOCKET_GATEIO_CHANNEL_BOOK_TICKER;
this->websocketChannelOrderBook = CCAPI_WEBSOCKET_GATEIO_CHANNEL_ORDER_BOOK;
this->websocketChannelCandlesticks = CCAPI_WEBSOCKET_GATEIO_CHANNEL_CANDLESTICKS;
this->symbolName = "currency_pair";
}
virtual ~MarketDataServiceGateio() {}
@@ -7,14 +7,14 @@ namespace ccapi {
class MarketDataServiceGateioBase : public MarketDataService {
public:
MarketDataServiceGateioBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~MarketDataServiceGateioBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl,
@@ -32,19 +32,19 @@ class MarketDataServiceGateioBase : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = this->websocketChannelBookTicker;
} else {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
std::string updateSpeed;
if (this->isDerivatives) {
updateSpeed = "0";
} else {
if (conflateIntervalMilliSeconds < 1000) {
if (conflateIntervalMilliseconds < 1000) {
updateSpeed = "100ms";
} else {
updateSpeed = "1000ms";
@@ -55,6 +55,10 @@ class MarketDataServiceGateioBase : public MarketDataService {
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "s", "m", "h", "d", "w");
channelId = this->websocketChannelCandlesticks + interval;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -62,20 +66,28 @@ class MarketDataServiceGateioBase : public MarketDataService {
std::vector<std::string> sendStringList;
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
if (channelId == this->websocketChannelBookTicker || channelId == this->websocketChannelTrades) {
if (channelId == this->websocketChannelBookTicker || channelId == this->websocketChannelTrades ||
channelId.rfind(this->websocketChannelCandlesticks, 0) == 0) {
std::vector<std::string> exchangeSubscriptionIdList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
document.AddMember("time", rj::Value(UtilTime::getUnixTimestamp(now)).Move(), allocator);
document.AddMember("channel", rj::Value(channelId.c_str(), allocator).Move(), allocator);
std::string channel(channelId);
if (channelId.rfind(this->websocketChannelCandlesticks, 0) == 0) {
channel = this->websocketChannelCandlesticks;
}
document.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
rj::Value payload(rj::kArrayType);
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
if (channelId == this->websocketChannelBookTicker) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
if (channelId.rfind(this->websocketChannelCandlesticks, 0) == 0) {
payload.PushBack(rj::Value(std::string(channelId.substr(this->websocketChannelCandlesticks.length())).c_str(), allocator).Move(), allocator);
}
payload.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
@@ -83,13 +95,12 @@ class MarketDataServiceGateioBase : public MarketDataService {
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
}
document.AddMember("payload", payload, allocator);
if (!this->isDerivatives) {
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
}
// if (!this->isDerivatives) {
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
// }
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
@@ -121,15 +132,15 @@ class MarketDataServiceGateioBase : public MarketDataService {
std::string exchangeSubscriptionId = std::string(this->websocketChannelOrderBook) + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
if (!this->isDerivatives) {
std::vector<std::string> exchangeSubscriptionIdList;
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
}
// if (!this->isDerivatives) {
std::vector<std::string> exchangeSubscriptionIdList;
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
// }
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
@@ -141,14 +152,14 @@ class MarketDataServiceGateioBase : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -165,20 +176,19 @@ class MarketDataServiceGateioBase : public MarketDataService {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) {
auto splitted = UtilString::split(exchangeSubscriptionId, '|');
std::string channelId = splitted.at(0);
std::string symbolId = splitted.at(1);
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
std::vector<std::string> correlationIdList_2 =
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
const auto& it = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).lower_bound(channelId);
if (it != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
const std::string& k = it->first;
if (k.compare(0, channelId.size(), channelId) == 0) {
std::vector<std::string> correlationIdList_2 = it->second.at(symbolId);
correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end());
}
}
@@ -199,124 +209,171 @@ class MarketDataServiceGateioBase : public MarketDataService {
if (eventType == "update" || eventType == "all") {
std::string channel = document["channel"].GetString();
const rj::Value& result = document["result"];
std::string symbol;
std::string originalChannelId(channel);
if (result.IsObject()) {
auto it = result.FindMember(symbolName.c_str());
auto its = result.FindMember("s");
symbol = it != result.MemberEnd() ? it->value.GetString() : (its != result.MemberEnd() ? its->value.GetString() : "");
}
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId;
std::string channelId;
std::string symbolId;
std::map<std::string, std::string> optionMap;
if (!symbol.empty()) {
exchangeSubscriptionId = channel + "|" + symbol;
channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
} else {
channelId = channel;
}
if (channelId == this->websocketChannelBookTicker) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
{
std::string p = result["b"].GetString();
if (!p.empty()) {
std::string channelId(originalChannelId);
std::string symbolId;
if (channel == this->websocketChannelCandlesticks) {
std::string n = result["n"].GetString();
auto first_of = n.find_first_of("_");
channelId = originalChannelId + n.substr(0, first_of);
symbolId = n.substr(first_of + 1);
} else {
auto it = result.FindMember(symbolName.c_str());
auto its = result.FindMember("s");
symbolId = it != result.MemberEnd() ? it->value.GetString() : (its != result.MemberEnd() ? its->value.GetString() : "");
}
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId;
std::map<std::string, std::string> optionMap;
if (!symbolId.empty()) {
exchangeSubscriptionId = channelId + "|" + symbolId;
optionMap = (*this->optionMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).lower_bound("channelId")).second.at(symbolId);
}
if (channel == this->websocketChannelBookTicker) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
{
std::string p = result["b"].GetString();
if (!p.empty()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["B"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
}
{
std::string p = result["a"].GetString();
if (!p.empty()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["A"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channel == this->websocketChannelOrderBook) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : result["bids"].GetArray()) {
if (bidIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["B"].GetString())});
dataPoint.insert(
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
++bidIndex;
}
}
{
std::string p = result["a"].GetString();
if (!p.empty()) {
int askIndex = 0;
for (const auto& x : result["asks"].GetArray()) {
if (askIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["A"].GetString())});
dataPoint.insert(
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
++askIndex;
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId.rfind(this->websocketChannelOrderBook, 0) == 0) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : result["bids"].GetArray()) {
if (bidIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
++bidIndex;
}
int askIndex = 0;
for (const auto& x : result["asks"].GetArray()) {
if (askIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
++askIndex;
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == this->websocketChannelTrades) {
if (this->isDerivatives) {
for (const auto& x : result.GetArray()) {
symbol = x["contract"].GetString();
exchangeSubscriptionId = channel + "|" + symbol;
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channel == this->websocketChannelTrades) {
if (!this->isDerivatives) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(x["create_time_ms"].GetString()));
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(result["create_time_ms"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
std::string size = x["size"].GetString();
std::string sizeAbs;
bool isBuyerMaker;
if (size.at(0) == '-') {
sizeAbs = size.substr(1);
isBuyerMaker = true;
} else {
sizeAbs = size;
isBuyerMaker = false;
}
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(sizeAbs)});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, isBuyerMaker ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(result["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(result["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(result["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(result["side"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else {
} else if (channel == this->websocketChannelCandlesticks) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(result["create_time_ms"].GetString()));
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::seconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(result["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(result["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(result["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(result["side"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, result["o"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, result["h"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, result["l"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, result["c"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, result["a"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, result["v"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (result.IsArray()) {
if (channel == this->websocketChannelTrades) {
if (this->isDerivatives) {
for (const auto& x : result.GetArray()) {
std::string symbolId = x["contract"].GetString();
std::string exchangeSubscriptionId = channel + "|" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(x["create_time_ms"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
std::string size = x["size"].GetString();
std::string sizeAbs;
bool isBuyerMaker;
if (size.at(0) == '-') {
sizeAbs = size.substr(1);
isBuyerMaker = true;
} else {
sizeAbs = size;
isBuyerMaker = false;
}
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(sizeAbs)});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, isBuyerMaker ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else if (channel == this->websocketChannelCandlesticks) {
if (this->isDerivatives) {
for (const auto& x : result.GetArray()) {
std::string n = x["n"].GetString();
auto first_of = n.find_first_of("_");
std::string channelId = originalChannelId + n.substr(0, first_of);
std::string symbolId = n.substr(first_of + 1);
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::seconds(std::stoll(x["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x["o"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x["h"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x["l"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x["c"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x["v"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
}
}
@@ -326,6 +383,7 @@ class MarketDataServiceGateioBase : public MarketDataService {
std::string websocketChannelTrades;
std::string websocketChannelBookTicker;
std::string websocketChannelOrderBook;
std::string websocketChannelCandlesticks;
};
} /* namespace ccapi */
#endif
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBase {
public:
MarketDataServiceGateioPerpetualFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
std::string prefix = "/api/v4";
@@ -37,6 +37,7 @@ class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBa
this->websocketChannelTrades = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_TRADES;
this->websocketChannelBookTicker = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_BOOK_TICKER;
this->websocketChannelOrderBook = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_ORDER_BOOK;
this->websocketChannelCandlesticks = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_CANDLESTICKS;
this->symbolName = "contract";
}
virtual ~MarketDataServiceGateioPerpetualFutures() {}
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceGemini : public MarketDataService {
public:
MarketDataServiceGemini(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GEMINI;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/marketdata";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/v1/trades/:symbol";
this->getInstrumentTarget = "/v1/symbols/details/:symbol";
this->getInstrumentsTarget = "/v1/symbols";
@@ -39,7 +39,7 @@ class MarketDataServiceGemini : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
int marketDepthSubscribedToExchange = 1;
@@ -49,7 +49,7 @@ class MarketDataServiceGemini : public MarketDataService {
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override { return std::vector<std::string>(); }
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -131,7 +131,7 @@ class MarketDataServiceGemini : public MarketDataService {
if (marketDepthSubscribedToExchange == 1) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnectionPtr->id][channelId][symbolId] = true;
}
auto exchangeSubscriptionId = wsConnectionPtr->url;
auto exchangeSubscriptionId = wsConnectionPtr->getUrl();
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnectionPtr->id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnectionPtr->id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
std::vector<std::string> correlationIdList_2 =
@@ -191,14 +191,14 @@ class MarketDataServiceGemini : public MarketDataService {
}
#endif
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -208,7 +208,7 @@ class MarketDataServiceGemini : public MarketDataService {
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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, "");
return;
@@ -222,10 +222,10 @@ class MarketDataServiceGemini : public MarketDataService {
}
if (type == "update" && !document["events"].GetArray().Empty()) {
MarketDataMessage marketDataMessage;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
marketDataMessage.exchangeSubscriptionId = wsConnection.url;
#else
marketDataMessage.exchangeSubscriptionId = wsConnectionPtr->url;
marketDataMessage.exchangeSubscriptionId = wsConnectionPtr->getUrl();
#endif
TimePoint time = timeReceived;
auto it = document.FindMember("timestampms");
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceHuobi : public MarketDataServiceHuobiBase {
public:
MarketDataServiceHuobi(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/market/history/trade";
this->getInstrumentTarget = "/v1/common/symbols";
this->getInstrumentsTarget = "/v1/common/symbols";
@@ -35,24 +35,19 @@ class MarketDataServiceHuobi : public MarketDataServiceHuobiBase {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
CCAPI_LOGGER_TRACE("");
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
CCAPI_LOGGER_TRACE("");
if (conflateIntervalMilliSeconds < 100) {
CCAPI_LOGGER_TRACE("");
if (conflateIntervalMilliseconds < 100) {
if (marketDepthRequested == 1) {
CCAPI_LOGGER_TRACE("");
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
} else {
CCAPI_LOGGER_TRACE("");
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE;
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
} else if (conflateIntervalMilliSeconds < 1000) {
} else if (conflateIntervalMilliseconds < 1000) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
} else {
@@ -7,10 +7,10 @@ namespace ccapi {
class MarketDataServiceHuobiBase : public MarketDataService {
public:
MarketDataServiceHuobiBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->needDecompressWebsocketMessage = true;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ErrorCode ec = this->inflater.init(false, 31);
#else
this->inflater.setWindowBitsOverride(31);
@@ -26,7 +26,7 @@ class MarketDataServiceHuobiBase : public MarketDataService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"ping\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + "}", wspp::frame::opcode::text, ec);
@@ -108,14 +108,14 @@ class MarketDataServiceHuobiBase : public MarketDataService {
return url + "|" + field + "|" + subscription.getSerializedOptions();
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -266,7 +266,7 @@ class MarketDataServiceHuobiBase : public MarketDataService {
payload += document["ping"].GetString();
payload += "}";
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, payload, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, payload, ec);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceHuobiCoinSwap : public MarketDataServiceHuobiDerivativesBase {
public:
MarketDataServiceHuobiCoinSwap(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH;
this->getInstrumentTarget = "/swap-api/v1/swap_contract_info";
this->getInstrumentsTarget = "/swap-api/v1/swap_contract_info";
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase {
public:
MarketDataServiceHuobiDerivativesBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->isDerivatives = true;
}
@@ -15,9 +15,9 @@ class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (conflateIntervalMilliSeconds < 1000) {
if (conflateIntervalMilliseconds < 1000) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
} else {
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceHuobiUsdtSwap : public MarketDataServiceHuobiDerivativesBase {
public:
MarketDataServiceHuobiUsdtSwap(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = CCAPI_HUOBI_USDT_SWAP_GET_RECENT_TRADES_PATH;
this->getInstrumentTarget = "/linear-swap-api/v1/swap_contract_info";
this->getInstrumentsTarget = "/linear-swap-api/v1/swap_contract_info";
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceKraken : public MarketDataService {
public:
MarketDataServiceKraken(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/0/public/Trades";
this->getInstrumentTarget = "/0/public/AssetPairs";
this->getInstrumentsTarget = "/0/public/AssetPairs";
@@ -37,7 +37,7 @@ class MarketDataServiceKraken : public MarketDataService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -52,12 +52,15 @@ class MarketDataServiceKraken : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 25, 100, 500, 1000}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({10, 25, 100, 500, 1000}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else if (field == CCAPI_CANDLESTICK) {
std::string interval = std::to_string(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)) / 60);
channelId += "-" + interval;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -120,19 +123,43 @@ class MarketDataServiceKraken : public MarketDataService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
} else if (channelId.rfind(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC, 0) == 0) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
rj::Value instrument(rj::kArrayType);
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListBySymbolId.first;
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
instrument.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
document.AddMember("pair", instrument, allocator);
rj::Value subscription(rj::kObjectType);
subscription.AddMember("interval", rj::Value(std::stoi(channelId.substr(std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC).length() + 1))).Move(),
allocator);
subscription.AddMember("name", rj::Value(std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC).c_str(), allocator).Move(), allocator);
document.AddMember("subscription", subscription, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
}
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -220,10 +247,10 @@ class MarketDataServiceKraken : public MarketDataService {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelNameWithSuffix == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE) {
auto symbolId = std::string(document[documentSize - 1].GetString());
for (const auto& x : document[1].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
auto symbolId = std::string(document[documentSize - 1].GetString());
marketDataMessage.exchangeSubscriptionId = channelNameWithSuffix + "|" + symbolId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
auto timePair = UtilTime::divide(std::string(x[2].GetString()));
@@ -237,6 +264,27 @@ class MarketDataServiceKraken : public MarketDataService {
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelNameWithSuffix.rfind(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC, 0) == 0) {
int intervalSeconds = std::stoi(channelNameWithSuffix.substr(std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC).length() + 1)) * 60;
auto symbolId = std::string(document[documentSize - 1].GetString());
const rj::Value& x = document[1].GetArray();
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.exchangeSubscriptionId = channelNameWithSuffix + "|" + symbolId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
auto timePair = UtilTime::divide(std::string(x[1].GetString()));
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first - intervalSeconds));
marketDataMessage.tp = tp;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[7].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME,
Decimal(UtilString::printDoubleScientific(std::stod(x[6].GetString()) * std::stod(x[7].GetString()))).toString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (document.IsObject() && document.HasMember("event")) {
std::string eventPayload = std::string(document["event"].GetString());
@@ -252,6 +300,8 @@ class MarketDataServiceKraken : public MarketDataService {
std::string exchangeSubscriptionId = document["subscription"]["name"].GetString();
if (exchangeSubscriptionId == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK) {
exchangeSubscriptionId += "-" + std::string(document["subscription"]["depth"].GetString());
} else if (exchangeSubscriptionId == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC) {
exchangeSubscriptionId += "-" + std::string(document["subscription"]["interval"].GetString());
}
std::string symbolId = document["pair"].GetString();
exchangeSubscriptionId += "|" + symbolId;
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceKrakenFutures : public MarketDataService {
public:
MarketDataServiceKrakenFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
std::string prefix("/derivatives/api/v3");
this->getRecentTradesTarget = prefix + "/history";
this->getInstrumentTarget = prefix + "/instruments";
@@ -80,14 +80,14 @@ class MarketDataServiceKrakenFutures : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,19 +7,19 @@ namespace ccapi {
class MarketDataServiceKucoin : public MarketDataServiceKucoinBase {
public:
MarketDataServiceKucoin(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
// this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -32,16 +32,22 @@ class MarketDataServiceKucoin : public MarketDataServiceKucoinBase {
this->apiPassphraseName = CCAPI_KUCOIN_API_PASSPHRASE;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
this->getRecentTradesTarget = "/api/v1/market/histories";
this->getHistoricalTradesTarget = "/api/v1/market/histories";
this->getRecentCandlesticksTarget = "/api/v1/market/candles";
this->getHistoricalCandlesticksTarget = "/api/v1/market/candles";
this->getMarketDepthTarget = "/api/v1/market/orderbook/level2";
this->getInstrumentTarget = "/api/v1/symbols";
this->getInstrumentsTarget = "/api/v1/symbols";
this->channelMarketTicker = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_TICKER;
this->channelMarketLevel2Depth5 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH5;
this->channelMarketLevel2Depth50 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH50;
this->channelMarketLevel2 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2;
this->channelMarketKlines = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_KLINES;
this->tickerSubject = "trade.ticker";
this->tickerBestBidPriceKey = "bestBid";
this->tickerBestAskPriceKey = "bestAsk";
this->matchSubject = "trade.l3match";
this->klineSubject = "trade.candles.update";
this->level2Subject = "level2";
this->recentTradesTimeKey = "time";
}
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceKucoinBase : public MarketDataService {
public:
MarketDataServiceKucoinBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~MarketDataServiceKucoinBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
@@ -18,7 +18,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (this->isDerivatives) {
if (marketDepthRequested == 1) {
@@ -29,7 +29,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
channelId = this->channelMarketLevel2Depth50;
}
} else {
// if (conflateIntervalMilliSeconds < 100) {
// if (conflateIntervalMilliseconds < 100) {
// channelId = this->channelMarketLevel2;
// }else{
if (marketDepthRequested == 1) {
@@ -41,9 +41,13 @@ class MarketDataServiceKucoinBase : public MarketDataService {
}
// }
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "", "min", "hour", "day", "week");
channelId += interval;
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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);
@@ -95,7 +99,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override {
@@ -124,7 +128,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
urlWebsocketBase += std::string(instanceServer["endpoint"].GetString());
urlWebsocketBase += "?token=";
urlWebsocketBase += std::string(document["data"]["token"].GetString());
wsConnectionPtr->url = urlWebsocketBase;
wsConnectionPtr->setUrl(urlWebsocketBase);
that->connect(wsConnectionPtr);
for (const auto& subscription : wsConnectionPtr->subscriptionList) {
auto instrument = subscription.getInstrument();
@@ -141,7 +145,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#endif
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -155,6 +159,9 @@ class MarketDataServiceKucoinBase : public MarketDataService {
if (channelId == this->channelMarketTicker || channelId == this->channelMarketLevel2Depth5 || channelId == this->channelMarketLevel2Depth50) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
if (!this->channelMarketKlines.empty() && channelId.rfind(this->channelMarketKlines, 0) == 0) {
exchangeSubscriptionId = this->channelMarketKlines + ":" + symbolId + "_" + channelId.substr(this->channelMarketKlines.length());
}
symbolListByTopicMap[channelId].push_back(symbolId);
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
@@ -163,28 +170,56 @@ class MarketDataServiceKucoinBase : public MarketDataService {
for (const auto& x : symbolListByTopicMap) {
auto topic = x.first;
auto symbolList = x.second;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("type", rj::Value("subscribe").Move(), allocator);
document.AddMember("privateChannel", false, allocator);
document.AddMember("response", true, allocator);
document.AddMember("topic", rj::Value((topic + ":" + UtilString::join(symbolList, ",")).c_str(), allocator).Move(), allocator);
int nextRequestId = this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id];
std::string requestId = std::to_string(nextRequestId);
std::vector<std::string> exchangeSubscriptionIdList;
for (const auto& symbol : symbolList) {
exchangeSubscriptionIdList.push_back(topic + ":" + symbol);
if (!this->channelMarketKlines.empty() && topic.rfind(this->channelMarketKlines, 0) == 0) {
for (const auto& symbol : symbolList) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("type", rj::Value("subscribe").Move(), allocator);
document.AddMember("privateChannel", false, allocator);
document.AddMember("response", true, allocator);
std::string exchangeSubscriptionId =
std::string(this->channelMarketKlines) + ":" + symbol + "_" + topic.substr(std::string(this->channelMarketKlines).length());
document.AddMember("topic", rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
int nextRequestId = this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id];
std::string requestId = std::to_string(nextRequestId);
std::vector<std::string> exchangeSubscriptionIdList;
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
} else {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("type", rj::Value("subscribe").Move(), allocator);
document.AddMember("privateChannel", false, allocator);
document.AddMember("response", true, allocator);
document.AddMember("topic", rj::Value((topic + ":" + UtilString::join(symbolList, ",")).c_str(), allocator).Move(), allocator);
int nextRequestId = this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id];
std::string requestId = std::to_string(nextRequestId);
std::vector<std::string> exchangeSubscriptionIdList;
for (const auto& symbol : symbolList) {
exchangeSubscriptionIdList.push_back(topic + ":" + symbol);
}
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
return sendStringList;
}
@@ -238,14 +273,14 @@ class MarketDataServiceKucoinBase : public MarketDataService {
}
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -257,7 +292,8 @@ class MarketDataServiceKucoinBase : public MarketDataService {
if (it != document.MemberEnd()) {
std::string type = it->value.GetString();
if (type == "message") {
if (std::string(document["subject"].GetString()) == "trade.l2update") {
std::string subject = document["subject"].GetString();
if (subject == "trade.l2update") {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
std::string exchangeSubscriptionId = document["topic"].GetString();
@@ -292,7 +328,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
int64_t versionId = std::stoll(data["sequenceEnd"].GetString());
this->processOrderBookWithVersionId(versionId, wsConnection, channelId, symbolId, exchangeSubscriptionId, optionMap, marketDataMessageList,
marketDataMessage);
} else if (std::string(document["subject"].GetString()) == this->tickerSubject) {
} else if (subject == this->tickerSubject) {
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId = document["topic"].GetString();
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
@@ -320,7 +356,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (std::string(document["subject"].GetString()) == this->level2Subject) {
} else if (subject == this->level2Subject) {
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId = document["topic"].GetString();
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
@@ -353,7 +389,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (std::string(document["subject"].GetString()) == this->matchSubject) {
} else if (subject == this->matchSubject) {
const rj::Value& data = document["data"];
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
@@ -369,18 +405,35 @@ class MarketDataServiceKucoinBase : public MarketDataService {
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(data["side"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (subject == this->klineSubject) {
const rj::Value& x = document["data"]["candles"].GetArray();
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
std::string exchangeSubscriptionId = document["topic"].GetString();
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePoint(std::make_pair(std::stoll(x[0].GetString()), 0));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x[6].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (type == "welcome") {
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval"));
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout"));
if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
if (this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Service::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
this->startSubscribe(wsConnection);
@@ -400,11 +453,11 @@ class MarketDataServiceKucoinBase : public MarketDataService {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id);
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id);
for (const auto& exchangeSubscriptionId : exchangeSubscriptionIdList) {
auto splitted = UtilString::split(exchangeSubscriptionId, ":");
auto channelId = splitted.at(0);
@@ -449,7 +502,8 @@ class MarketDataServiceKucoinBase : public MarketDataService {
case Request::Operation::GENERIC_PUBLIC_REQUEST: {
MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
req.method(http::verb::get);
auto target = this->getRecentTradesTarget;
std::string queryString;
@@ -457,6 +511,63 @@ class MarketDataServiceKucoinBase : public MarketDataService {
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
req.method(http::verb::get);
auto target = this->getRecentCandlesticksTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
if (this->isDerivatives) {
this->appendParam(queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "granularity"},
{CCAPI_START_TIME_SECONDS, "from"},
{CCAPI_END_TIME_SECONDS, "to"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, [that = shared_from_base<MarketDataServiceKucoinBase>()](
const std::string& input) { return std::to_string(std::stoi(input) / 60); }},
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceKucoinBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceKucoinBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
} else {
this->appendParam(queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "type"},
{CCAPI_START_TIME_SECONDS, "startAt"},
{CCAPI_END_TIME_SECONDS, "endAt"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS,
[that = shared_from_base<MarketDataServiceKucoinBase>()](const std::string& input) {
return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), "", "min", "hour", "day", "week");
}},
});
}
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_MARKET_DEPTH: {
req.method(http::verb::get);
auto target = this->getMarketDepthTarget;
;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendSymbolId(queryString, symbolId, "symbol");
std::string maxMarketDepthStr = mapGetWithDefault(param, std::string(CCAPI_MARKET_DEPTH_MAX));
if (maxMarketDepthStr.empty()) {
if (this->isDerivatives) {
std::string toReplace = "depth";
target.replace(target.find(toReplace), toReplace.length(), "snapshot");
}
} else {
target = this->getMarketDepthTarget + (this->isDerivatives ? "" : "_") +
std::to_string(this->calculateMarketDepthAllowedByExchange(std::stoi(maxMarketDepthStr), std::vector<int>({20, 100})));
}
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
@@ -476,7 +587,8 @@ class MarketDataServiceKucoinBase : public MarketDataService {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
for (const auto& x : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
@@ -490,6 +602,52 @@ class MarketDataServiceKucoinBase : public MarketDataService {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
for (const auto& x : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.tp = this->isDerivatives ? TimePoint(std::chrono::milliseconds(std::stoll(x[0].GetString())))
: TimePoint(std::chrono::seconds(std::stoll(x[0].GetString())));
MarketDataMessage::TypeForDataPoint dataPoint;
if (this->isDerivatives) {
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, std::string(x[1].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, std::string(x[2].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, std::string(x[3].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, std::string(x[4].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, std::string(x[5].GetString())});
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, std::string(x[1].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, std::string(x[3].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, std::string(x[4].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, std::string(x[2].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, std::string(x[5].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, std::string(x[6].GetString())});
}
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_MARKET_DEPTH: {
const rj::Value& data = document["data"];
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.tp = this->isDerivatives ? TimePoint(std::chrono::nanoseconds(std::stoll(data["ts"].GetString())))
: TimePoint(std::chrono::milliseconds(std::stoll(data["time"].GetString())));
for (const auto& x : data["bids"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : data["asks"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
@@ -529,10 +687,12 @@ class MarketDataServiceKucoinBase : public MarketDataService {
std::string channelMarketLevel2Depth5;
std::string channelMarketLevel2Depth50;
std::string channelMarketLevel2;
std::string channelMarketKlines;
std::string tickerSubject;
std::string tickerBestBidPriceKey;
std::string tickerBestAskPriceKey;
std::string matchSubject;
std::string klineSubject;
std::string recentTradesTimeKey;
std::string level2Subject;
std::string apiPassphraseName;
@@ -7,19 +7,19 @@ namespace ccapi {
class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase {
public:
MarketDataServiceKucoinFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
// this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -28,6 +28,10 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase {
// }
// #endif
this->getRecentTradesTarget = "/api/v1/trade/history";
this->getHistoricalTradesTarget = "/api/v1/trade/history";
this->getRecentCandlesticksTarget = "/api/v1/kline/query";
this->getHistoricalCandlesticksTarget = "/api/v1/kline/query";
this->getMarketDepthTarget = "/api/v1/level2/depth";
this->getInstrumentTarget = "/api/v1/contracts/active";
this->getInstrumentsTarget = "/api/v1/contracts/active";
this->isDerivatives = true;
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceMexc : public MarketDataService {
public:
MarketDataServiceMexc(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC;
this->baseUrlWs = std::string(CCAPI_MEXC_URL_WS_BASE) + "/ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v3/trades";
this->getRecentAggTradesTarget = "/api/v3/aggTrades";
this->getInstrumentsTarget = "/api/v3/exchangeInfo";
@@ -37,7 +37,7 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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"})",
@@ -71,7 +71,7 @@ class MarketDataServiceMexc : public MarketDataService {
}
document.AddMember("params", params, allocator);
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
rj::StringBuffer stringBuffer;
@@ -105,14 +105,14 @@ class MarketDataServiceMexc : public MarketDataService {
}
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -126,11 +126,11 @@ class MarketDataServiceMexc : public MarketDataService {
std::string msg = document["msg"].GetString();
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) {
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceMexcFutures : public MarketDataService {
public:
MarketDataServiceMexcFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v1/contract/deals/{symbol}";
this->getInstrumentsTarget = "/api/v1/contract/detail";
}
@@ -36,7 +36,7 @@ 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
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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<WsConnection> wsConnectionPtr, ErrorCode& ec) override {
@@ -92,14 +92,14 @@ class MarketDataServiceMexcFutures : public MarketDataService {
}
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,31 +7,36 @@ namespace ccapi {
class MarketDataServiceOkx : public MarketDataService {
public:
MarketDataServiceOkx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_OKX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKX_PUBLIC_WS_PATH;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_OKX_API_KEY;
this->apiSecretName = CCAPI_OKX_API_SECRET;
this->apiPassphraseName = CCAPI_OKX_API_PASSPHRASE;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
this->getRecentTradesTarget = "/api/v5/market/trades";
this->getHistoricalTradesTarget = "/api/v5/market/history-trades";
this->getRecentCandlesticksTarget = "/api/v5/market/candles";
this->getHistoricalCandlesticksTarget = "/api/v5/market/history-candles";
this->getMarketDepthTarget = "/api/v5/market/books";
this->getRecentTradesTarget = "/api/v5/market/trades";
this->getInstrumentTarget = "/api/v5/public/instruments";
this->getInstrumentsTarget = "/api/v5/public/instruments";
}
@@ -40,13 +45,21 @@ class MarketDataServiceOkx : public MarketDataService {
private:
#endif
std::string getInstrumentGroup(const Subscription& subscription) override {
std::string baseUrlWsGivenSubscription(this->baseUrlWs);
if (subscription.getField() == CCAPI_CANDLESTICK) {
baseUrlWsGivenSubscription = this->sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKX_BUSINESS_WS_PATH;
}
return baseUrlWsGivenSubscription + "|" + subscription.getField() + "|" + subscription.getSerializedOptions() + "|" +
subscription.getSerializedCredential();
}
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); }
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (conflateIntervalMilliSeconds < 100) {
if (conflateIntervalMilliseconds < 100) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT;
} else if (marketDepthRequested <= 50) {
@@ -61,9 +74,13 @@ class MarketDataServiceOkx : public MarketDataService {
channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400;
}
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "s", "m", "H", "D", "W");
channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_CANDLESTICK + interval;
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
@@ -122,14 +139,14 @@ class MarketDataServiceOkx : public MarketDataService {
return intToHex(csCalc);
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -140,7 +157,7 @@ class MarketDataServiceOkx : public MarketDataService {
auto it = document.FindMember("event");
std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
if (eventStr == "login") {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->startSubscribe(wsConnection);
#else
this->startSubscribe(wsConnectionPtr);
@@ -249,6 +266,23 @@ class MarketDataServiceOkx : public MarketDataService {
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelId.rfind(CCAPI_WEBSOCKET_OKX_CHANNEL_CANDLESTICK, 0) == 0) {
for (const auto& datum : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[0].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, datum[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, datum[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, datum[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, datum[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, datum[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, datum[7].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
@@ -273,6 +307,66 @@ class MarketDataServiceOkx : public MarketDataService {
this->appendSymbolId(queryString, symbolId, "instId");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_HISTORICAL_TRADES: {
req.method(http::verb::get);
auto target = this->getHistoricalTradesTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TRADE_ID, "before"},
{CCAPI_END_TRADE_ID, "after"},
{CCAPI_START_TIME_SECONDS, "before"},
{CCAPI_END_TIME_SECONDS, "after"},
},
{
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceOkx>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceOkx>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "instId");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
req.method(http::verb::get);
auto target = this->getRecentCandlesticksTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "bar"},
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "before"},
{CCAPI_END_TIME_SECONDS, "after"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS,
[that = shared_from_base<MarketDataServiceOkx>()](const std::string& input) {
return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), "s", "m", "H", "D", "W");
}},
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceOkx>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceOkx>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "instId");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_MARKET_DEPTH: {
req.method(http::verb::get);
auto target = this->getMarketDepthTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_MARKET_DEPTH_MAX, "sz"},
});
this->appendSymbolId(queryString, symbolId, "instId");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
@@ -317,7 +411,8 @@ class MarketDataServiceOkx : public MarketDataService {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
for (const auto& datum : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
@@ -331,6 +426,42 @@ class MarketDataServiceOkx : public MarketDataService {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
for (const auto& x : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x[0].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x[7].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_MARKET_DEPTH: {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
const rj::Value& data = document["data"][0];
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["ts"].GetString()));
for (const auto& x : data["bids"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : data["asks"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceWhitebit : public MarketDataService {
public:
MarketDataServiceWhitebit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_WHITEBIT;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v4/public/trades/{market}";
this->getInstrumentsTarget = "/api/v4/public/markets";
this->methodDepthSubscribe = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) + "_subscribe";
@@ -40,7 +40,7 @@ class MarketDataServiceWhitebit : public MarketDataService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
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":[]})",
@@ -91,8 +91,8 @@ class MarketDataServiceWhitebit : public MarketDataService {
sendStringList.push_back(sendString);
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = {
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = {
exchangeSubscriptionId};
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
}
@@ -118,8 +118,7 @@ class MarketDataServiceWhitebit : public MarketDataService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
}
@@ -127,14 +126,14 @@ class MarketDataServiceWhitebit : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -216,11 +215,11 @@ class MarketDataServiceWhitebit : public MarketDataService {
std::vector<std::string> correlationIdList;
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) {
std::string channelId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
+294 -200
View File
@@ -31,7 +31,7 @@
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
// clang-format off
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#include "websocketpp/config/boost_config.hpp"
#include "websocketpp/client.hpp"
#include "websocketpp/common/connection_hdl.hpp"
@@ -41,7 +41,7 @@
#endif
// clang-format on
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && \
(defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \
defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \
@@ -69,9 +69,9 @@
namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
namespace ssl = boost::asio::ssl;
using tcp = boost::asio::ip::tcp;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
namespace ssl = net::ssl;
using tcp = net::ip::tcp;
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
namespace wspp = websocketpp;
#endif
namespace rj = rapidjson;
@@ -82,8 +82,8 @@ namespace ccapi {
*/
class Service : public std::enable_shared_from_this<Service> {
public:
typedef std::shared_ptr<ServiceContext> ServiceContextPtr;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
typedef ServiceContext* ServiceContextPtr;
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
typedef wspp::lib::error_code ErrorCode;
#else
typedef boost::system::error_code ErrorCode; // a.k.a. beast::error_code
@@ -117,16 +117,15 @@ class Service : public std::enable_shared_from_this<Service> {
sessionConfigs(sessionConfigs),
serviceContextPtr(serviceContextPtr),
resolver(*serviceContextPtr->ioContextPtr),
resolverWs(*serviceContextPtr->ioContextPtr),
httpConnectionPool(sessionOptions.httpConnectionPoolMaxSize) {
resolverWs(*serviceContextPtr->ioContextPtr) {
this->enableCheckPingPongWebsocketProtocolLevel = this->sessionOptions.enableCheckPingPongWebsocketProtocolLevel;
this->enableCheckPingPongWebsocketApplicationLevel = this->sessionOptions.enableCheckPingPongWebsocketApplicationLevel;
// this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pingWebsocketProtocolLevelIntervalMilliSeconds;
// this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds;
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pingWebsocketApplicationLevelIntervalMilliSeconds;
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pongWebsocketApplicationLevelTimeoutMilliSeconds;
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixIntervalMilliSeconds;
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixTimeoutMilliSeconds;
// this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pingWebsocketProtocolLevelIntervalMilliseconds;
// this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pongWebsocketProtocolLevelTimeoutMilliseconds;
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pingWebsocketApplicationLevelIntervalMilliseconds;
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pongWebsocketApplicationLevelTimeoutMilliseconds;
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixIntervalMilliseconds;
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixTimeoutMilliseconds;
}
virtual ~Service() {
for (const auto& x : this->pingTimerByMethodByConnectionIdMap) {
@@ -142,11 +141,20 @@ class Service : public std::enable_shared_from_this<Service> {
for (const auto& x : this->connectRetryOnFailTimerByConnectionIdMap) {
x.second->cancel();
}
if (this->httpConnectionPoolPurgeTimer) {
this->httpConnectionPoolPurgeTimer->cancel();
}
void purgeHttpConnectionPool() { this->httpConnectionPool.clear(); }
void purgeHttpConnectionPool(const std::string& localIpAddress) { this->httpConnectionPool.erase(localIpAddress); }
void purgeHttpConnectionPool(const std::string& localIpAddress, const std::string& baseUrl) { this->httpConnectionPool[localIpAddress].erase(baseUrl); }
void forceCloseWebsocketConnections() {
for (const auto& x : this->wsConnectionByIdMap) {
ErrorCode ec;
auto wsConnectionPtr = x.second;
this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason("force close"), ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown");
}
}
}
void purgeHttpConnectionPool() { this->httpConnectionPool.purge(); }
void stop() {
for (const auto& x : this->sendRequestDelayTimerByCorrelationIdMap) {
x.second->cancel();
@@ -155,21 +163,12 @@ class Service : public std::enable_shared_from_this<Service> {
this->shouldContinue = false;
for (const auto& x : this->wsConnectionByIdMap) {
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
auto wsConnection = x.second;
this->close(wsConnection, wsConnection.hdl, websocketpp::close::status::normal, "stop", ec);
#else
auto wsConnectionPtr = x.second;
this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason("stop"), ec);
#endif
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown");
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
#else
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false;
#endif
}
}
virtual void convertRequestForRestCustom(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
@@ -182,14 +181,14 @@ class Service : public std::enable_shared_from_this<Service> {
const std::map<std::string, std::string>& credential) {}
virtual void processSuccessfulTextMessageRest(int statusCode, const Request& request, const std::string& textMessage, const TimePoint& timeReceived,
Queue<Event>* eventQueuePtr) {}
std::shared_ptr<std::future<void>> sendRequest(Request& request, const bool useFuture, const TimePoint& now, long delayMilliSeconds,
std::shared_ptr<std::future<void>> sendRequest(Request& request, const bool useFuture, const TimePoint& now, long delayMilliseconds,
Queue<Event>* eventQueuePtr) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_DEBUG("request = " + toString(request));
CCAPI_LOGGER_DEBUG("useFuture = " + toString(useFuture));
TimePoint then;
if (delayMilliSeconds > 0) {
then = now + std::chrono::milliseconds(delayMilliSeconds);
if (delayMilliseconds > 0) {
then = now + std::chrono::milliseconds(delayMilliseconds);
} else {
then = now;
}
@@ -217,24 +216,24 @@ class Service : public std::enable_shared_from_this<Service> {
}
std::shared_ptr<std::promise<void>> promisePtr(promisePtrRaw);
HttpRetry retry(0, 0, "", promisePtr);
if (delayMilliSeconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliSeconds)));
if (delayMilliseconds > 0) {
TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliseconds)));
timerPtr->async_wait([that = shared_from_this(), request, req, retry, eventQueuePtr](ErrorCode const& ec) mutable {
if (ec) {
CCAPI_LOGGER_ERROR("request = " + toString(request) + ", sendRequest timer error: " + ec.message());
that->onError(Event::Type::REQUEST_STATUS, Message::Type::GENERIC_ERROR, ec, "timer", {request.getCorrelationId()}, eventQueuePtr);
} else {
auto thatReq = req;
auto now = UtilTime::now();
request.setTimeSent(now);
that->tryRequest(request, thatReq, retry, eventQueuePtr);
that->tryRequest(request, req, retry, eventQueuePtr);
}
that->sendRequestDelayTimerByCorrelationIdMap.erase(request.getCorrelationId());
});
this->sendRequestDelayTimerByCorrelationIdMap[request.getCorrelationId()] = timerPtr;
} else {
request.setTimeSent(now);
this->tryRequest(request, req, retry, eventQueuePtr);
net::post(*this->serviceContextPtr->ioContextPtr,
[that = shared_from_this(), request, req, retry, eventQueuePtr]() mutable { that->tryRequest(request, req, retry, eventQueuePtr); });
}
std::shared_ptr<std::future<void>> futurePtr(nullptr);
if (useFuture) {
@@ -303,10 +302,10 @@ class Service : public std::enable_shared_from_this<Service> {
// return output;
// }
typedef ServiceContext::SslContextPtr SslContextPtr;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
typedef ServiceContext::TlsClient TlsClient;
#endif
typedef std::shared_ptr<boost::asio::steady_timer> TimerPtr;
typedef std::shared_ptr<net::steady_timer> TimerPtr;
void setHostRestFromUrlRest(std::string baseUrlRest) {
auto hostPort = this->extractHostFromUrl(baseUrlRest);
this->hostRest = hostPort.first;
@@ -341,7 +340,7 @@ class Service : public std::enable_shared_from_this<Service> {
return std::static_pointer_cast<Derived>(shared_from_this());
}
void sendRequest(const http::request<http::string_body>& req, std::function<void(const beast::error_code&)> errorHandler,
std::function<void(const http::response<http::string_body>&)> responseHandler, long timeoutMilliSeconds) {
std::function<void(const http::response<http::string_body>&)> responseHandler, long timeoutMilliseconds) {
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
std::ostringstream oss;
oss << req;
@@ -358,11 +357,17 @@ class Service : public std::enable_shared_from_this<Service> {
}
std::shared_ptr<HttpConnection> httpConnectionPtr(new HttpConnection(this->hostRest, this->portRest, streamPtr));
CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr));
this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliSeconds, this->tcpResolverResultsRest);
std::shared_ptr<tcp::resolver> newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr));
CCAPI_LOGGER_TRACE("this->hostRest = " + this->hostRest);
CCAPI_LOGGER_TRACE("this->portRest = " + this->portRest);
newResolverPtr->async_resolve(this->hostRest, this->portRest,
beast::bind_front_handler(&Service::onResolve, shared_from_this(), httpConnectionPtr, newResolverPtr, req, errorHandler,
responseHandler, timeoutMilliseconds));
// this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliseconds, this->tcpResolverResultsRest);
}
void sendRequest(const std::string& host, const std::string& port, const http::request<http::string_body>& req,
std::function<void(const beast::error_code&)> errorHandler, std::function<void(const http::response<http::string_body>&)> responseHandler,
long timeoutMilliSeconds) {
long timeoutMilliseconds) {
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
std::ostringstream oss;
oss << req;
@@ -379,26 +384,28 @@ class Service : public std::enable_shared_from_this<Service> {
std::shared_ptr<HttpConnection> httpConnectionPtr(new HttpConnection(host, port, streamPtr));
CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr));
std::shared_ptr<tcp::resolver> newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr));
CCAPI_LOGGER_TRACE("host = " + host);
CCAPI_LOGGER_TRACE("port = " + port);
newResolverPtr->async_resolve(host, port,
beast::bind_front_handler(&Service::onResolve, shared_from_this(), httpConnectionPtr, newResolverPtr, req, errorHandler,
responseHandler, timeoutMilliSeconds));
responseHandler, timeoutMilliseconds));
}
void onResolve(std::shared_ptr<HttpConnection> httpConnectionPtr, std::shared_ptr<tcp::resolver> newResolverPtr, http::request<http::string_body> req,
std::function<void(const beast::error_code&)> errorHandler, std::function<void(const http::response<http::string_body>&)> responseHandler,
long timeoutMilliSeconds, beast::error_code ec, tcp::resolver::results_type tcpNewResolverResults) {
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, tcpNewResolverResults);
this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliseconds, tcpNewResolverResults);
}
void startConnect(std::shared_ptr<HttpConnection> httpConnectionPtr, http::request<http::string_body> req,
std::function<void(const beast::error_code&)> errorHandler, std::function<void(const http::response<http::string_body>&)> responseHandler,
long timeoutMilliSeconds, tcp::resolver::results_type tcpNewResolverResults) {
long timeoutMilliseconds, tcp::resolver::results_type tcpNewResolverResults) {
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
if (timeoutMilliSeconds > 0) {
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliSeconds));
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(
@@ -488,7 +495,7 @@ class Service : public std::enable_shared_from_this<Service> {
responseHandler(*resPtr);
}
template <class T>
std::shared_ptr<T> createStream(std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host) {
std::shared_ptr<T> createStream(net::io_context* iocPtr, net::ssl::context* ctxPtr, const std::string& host) {
std::shared_ptr<T> streamPtr(new T(*iocPtr, *ctxPtr));
// Set SNI Hostname (many hosts need this to handshake successfully)
if (!SSL_set_tlsext_host_name(streamPtr->native_handle(), host.c_str())) {
@@ -498,25 +505,15 @@ class Service : public std::enable_shared_from_this<Service> {
}
return streamPtr;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
template <>
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> createStream(std::shared_ptr<net::io_context> iocPtr,
std::shared_ptr<net::ssl::context> ctxPtr,
const std::string& host) {
CCAPI_LOGGER_TRACE("host = " + host)
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> createWsStream(net::io_context* iocPtr, net::ssl::context* ctxPtr) {
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(
new beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>(*iocPtr, *ctxPtr));
// Set SNI Hostname (many hosts need this to handshake successfully)
if (!SSL_set_tlsext_host_name(streamPtr->next_layer().native_handle(), host.c_str())) {
beast::error_code ec{static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()};
CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message());
throw ec;
}
return streamPtr;
}
#endif
// std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> createStream(std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr,
// std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> createStream(net::io_context* iocPtr, net::ssl::context* ctxPtr,
// const std::string& host) {
// std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(new beast::ssl_stream<beast::tcp_stream>(*iocPtr, *ctxPtr));
// // Set SNI Hostname (many hosts need this to handshake successfully)
@@ -527,31 +524,120 @@ class Service : public std::enable_shared_from_this<Service> {
// }
// return streamPtr;
// }
void performRequest(std::shared_ptr<HttpConnection> httpConnectionPtr, const Request& request, http::request<http::string_body>& req, const HttpRetry& retry,
Queue<Event>* eventQueuePtr) {
void performRequestWithNewHttpConnection(std::shared_ptr<HttpConnection> httpConnectionPtr, const Request& request, http::request<http::string_body>& req,
const HttpRetry& retry, Queue<Event>* eventQueuePtr) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr));
CCAPI_LOGGER_DEBUG("request = " + toString(request));
CCAPI_LOGGER_DEBUG("retry = " + toString(retry));
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
CCAPI_LOGGER_DEBUG("this->sessionOptions.httpRequestTimeoutMilliSeconds = " + toString(this->sessionOptions.httpRequestTimeoutMilliSeconds));
if (this->sessionOptions.httpRequestTimeoutMilliSeconds > 0) {
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliSeconds));
CCAPI_LOGGER_DEBUG("this->sessionOptions.httpRequestTimeoutMilliseconds = " + toString(this->sessionOptions.httpRequestTimeoutMilliseconds));
if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) {
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds));
}
CCAPI_LOGGER_TRACE("before async_connect");
beast::get_lowest_layer(stream).async_connect(
this->tcpResolverResultsRest,
beast::bind_front_handler(&Service::onConnect_2, shared_from_this(), httpConnectionPtr, request, req, retry, eventQueuePtr));
CCAPI_LOGGER_TRACE("after async_connect");
const auto& localIpAddress = request.getLocalIpAddress();
CCAPI_LOGGER_TRACE("localIpAddress = " + localIpAddress);
if (!localIpAddress.empty()) {
if (!beast::get_lowest_layer(stream).socket().is_open()) {
ErrorCode ec;
CCAPI_LOGGER_TRACE("before socket open");
beast::get_lowest_layer(stream).socket().open(net::ip::tcp::v4(), ec);
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket open", {request.getCorrelationId()}, eventQueuePtr);
return;
}
}
ErrorCode ec;
tcp::endpoint existingLocalEndpoint = beast::get_lowest_layer(stream).socket().local_endpoint(ec);
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket get local endpoint", {request.getCorrelationId()},
eventQueuePtr);
return;
}
tcp::endpoint localEndpoint(net::ip::address::from_string(localIpAddress),
0); // Note: Setting the port to 0 means the OS will select a free port for you
if (localEndpoint != existingLocalEndpoint) {
ErrorCode ec;
CCAPI_LOGGER_TRACE("before socket bind");
beast::get_lowest_layer(stream).socket().bind(localEndpoint, ec);
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket bind", {request.getCorrelationId()}, eventQueuePtr);
return;
}
}
}
std::shared_ptr<tcp::resolver> newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr));
CCAPI_LOGGER_TRACE("httpConnectionPtr->host = " + httpConnectionPtr->host);
CCAPI_LOGGER_TRACE("httpConnectionPtr->port = " + httpConnectionPtr->port);
newResolverPtr->async_resolve(
httpConnectionPtr->host, httpConnectionPtr->port,
beast::bind_front_handler(&Service::onResolveWorkaround, shared_from_this(), httpConnectionPtr, newResolverPtr, request, req, retry, eventQueuePtr));
CCAPI_LOGGER_FUNCTION_EXIT;
}
void onConnect_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, http::request<http::string_body> req, HttpRetry retry,
Queue<Event>* eventQueuePtr, beast::error_code ec, tcp::resolver::results_type::endpoint_type) {
CCAPI_LOGGER_TRACE("async_connect callback start");
void onResolveWorkaround(std::shared_ptr<HttpConnection> httpConnectionPtr, std::shared_ptr<tcp::resolver> newResolverPtr, Request request,
http::request<http::string_body> req, HttpRetry retry, Queue<Event>* eventQueuePtr, beast::error_code ec,
tcp::resolver::results_type tcpNewResolverResults) {
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "DNS resolve", {request.getCorrelationId()}, eventQueuePtr);
return;
}
CCAPI_LOGGER_TRACE("before asyncConnectWorkaround");
TimerPtr timerPtr{nullptr};
if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) {
timerPtr = std::make_shared<boost::asio::steady_timer>(*this->serviceContextPtr->ioContextPtr,
std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds));
timerPtr->async_wait([httpConnectionPtr](ErrorCode const& ec) {
if (ec) {
if (ec != net::error::make_error_code(net::error::basic_errors::operation_aborted)) {
CCAPI_LOGGER_ERROR("httpConnectionPtr = " + toString(*httpConnectionPtr) + ", connect timeout timer error: " + ec.message());
}
} else {
CCAPI_LOGGER_TRACE("httpConnectionPtr = " + toString(*httpConnectionPtr) + ", connect timeout timer triggered");
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
beast::get_lowest_layer(stream).socket().cancel();
}
});
}
this->asyncConnectWorkaround(httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr, tcpNewResolverResults, 0);
CCAPI_LOGGER_TRACE("after asyncConnectWorkaround");
}
// used to avoid asio close and reopen the socket and therefore losing the bound local ip address
void asyncConnectWorkaround(std::shared_ptr<HttpConnection> httpConnectionPtr, TimerPtr timerPtr, Request request, http::request<http::string_body> req,
HttpRetry retry, Queue<Event>* eventQueuePtr, tcp::resolver::results_type tcpNewResolverResults,
size_t tcpNewResolverResultsIndex) {
auto it = tcpNewResolverResults.begin();
std::advance(it, tcpNewResolverResultsIndex);
if (it == tcpNewResolverResults.end()) {
ErrorCode ec = net::error::make_error_code(net::error::misc_errors::not_found);
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "connect", {request.getCorrelationId()}, eventQueuePtr);
return;
}
CCAPI_LOGGER_TRACE("before async_connect");
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
beast::get_lowest_layer(stream).socket().async_connect(
*it, beast::bind_front_handler(&Service::onConnect_2, shared_from_this(), httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr,
tcpNewResolverResults, tcpNewResolverResultsIndex));
CCAPI_LOGGER_TRACE("after async_connect");
}
void onConnect_2(std::shared_ptr<HttpConnection> httpConnectionPtr, TimerPtr timerPtr, Request request, http::request<http::string_body> req, HttpRetry retry,
Queue<Event>* eventQueuePtr, tcp::resolver::results_type tcpNewResolverResults, size_t tcpNewResolverResultsIndex, beast::error_code ec) {
CCAPI_LOGGER_TRACE("async_connect callback start");
CCAPI_LOGGER_TRACE("local endpoint has address " + beast::get_lowest_layer(*httpConnectionPtr->streamPtr).socket().local_endpoint().address().to_string());
if (ec) {
CCAPI_LOGGER_TRACE("fail");
if (ec == net::error::make_error_code(net::error::basic_errors::operation_aborted)) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "connect attempt timeout", {request.getCorrelationId()}, eventQueuePtr);
return;
}
this->asyncConnectWorkaround(httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr, tcpNewResolverResults, tcpNewResolverResultsIndex + 1);
return;
}
timerPtr->cancel();
CCAPI_LOGGER_TRACE("connected");
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
// #ifdef CCAPI_DISABLE_NAGLE_ALGORITHM
@@ -576,8 +662,8 @@ class Service : public std::enable_shared_from_this<Service> {
void startWrite_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, http::request<http::string_body> req, HttpRetry retry,
Queue<Event>* eventQueuePtr) {
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
if (this->sessionOptions.httpRequestTimeoutMilliSeconds > 0) {
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliSeconds));
if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) {
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds));
}
std::shared_ptr<http::request<http::string_body>> reqPtr(new http::request<http::string_body>(std::move(req)));
CCAPI_LOGGER_TRACE("before async_write");
@@ -592,7 +678,7 @@ class Service : public std::enable_shared_from_this<Service> {
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "write", {request.getCorrelationId()}, eventQueuePtr);
this->httpConnectionPool.purge();
this->httpConnectionPool[request.getLocalIpAddress()][request.getBaseUrl()].clear();
auto now = UtilTime::now();
auto req = this->convertRequest(request, now);
retry.numRetry += 1;
@@ -609,32 +695,17 @@ class Service : public std::enable_shared_from_this<Service> {
beast::bind_front_handler(&Service::onRead_2, shared_from_this(), httpConnectionPtr, request, reqPtr, retry, bufferPtr, resPtr, eventQueuePtr));
CCAPI_LOGGER_TRACE("after async_read");
}
void setHttpConnectionPoolPurgeTimer() {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(5000)));
timerPtr->async_wait([that = shared_from_this()](ErrorCode const& ec) {
auto now = UtilTime::now();
if (ec) {
that->onError(Event::Type::SESSION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
if (std::chrono::duration_cast<std::chrono::milliseconds>(now - that->lastHttpConnectionPoolPushBackTp).count() >
that->sessionOptions.httpConnectionPoolIdleTimeoutMilliSeconds) {
that->httpConnectionPool.purge();
}
that->setHttpConnectionPoolPurgeTimer();
}
});
this->httpConnectionPoolPurgeTimer = timerPtr;
}
void onRead_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, std::shared_ptr<http::request<http::string_body>> reqPtr, HttpRetry retry,
std::shared_ptr<beast::flat_buffer> bufferPtr, std::shared_ptr<http::response<http::string_body>> resPtr, Queue<Event>* eventQueuePtr,
beast::error_code ec, std::size_t bytes_transferred) {
CCAPI_LOGGER_TRACE("async_read callback start");
CCAPI_LOGGER_TRACE("local endpoint has address " + beast::get_lowest_layer(*httpConnectionPtr->streamPtr).socket().local_endpoint().address().to_string());
auto now = UtilTime::now();
boost::ignore_unused(bytes_transferred);
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "read", {request.getCorrelationId()}, eventQueuePtr);
this->httpConnectionPool.purge();
this->httpConnectionPool[request.getLocalIpAddress()][request.getBaseUrl()].clear();
auto now = UtilTime::now();
auto req = this->convertRequest(request, now);
retry.numRetry += 1;
@@ -642,19 +713,17 @@ class Service : public std::enable_shared_from_this<Service> {
return;
}
if (!this->sessionOptions.enableOneHttpConnectionPerRequest) {
try {
if (std::chrono::duration_cast<std::chrono::seconds>(this->lastHttpConnectionPoolPushBackTp.time_since_epoch()).count() == 0 &&
this->sessionOptions.httpConnectionPoolIdleTimeoutMilliSeconds > 0) {
this->setHttpConnectionPoolPurgeTimer();
}
this->httpConnectionPool.pushBack(std::move(httpConnectionPtr));
this->lastHttpConnectionPoolPushBackTp = now;
CCAPI_LOGGER_TRACE("pushed back httpConnectionPtr " + toString(*httpConnectionPtr) + " to pool");
} catch (const std::runtime_error& e) {
if (e.what() != this->httpConnectionPool.EXCEPTION_QUEUE_FULL) {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
}
httpConnectionPtr->lastReceiveDataTp = now;
const auto& localIpAddress = request.getLocalIpAddress();
const auto& requestBaseUrl = request.getBaseUrl();
if (this->sessionOptions.httpConnectionPoolMaxSize > 0 &&
this->httpConnectionPool[localIpAddress][requestBaseUrl].size() >= this->sessionOptions.httpConnectionPoolMaxSize) {
CCAPI_LOGGER_TRACE("httpConnectionPool is full for localIpAddress = " + localIpAddress + ", requestBaseUrl = " + toString(requestBaseUrl));
this->httpConnectionPool[localIpAddress][requestBaseUrl].pop_front();
}
this->httpConnectionPool[localIpAddress][requestBaseUrl].push_back(httpConnectionPtr);
CCAPI_LOGGER_TRACE("pushed back httpConnectionPtr " + toString(*httpConnectionPtr) + " to httpConnectionPool for localIpAddress = " + localIpAddress +
", requestBaseUrl = " + toString(requestBaseUrl));
}
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
{
@@ -737,7 +806,13 @@ class Service : public std::enable_shared_from_this<Service> {
CCAPI_LOGGER_TRACE("retry = " + toString(retry));
if (retry.numRetry <= this->sessionOptions.httpMaxNumRetry && retry.numRedirect <= this->sessionOptions.httpMaxNumRedirect) {
try {
if (this->sessionOptions.enableOneHttpConnectionPerRequest || this->httpConnectionPool.empty()) {
const auto& localIpAddress = request.getLocalIpAddress();
const auto& requestBaseUrl = request.getBaseUrl();
if (this->sessionOptions.enableOneHttpConnectionPerRequest || this->httpConnectionPool[localIpAddress][requestBaseUrl].empty() ||
std::chrono::duration_cast<std::chrono::seconds>(request.getTimeSent() -
this->httpConnectionPool[localIpAddress][requestBaseUrl].back()->lastReceiveDataTp)
.count() >= this->sessionOptions.httpConnectionKeepAliveTimeoutSeconds) {
this->httpConnectionPool[localIpAddress][requestBaseUrl].clear();
std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(nullptr);
try {
streamPtr = this->createStream<beast::ssl_stream<beast::tcp_stream>>(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr,
@@ -747,32 +822,24 @@ class Service : public std::enable_shared_from_this<Service> {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "create stream", {request.getCorrelationId()}, eventQueuePtr);
return;
}
std::shared_ptr<HttpConnection> httpConnectionPtr(new HttpConnection(this->hostRest, this->portRest, streamPtr));
CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr));
this->performRequest(httpConnectionPtr, request, req, retry, eventQueuePtr);
} else {
std::shared_ptr<HttpConnection> httpConnectionPtr(nullptr);
try {
httpConnectionPtr = std::move(this->httpConnectionPool.popBack());
CCAPI_LOGGER_TRACE("about to perform request with existing httpConnectionPtr " + toString(*httpConnectionPtr));
this->startWrite_2(httpConnectionPtr, request, req, retry, eventQueuePtr);
} catch (const std::runtime_error& e) {
if (e.what() != this->httpConnectionPool.EXCEPTION_QUEUE_EMPTY) {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
}
std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(nullptr);
try {
streamPtr = this->createStream<beast::ssl_stream<beast::tcp_stream>>(this->serviceContextPtr->ioContextPtr,
this->serviceContextPtr->sslContextPtr, this->hostRest);
} catch (const beast::error_code& ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "create stream", {request.getCorrelationId()}, eventQueuePtr);
return;
}
httpConnectionPtr = std::make_shared<HttpConnection>(this->hostRest, this->portRest, streamPtr);
CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr));
this->performRequest(httpConnectionPtr, request, req, retry, eventQueuePtr);
std::string host, port;
if (requestBaseUrl.empty()) {
host = this->hostRest;
port = this->portRest;
} else {
host = request.getHost();
port = request.getPort();
}
std::shared_ptr<HttpConnection> httpConnectionPtr(new HttpConnection(host, port, streamPtr));
CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr) + " for localIpAddress = " + localIpAddress +
", requestBaseUrl = " + toString(requestBaseUrl));
this->performRequestWithNewHttpConnection(httpConnectionPtr, request, req, retry, eventQueuePtr);
} else {
std::shared_ptr<HttpConnection> httpConnectionPtr = this->httpConnectionPool[localIpAddress][requestBaseUrl].back();
this->httpConnectionPool[localIpAddress][requestBaseUrl].pop_back();
CCAPI_LOGGER_TRACE("about to perform request with existing httpConnectionPtr " + toString(*httpConnectionPtr) +
" for localIpAddress = " + localIpAddress + ", requestBaseUrl = " + toString(requestBaseUrl));
this->startWrite_2(httpConnectionPtr, request, req, retry, eventQueuePtr);
}
} catch (const std::exception& e) {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
@@ -805,7 +872,7 @@ class Service : public std::enable_shared_from_this<Service> {
} else {
req.keep_alive(true);
}
req.set(http::field::host, this->hostRest);
req.set(http::field::host, request.getBaseUrl().empty() ? this->hostRest : request.getHost());
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
this->convertRequestForRest(req, request, now, symbolId, credential);
CCAPI_LOGGER_FUNCTION_EXIT;
@@ -821,14 +888,15 @@ class Service : public std::enable_shared_from_this<Service> {
}
}
}
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {}) {
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param, const std::map<std::string, std::string> standardizationMap = {},
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) {
int i = 0;
for (const auto& kv : param) {
std::string key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
queryString += key;
queryString += "=";
queryString += Url::urlEncode(kv.second);
std::string value = conversionMap.find(kv.first) != conversionMap.end() ? conversionMap.at(kv.first)(kv.second) : kv.second;
queryString += Url::urlEncode(value);
queryString += "&";
++i;
}
@@ -857,7 +925,7 @@ class Service : public std::enable_shared_from_this<Service> {
std::string methodStringUpper = UtilString::toUpper(methodString);
return http::string_to_verb(methodStringUpper);
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
SslContextPtr onTlsInit(wspp::connection_hdl hdl) { return this->serviceContextPtr->sslContextPtr; }
WsConnection& getWsConnectionFromConnectionPtr(TlsClient::connection_ptr connectionPtr) {
return this->wsConnectionByIdMap.at(this->connectionAddressToString(connectionPtr));
@@ -954,7 +1022,7 @@ class Service : public std::enable_shared_from_this<Service> {
if (this->connectRetryOnFailTimerByConnectionIdMap.find(thisWsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) {
this->connectRetryOnFailTimerByConnectionIdMap.at(thisWsConnection.id)->cancel();
}
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000)));
TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000)));
timerPtr->async_wait([thisWsConnection, that = shared_from_this(), urlBase](ErrorCode const& ec) {
if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) {
if (ec) {
@@ -1120,11 +1188,11 @@ class Service : public std::enable_shared_from_this<Service> {
std::function<void(wspp::connection_hdl, ErrorCode&)> pingMethod) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method));
auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method];
auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds));
if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) {
auto pingIntervalMilliseconds = this->pingIntervalMillisecondsByMethodMap[method];
auto pongTimeoutMilliseconds = this->pongTimeoutMillisecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliseconds = " + toString(pingIntervalMilliseconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliseconds = " + toString(pongTimeoutMilliseconds));
if (pingIntervalMilliseconds <= pongTimeoutMilliseconds) {
return;
}
if (wsConnection.status == WsConnection::Status::OPEN) {
@@ -1133,8 +1201,8 @@ class Service : public std::enable_shared_from_this<Service> {
this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel();
}
TimerPtr timerPtr(
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds)));
timerPtr->async_wait([wsConnection, that = shared_from_this(), hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliseconds - pongTimeoutMilliseconds)));
timerPtr->async_wait([wsConnection, that = shared_from_this(), hdl, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) {
if (ec) {
CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", ping timer error: " + ec.message());
@@ -1146,7 +1214,7 @@ class Service : public std::enable_shared_from_this<Service> {
if (ec) {
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping");
}
if (pongTimeoutMilliSeconds <= 0) {
if (pongTimeoutMilliseconds <= 0) {
return;
}
if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() &&
@@ -1154,8 +1222,8 @@ class Service : public std::enable_shared_from_this<Service> {
that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) {
that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel();
}
TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds)));
timerPtr->async_wait([wsConnection, that, hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
TimerPtr timerPtr(new net::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliseconds)));
timerPtr->async_wait([wsConnection, that, hdl, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) {
if (ec) {
CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", pong time out timer error: " + ec.message());
@@ -1167,7 +1235,7 @@ class Service : public std::enable_shared_from_this<Service> {
that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) !=
that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() &&
std::chrono::duration_cast<std::chrono::milliseconds>(now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method))
.count() >= pongTimeoutMilliSeconds) {
.count() >= pongTimeoutMilliseconds) {
auto thisWsConnection = wsConnection;
ErrorCode ec;
that->close(thisWsConnection, hdl, websocketpp::close::status::normal, "pong timeout", ec);
@@ -1213,29 +1281,40 @@ class Service : public std::enable_shared_from_this<Service> {
WsConnection& wsConnection = *wsConnectionPtr;
wsConnection.status = WsConnection::Status::CONNECTING;
CCAPI_LOGGER_DEBUG("connection initialization on id " + wsConnection.id);
std::string url = wsConnection.url;
std::string url = wsConnection.getUrl();
CCAPI_LOGGER_DEBUG("url = " + url);
this->startResolveWs(wsConnectionPtr);
CCAPI_LOGGER_FUNCTION_EXIT;
}
void startResolveWs(std::shared_ptr<WsConnection> wsConnectionPtr) {
std::shared_ptr<tcp::resolver> newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr));
CCAPI_LOGGER_TRACE("wsConnectionPtr = " + wsConnectionPtr->toString());
CCAPI_LOGGER_TRACE("wsConnectionPtr->host = " + wsConnectionPtr->host);
CCAPI_LOGGER_TRACE("wsConnectionPtr->port = " + wsConnectionPtr->port);
newResolverPtr->async_resolve(wsConnectionPtr->host, wsConnectionPtr->port,
beast::bind_front_handler(&Service::onResolveWs, shared_from_this(), wsConnectionPtr, newResolverPtr));
}
void onResolveWs(std::shared_ptr<WsConnection> wsConnectionPtr, std::shared_ptr<tcp::resolver> 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);
CCAPI_LOGGER_TRACE("dns resolve fail");
this->onFail(wsConnectionPtr);
return;
}
this->startConnectWs(wsConnectionPtr, this->sessionOptions.websocketConnectTimeoutMilliSeconds, tcpNewResolverResultsWs);
this->startConnectWs(wsConnectionPtr, this->sessionOptions.websocketConnectTimeoutMilliseconds, tcpNewResolverResultsWs);
}
void startConnectWs(std::shared_ptr<WsConnection> wsConnectionPtr, long timeoutMilliSeconds, tcp::resolver::results_type tcpResolverResults) {
void startConnectWs(std::shared_ptr<WsConnection> wsConnectionPtr, long timeoutMilliseconds, tcp::resolver::results_type tcpResolverResults) {
beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>& stream = *wsConnectionPtr->streamPtr;
if (timeoutMilliSeconds > 0) {
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliSeconds));
if (timeoutMilliseconds > 0) {
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliseconds));
}
// Set SNI Hostname (many hosts need this to handshake successfully)
CCAPI_LOGGER_TRACE("wsConnectionPtr->host = " + wsConnectionPtr->host)
if (!SSL_set_tlsext_host_name(stream.next_layer().native_handle(), wsConnectionPtr->host.c_str())) {
beast::error_code ec{static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()};
CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message());
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "set SNI Hostname", wsConnectionPtr->correlationIdList);
return;
}
CCAPI_LOGGER_TRACE("before async_connect");
beast::get_lowest_layer(stream).async_connect(tcpResolverResults, beast::bind_front_handler(&Service::onConnectWs, shared_from_this(), wsConnectionPtr));
@@ -1250,7 +1329,9 @@ class Service : public std::enable_shared_from_this<Service> {
}
CCAPI_LOGGER_TRACE("connected");
CCAPI_LOGGER_TRACE("ep.port() = " + std::to_string(ep.port()));
wsConnectionPtr->hostHttpHeaderValue = this->hostWs + ':' + std::to_string(ep.port());
wsConnectionPtr->hostHttpHeaderValue =
this->hostHttpHeaderValueIgnorePort ? wsConnectionPtr->host : wsConnectionPtr->host + ':' + std::to_string(ep.port());
CCAPI_LOGGER_TRACE("wsConnectionPtr->hostHttpHeaderValue = " + wsConnectionPtr->hostHttpHeaderValue);
beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>& stream = *wsConnectionPtr->streamPtr;
beast::get_lowest_layer(stream).socket().set_option(tcp::no_delay(true));
CCAPI_LOGGER_TRACE("before ssl async_handshake");
@@ -1260,15 +1341,15 @@ class Service : public std::enable_shared_from_this<Service> {
void onSslHandshakeWs(std::shared_ptr<WsConnection> wsConnectionPtr, beast::error_code ec) {
CCAPI_LOGGER_TRACE("ssl async_handshake callback start");
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "ssl handshake", wsConnectionPtr->correlationIdList);
CCAPI_LOGGER_TRACE("ssl handshake fail");
this->onFail(wsConnectionPtr);
return;
}
CCAPI_LOGGER_TRACE("ssl handshaked");
beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>& stream = *wsConnectionPtr->streamPtr;
beast::get_lowest_layer(stream).expires_never();
beast::websocket::stream_base::timeout opt{std::chrono::milliseconds(this->sessionOptions.websocketConnectTimeoutMilliSeconds),
std::chrono::milliseconds(this->sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds), true};
beast::websocket::stream_base::timeout opt{std::chrono::milliseconds(this->sessionOptions.websocketConnectTimeoutMilliseconds),
std::chrono::milliseconds(this->sessionOptions.pongWebsocketProtocolLevelTimeoutMilliseconds), true};
stream.set_option(opt);
stream.set_option(beast::websocket::stream_base::decorator([wsConnectionPtr](beast::websocket::request_type& req) {
@@ -1285,8 +1366,8 @@ class Service : public std::enable_shared_from_this<Service> {
void onWsHandshakeWs(std::shared_ptr<WsConnection> wsConnectionPtr, beast::error_code ec) {
CCAPI_LOGGER_TRACE("ws async_handshake callback start");
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "ws handshake", wsConnectionPtr->correlationIdList);
CCAPI_LOGGER_TRACE("ws handshake fail");
this->onFail(wsConnectionPtr);
return;
}
CCAPI_LOGGER_TRACE("ws handshaked");
@@ -1295,7 +1376,9 @@ class Service : public std::enable_shared_from_this<Service> {
CCAPI_LOGGER_TRACE("about to start read");
this->startReadWs(wsConnectionPtr);
auto& stream = *wsConnectionPtr->streamPtr;
stream.control_callback(beast::bind_front_handler(&Service::onControlCallback, shared_from_this(), wsConnectionPtr));
stream.control_callback([wsConnectionPtr, that = shared_from_this()](boost::beast::websocket::frame_type kind, boost::beast::string_view payload) {
that->onControlCallback(wsConnectionPtr, kind, payload);
});
}
void startReadWs(std::shared_ptr<WsConnection> wsConnectionPtr) {
auto& stream = *wsConnectionPtr->streamPtr;
@@ -1305,7 +1388,7 @@ class Service : public std::enable_shared_from_this<Service> {
stream.async_read(readMessageBuffer, beast::bind_front_handler(&Service::onReadWs, shared_from_this(), wsConnectionPtr));
CCAPI_LOGGER_TRACE("after async_read");
}
void onReadWs(std::shared_ptr<WsConnection> wsConnectionPtr, const boost::system::error_code& ec, std::size_t n) {
void onReadWs(std::shared_ptr<WsConnection> wsConnectionPtr, const ErrorCode& ec, std::size_t n) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("n = " + toString(n));
auto now = UtilTime::now();
@@ -1339,7 +1422,7 @@ class Service : public std::enable_shared_from_this<Service> {
this->onMessage(wsConnectionPtr, (const char*)readMessageBuffer.data().data(), readMessageBuffer.size());
readMessageBuffer.consume(readMessageBuffer.size());
this->startReadWs(wsConnectionPtr);
this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now);
this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now, false);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) {
@@ -1348,7 +1431,7 @@ class Service : public std::enable_shared_from_this<Service> {
WsConnection& wsConnection = *wsConnectionPtr;
wsConnection.status = WsConnection::Status::OPEN;
CCAPI_LOGGER_INFO("connection " + toString(wsConnection) + " established");
auto urlBase = UtilString::split(wsConnection.url, "?").at(0);
auto urlBase = UtilString::split(wsConnection.getUrl(), "?").at(0);
this->connectNumRetryOnFailByConnectionUrlMap[urlBase] = 0;
Event event;
event.setType(Event::Type::SESSION_STATUS);
@@ -1360,7 +1443,7 @@ class Service : public std::enable_shared_from_this<Service> {
message.setCorrelationIdList(correlationIdList);
Element element;
element.insert(CCAPI_CONNECTION_ID, wsConnection.id);
element.insert(CCAPI_CONNECTION_URL, wsConnection.url);
element.insert(CCAPI_CONNECTION_URL, wsConnection.getUrl());
message.setElementList({element});
event.setMessageList({message});
this->eventHandler(event, nullptr);
@@ -1386,6 +1469,7 @@ class Service : public std::enable_shared_from_this<Service> {
memcpy(writeMessageBuffer.data() + n, data, dataSize);
writeMessageBufferBoundary.push_back(dataSize);
n += dataSize;
CCAPI_LOGGER_TRACE("connectionId = " + connectionId);
CCAPI_LOGGER_DEBUG("about to send " + std::string(data, dataSize));
CCAPI_LOGGER_TRACE("writeMessageBufferWrittenLength = " + toString(writeMessageBufferWrittenLength));
if (writeMessageBufferWrittenLength == 0) {
@@ -1401,10 +1485,10 @@ class Service : public std::enable_shared_from_this<Service> {
CCAPI_LOGGER_TRACE("before async_write");
CCAPI_LOGGER_TRACE("numBytesToWrite = " + toString(numBytesToWrite));
stream.binary(false);
stream.async_write(boost::asio::buffer(data, numBytesToWrite), beast::bind_front_handler(&Service::onWriteWs, shared_from_this(), wsConnectionPtr));
stream.async_write(net::buffer(data, numBytesToWrite), beast::bind_front_handler(&Service::onWriteWs, shared_from_this(), wsConnectionPtr));
CCAPI_LOGGER_TRACE("after async_write");
}
void onWriteWs(std::shared_ptr<WsConnection> wsConnectionPtr, const boost::system::error_code& ec, std::size_t n) {
void onWriteWs(std::shared_ptr<WsConnection> wsConnectionPtr, const ErrorCode& ec, std::size_t n) {
CCAPI_LOGGER_FUNCTION_ENTER;
auto& connectionId = wsConnectionPtr->id;
auto& writeMessageBuffer = this->writeMessageBufferByConnectionIdMap[connectionId];
@@ -1427,13 +1511,13 @@ class Service : public std::enable_shared_from_this<Service> {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "connection " + toString(wsConnection) + " has failed before opening");
WsConnection thisWsConnection = wsConnection;
this->wsConnectionByIdMap.erase(thisWsConnection.id);
auto urlBase = UtilString::split(thisWsConnection.url, "?").at(0);
auto urlBase = UtilString::split(thisWsConnection.getUrl(), "?").at(0);
long seconds = std::round(UtilAlgorithm::exponentialBackoff(1, 1, 2, std::min(this->connectNumRetryOnFailByConnectionUrlMap[urlBase], 6)));
CCAPI_LOGGER_INFO("about to set timer for " + toString(seconds) + " seconds");
if (this->connectRetryOnFailTimerByConnectionIdMap.find(thisWsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) {
this->connectRetryOnFailTimerByConnectionIdMap.at(thisWsConnection.id)->cancel();
}
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000)));
TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000)));
timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), urlBase](ErrorCode const& ec) {
WsConnection& thisWsConnection = *wsConnectionPtr;
if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) {
@@ -1460,8 +1544,7 @@ class Service : public std::enable_shared_from_this<Service> {
std::shared_ptr<WsConnection> thatWsConnectionPtr = wsConnectionPtr;
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = this->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(this->serviceContextPtr->ioContextPtr,
this->serviceContextPtr->sslContextPtr, this->hostWs);
streamPtr = this->createWsStream(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr);
} catch (const beast::error_code& ec) {
throw ec;
}
@@ -1520,7 +1603,7 @@ class Service : public std::enable_shared_from_this<Service> {
message.setType(Message::Type::SESSION_CONNECTION_DOWN);
Element element;
element.insert(CCAPI_CONNECTION_ID, wsConnection.id);
element.insert(CCAPI_CONNECTION_URL, wsConnection.url);
element.insert(CCAPI_CONNECTION_URL, wsConnection.getUrl());
element.insert(CCAPI_REASON, reason);
message.setElementList({element});
std::vector<std::string> correlationIdList;
@@ -1602,38 +1685,42 @@ class Service : public std::enable_shared_from_this<Service> {
}
void onPong(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view payload) {
auto now = UtilTime::now();
this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now);
this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now, true);
}
void onPongByMethod(PingPongMethod method, std::shared_ptr<WsConnection> wsConnectionPtr, const TimePoint& timeReceived) {
void onPongByMethod(PingPongMethod method, std::shared_ptr<WsConnection> wsConnectionPtr, const TimePoint& timeReceived, bool truePong) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE(pingPongMethodToString(method) + ": received a pong from " + toString(*wsConnectionPtr));
CCAPI_LOGGER_TRACE(pingPongMethodToString(method) + ": received a " + (truePong ? "websocket protocol pong" : "data message") + " from " +
toString(*wsConnectionPtr));
this->lastPongTpByMethodByConnectionIdMap[wsConnectionPtr->id][method] = timeReceived;
CCAPI_LOGGER_FUNCTION_EXIT;
}
void onPing(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view payload) {
CCAPI_LOGGER_FUNCTION_ENTER;
auto now = UtilTime::now();
CCAPI_LOGGER_TRACE("received a ping from " + toString(*wsConnectionPtr));
this->lastPongTpByMethodByConnectionIdMap[wsConnectionPtr->id][PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = now;
CCAPI_LOGGER_FUNCTION_EXIT;
}
void send(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view payload, ErrorCode& ec) {
this->writeMessage(wsConnectionPtr, payload.data(), payload.length());
}
void ping(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view payload, ErrorCode& ec) {
if (!this->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id]) {
if (!this->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id]) {
auto& stream = *wsConnectionPtr->streamPtr;
stream.async_ping("", [that = this, wsConnectionPtr](ErrorCode const& ec) { that->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id] = false; });
this->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id] = true;
stream.async_ping(
"", [that = this, wsConnectionPtr](ErrorCode const& ec) { that->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id] = false; });
this->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id] = true;
}
}
virtual void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) {}
void setPingPongTimer(PingPongMethod method, std::shared_ptr<WsConnection> wsConnectionPtr, std::function<void(ErrorCode&)> pingMethod) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method));
auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method];
auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds));
if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) {
auto pingIntervalMilliseconds = this->pingIntervalMillisecondsByMethodMap[method];
auto pongTimeoutMilliseconds = this->pongTimeoutMillisecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliseconds = " + toString(pingIntervalMilliseconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliseconds = " + toString(pongTimeoutMilliseconds));
if (pingIntervalMilliseconds <= pongTimeoutMilliseconds) {
return;
}
WsConnection& wsConnection = *wsConnectionPtr;
@@ -1643,8 +1730,8 @@ class Service : public std::enable_shared_from_this<Service> {
this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel();
}
TimerPtr timerPtr(
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds)));
timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliseconds - pongTimeoutMilliseconds)));
timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
WsConnection& wsConnection = *wsConnectionPtr;
if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) {
if (ec) {
@@ -1657,7 +1744,7 @@ class Service : public std::enable_shared_from_this<Service> {
if (ec) {
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping");
}
if (pongTimeoutMilliSeconds <= 0) {
if (pongTimeoutMilliseconds <= 0) {
return;
}
if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() &&
@@ -1665,8 +1752,8 @@ class Service : public std::enable_shared_from_this<Service> {
that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) {
that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel();
}
TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds)));
timerPtr->async_wait([wsConnectionPtr, that, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
TimerPtr timerPtr(new net::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliseconds)));
timerPtr->async_wait([wsConnectionPtr, that, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
WsConnection& wsConnection = *wsConnectionPtr;
if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) {
if (ec) {
@@ -1679,7 +1766,7 @@ class Service : public std::enable_shared_from_this<Service> {
that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) !=
that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() &&
std::chrono::duration_cast<std::chrono::milliseconds>(now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method))
.count() >= pongTimeoutMilliSeconds) {
.count() >= pongTimeoutMilliseconds) {
auto thisWsConnectionPtr = wsConnectionPtr;
ErrorCode ec;
that->close(thisWsConnectionPtr, beast::websocket::close_code::normal,
@@ -1705,8 +1792,17 @@ class Service : public std::enable_shared_from_this<Service> {
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
std::string convertParamTimeSecondsToTimeMilliseconds(const std::string& input) {
auto dotPosition = input.find('.');
if (dotPosition == std::string::npos) {
return std::to_string(std::stoll(input) * 1000);
} else {
}
return std::to_string(std::stoll(input.substr(0, dotPosition)) * 1000 + std::stoll(UtilString::rightPadTo(input.substr(dotPosition + 1, 3), 3, '0')));
}
virtual void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived) {}
#endif
bool hostHttpHeaderValueIgnorePort{};
std::string apiKeyName;
std::string apiSecretName;
std::string exchangeName;
@@ -1721,13 +1817,11 @@ class Service : public std::enable_shared_from_this<Service> {
std::string portRest;
std::string hostWs;
std::string portWs;
tcp::resolver::results_type tcpResolverResultsRest, tcpResolverResultsWs;
Queue<std::shared_ptr<HttpConnection>> httpConnectionPool;
TimePoint lastHttpConnectionPoolPushBackTp{std::chrono::seconds{0}};
TimerPtr httpConnectionPoolPurgeTimer;
// tcp::resolver::results_type tcpResolverResultsRest, tcpResolverResultsWs;
std::map<std::string, std::map<std::string, std::deque<std::shared_ptr<HttpConnection>>>> httpConnectionPool;
std::map<std::string, std::string> credentialDefault;
std::map<std::string, TimerPtr> sendRequestDelayTimerByCorrelationIdMap;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
std::map<std::string, WsConnection> wsConnectionByIdMap;
#else
std::map<std::string, std::shared_ptr<WsConnection>> wsConnectionByIdMap; // TODO(cryptochassis): for consistency, to be renamed to wsConnectionPtrByIdMap
@@ -1736,15 +1830,15 @@ class Service : public std::enable_shared_from_this<Service> {
std::map<std::string, size_t> writeMessageBufferWrittenLengthByConnectionIdMap;
std::map<std::string, std::vector<size_t>> writeMessageBufferBoundaryByConnectionIdMap;
#endif
std::map<std::string, bool> wsConnectionPendingPingingByIdMap;
std::map<std::string, bool> wsConnectionPendingPingingByConnectionIdMap;
std::map<std::string, bool> shouldProcessRemainingMessageOnClosingByConnectionIdMap;
std::map<std::string, int> connectNumRetryOnFailByConnectionUrlMap;
std::map<std::string, TimerPtr> connectRetryOnFailTimerByConnectionIdMap;
std::map<std::string, std::map<PingPongMethod, TimePoint>> lastPongTpByMethodByConnectionIdMap;
std::map<std::string, std::map<PingPongMethod, TimerPtr>> pingTimerByMethodByConnectionIdMap;
std::map<std::string, std::map<PingPongMethod, TimerPtr>> pongTimeOutTimerByMethodByConnectionIdMap;
std::map<PingPongMethod, long> pingIntervalMilliSecondsByMethodMap;
std::map<PingPongMethod, long> pongTimeoutMilliSecondsByMethodMap;
std::map<PingPongMethod, long> pingIntervalMillisecondsByMethodMap;
std::map<PingPongMethod, long> pongTimeoutMillisecondsByMethodMap;
std::atomic<bool> shouldContinue{true};
std::map<std::string, std::map<std::string, std::string>> extraPropertyByConnectionIdMap;
bool enableCheckPingPongWebsocketProtocolLevel{};
@@ -1757,7 +1851,7 @@ class Service : public std::enable_shared_from_this<Service> {
(defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \
defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \
(defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_BITMART))
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
struct monostate {};
websocketpp::extensions_workaround::permessage_deflate::enabled<monostate> inflater;
#else
@@ -1,6 +1,6 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#include "ccapi_cpp/ccapi_logger.h"
#include "websocketpp/client.hpp"
#include "websocketpp/common/connection_hdl.hpp"
@@ -77,23 +77,46 @@ namespace ccapi {
class ServiceContext CCAPI_FINAL {
public:
typedef boost::asio::io_context IoContext;
typedef std::shared_ptr<boost::asio::io_context> IoContextPtr;
typedef boost::asio::io_context* IoContextPtr;
typedef boost::asio::executor_work_guard<boost::asio::io_context::executor_type> ExecutorWorkGuard;
typedef std::shared_ptr<ExecutorWorkGuard> ExecutorWorkGuardPtr;
typedef ExecutorWorkGuard* ExecutorWorkGuardPtr;
typedef boost::asio::ssl::context SslContext;
typedef std::shared_ptr<SslContext> SslContextPtr;
typedef SslContext* SslContextPtr;
ServiceContext() {
this->ioContextPtr = new boost::asio::io_context();
this->executorWorkGuardPtr = new ExecutorWorkGuard(this->ioContextPtr->get_executor());
this->sslContextPtr = new SslContext(SslContext::tls_client);
// this->sslContextPtr->set_options(SslContext::default_workarounds | SslContext::no_sslv2 | SslContext::no_sslv3 | SslContext::single_dh_use);
this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none);
// TODO(cryptochassis): verify ssl certificate to strengthen security
// https://github.com/boostorg/asio/blob/develop/example/cpp03/ssl/client.cpp
}
#ifndef SWIG
ServiceContext(IoContextPtr ioContextPtr) {
this->ioContextPtr = ioContextPtr;
this->executorWorkGuardPtr = new ExecutorWorkGuard(this->ioContextPtr->get_executor());
this->sslContextPtr = new SslContext(SslContext::tls_client);
this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none);
}
ServiceContext(SslContextPtr sslContextPtr) {
this->ioContextPtr = new boost::asio::io_context();
this->executorWorkGuardPtr = new ExecutorWorkGuard(this->ioContextPtr->get_executor());
this->sslContextPtr = sslContextPtr;
this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none);
}
ServiceContext(IoContextPtr ioContextPtr, SslContextPtr sslContextPtr) {
this->ioContextPtr = ioContextPtr;
this->executorWorkGuardPtr = new ExecutorWorkGuard(this->ioContextPtr->get_executor());
this->sslContextPtr = sslContextPtr;
this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none);
}
#endif
ServiceContext(const ServiceContext&) = delete;
ServiceContext& operator=(const ServiceContext&) = delete;
virtual ~ServiceContext() {
// delete this->ExecutorWorkGuardPtr;
// delete this->ioContextPtr;
// delete this->sslContextPtr;
delete this->executorWorkGuardPtr;
delete this->ioContextPtr;
delete this->sslContextPtr;
}
void start() {
CCAPI_LOGGER_INFO("about to start client asio io_context run loop");
@@ -104,9 +127,12 @@ class ServiceContext CCAPI_FINAL {
this->executorWorkGuardPtr->reset();
this->ioContextPtr->stop();
}
IoContextPtr ioContextPtr{new IoContext()};
ExecutorWorkGuardPtr executorWorkGuardPtr{new ExecutorWorkGuard(ioContextPtr->get_executor())};
SslContextPtr sslContextPtr{new SslContext(SslContext::tls_client)};
IoContextPtr ioContextPtr{nullptr};
ExecutorWorkGuardPtr executorWorkGuardPtr{nullptr};
SslContextPtr sslContextPtr{nullptr};
// IoContextPtr ioContextPtr{new IoContext()};
// ExecutorWorkGuardPtr executorWorkGuardPtr{new ExecutorWorkGuard(ioContextPtr->get_executor())};
// SslContextPtr sslContextPtr{new SslContext(SslContext::tls_client)};
};
} /* namespace ccapi */